问:
Monospace font and custom font (Marshmallow)
I recently made an RPG with ASCII-arts and since android 5.0 there arts are messed up.

I use a custom font to display it, defined with this :

```<code>Typeface face= Typeface.createFromAsset(getAssets(),"fonts/courier.ttf");
    etiqPlateau.setTypeface(face);
</code>```

I used the android:fontFamily="monospace" setting in the xml but it looks like the TypeFace defined in java code overrides the xml setting. Is it possible to define the attributes of a typeface in xml or at least define the use of monospaced font in 5.0+ ? Help!

In Android 4.4 (Picture)

In Android 6.0 (Picture)

EDIT --
Even when I use the android:fontfamily on XML without setting up a typeface, android 5.0+ messes up the monospace font.

答:
you can also try this

```<code>public static class FontCache {

    private static HashMap<String, Typeface> fontCache = new HashMap<>();

    public static Typeface getTypeface(String fontname, Context context) {
        Typeface typeface = fontCache.get(fontname);

        if (typeface == null) {
            try {
                typeface = Typeface.createFromAsset(context.getAssets(), fontname);
            } catch (Exception e) {
                return null;
            }

            fontCache.put(fontname, typeface);
        }

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

Typeface customFont = FontCache.getTypeface("your custom downloaded
  font.ttf", clContext);

```<code>code snippet:
Typeface customFont = FontCache.getTypeface("chyga.ttf", clContext);
yourTextView.setTypeface(customFont);
</code>```

Body:
I recently made an RPG with ASCII-arts and since android 5.0 there arts are messed up.

I use a custom font to display it, defined with this :

Typeface face= Typeface.createFromAsset(getAssets(),"fonts/courier.ttf");
    etiqPlateau.setTypeface(face);

I used the android:fontFamily="monospace" setting in the xml but it looks like the TypeFace defined in java code overrides the xml setting. Is it possible to define the attributes of a typeface in xml or at least define the use of monospaced font in 5.0+ ? Help!

In Android 4.4 (Picture)

In Android 6.0 (Picture)

EDIT --
Even when I use the android:fontfamily on XML without setting up a typeface, android 5.0+ messes up the monospace font.

Body:
you can also try this

public static class FontCache {

    private static HashMap<String, Typeface> fontCache = new HashMap<>();

    public static Typeface getTypeface(String fontname, Context context) {
        Typeface typeface = fontCache.get(fontname);

        if (typeface == null) {
            try {
                typeface = Typeface.createFromAsset(context.getAssets(), fontname);
            } catch (Exception e) {
                return null;
            }

            fontCache.put(fontname, typeface);
        }

        return typeface;
    }
}

Typeface customFont = FontCache.getTypeface("your custom downloaded
  font.ttf", clContext);

code snippet:
Typeface customFont = FontCache.getTypeface("chyga.ttf", clContext);
yourTextView.setTypeface(customFont);


来源: stackexchange

问:
Multiplying Functions in Python
I'm writing a short program for my class and I'm stuck on the last portion. When I run the program, everything functions appropriately up until I get to the end of the code where I try to multiply the cost of two separate functions in order to define another. How can I rectify this?

Here is the code in full:

```<code>def main():
    wall_space = float(input('Enter amount of wall space in square feet: '))
    gallon_price = float(input('Enter the cost of paint per gallon: '))
    rate_factor = wall_space / 115
    total_gallons(rate_factor, 1)
    total_labor_cost(rate_factor, 8)
    total_gal_cost(rate_factor, gallon_price)
    total_hourly_cost(rate_factor, 20)
    total_cost(total_hourly_cost, total_gal_cost)
    print()

def total_gallons(rate1, rate2):
    result = rate1 * rate2
    print('The number of gallons of required is: ', result)
    print()

def total_labor_cost(rate1, rate2):
    result = rate1 * rate2
    print('The hours of labor required are: ', result)
    print()

def total_gal_cost(rate1, rate2):
    result = rate1 * rate2
    print('The cost of the paint in total is: ', result)
    print()

def total_hourly_cost(rate1, rate2):
    result = rate1 * rate2
    print('The total labor charges are: ', result)
    print()

def total_cost(rate1, rate2):
    result = rate1 * rate2
    print('This is the total cost of the paint job: ', result)
    print()

main()
</code>```

I'm desperate here guys!

答:
We can multiply multiple arguments, by following ways:

```<code>>>> def mul(*args):
    multi = 1
    for i in args:
          multi *=i
    return multi
</code>```

mul(2,8)

16

mul(2,8,3)
      48

ContentLicense: CC BY-SA 3.0

Title: Multiplying Functions in Python

Body:
I'm writing a short program for my class and I'm stuck on the last portion. When I run the program, everything functions appropriately up until I get to the end of the code where I try to multiply the cost of two separate functions in order to define another. How can I rectify this?

Here is the code in full:

def main():
    wall_space = float(input('Enter amount of wall space in square feet: '))
    gallon_price = float(input('Enter the cost of paint per gallon: '))
    rate_factor = wall_space / 115
    total_gallons(rate_factor, 1)
    total_labor_cost(rate_factor, 8)
    total_gal_cost(rate_factor, gallon_price)
    total_hourly_cost(rate_factor, 20)
    total_cost(total_hourly_cost, total_gal_cost)
    print()

def total_gallons(rate1, rate2):
    result = rate1 * rate2
    print('The number of gallons of required is: ', result)
    print()

def total_labor_cost(rate1, rate2):
    result = rate1 * rate2
    print('The hours of labor required are: ', result)
    print()

def total_gal_cost(rate1, rate2):
    result = rate1 * rate2
    print('The cost of the paint in total is: ', result)
    print()

def total_hourly_cost(rate1, rate2):
    result = rate1 * rate2
    print('The total labor charges are: ', result)
    print()

def total_cost(rate1, rate2):
    result = rate1 * rate2
    print('This is the total cost of the paint job: ', result)
    print()

main()

I'm desperate here guys!

Body:
We can multiply multiple arguments, by following ways:

>>> def mul(*args):
    multi = 1
    for i in args:
          multi *=i
    return multi

mul(2,8)

16

mul(2,8,3)
      48


问:
mvvm light - messaging
I'm curently teaching myself the MVVM pattern.
I've hit my first snag with the concept of messaging.
I know messaging is contained in the mvvm-light toolkit. But I cannot find an example of usage anywhere (no sample projects are provided in the download).

If anyone can direct me to some information as to how to use messaging in that toolkit, that would be ace.

Thanks

答:
I have posted an example of using Messaging here, as part of my Intro to MVVM Light series.

My goal in this example is to send a message indicating that navigation is needed.  The VM can't manage the navigation so it sends a message to the view.  We do this in three steps:

Create a class to contain the message that is to be passed

In the view model, instantiate the message class and broadcast the message

Within MainPage.xaml.cs register for the message and handle it when received

The complete source code is posted and also available for download.

ContentLicense: CC BY-SA 2.5

Title: mvvm light - messaging


问:
Sidebar menu dropdown coming down from the right
I have completed the sidebar menu already but I want it to dropdown coming from the right but mine is coming downwards. I try to search for those whose dropdown list comes out from the right but I can't find a lot of example. Can someone teach me what should I do to make it appear to the right side instead of coming downwards? Thanks in advance

As you can see in my screenshot, my dropdown is coming downwards only, I want it to appear at the right side. How do I do it?

sidebar.blade.php

```<code><!DOCTYPE html>
<html>
    <head>
        <title>SideBar Menu</title>
        <link href="{{ asset('css/test.css') }}" rel="stylesheet">
    </head>
    <body>
        <div id="sidebar">
            <ul>
                <li><a href="{{route('home')}}">Summary</a></li>
                <li><a href="{{route('deleted_result')}}">Deleted Records</a></li>
                <li><a href="{{url('/verification')}}">Verification</a></li>
                <li><a href="{{url('/evaltest')}}">Evalaluation</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Edit User Information <span class="caret"></span></a>
                    <ul class="dropdown-menu forAnimate" role="menu">
                        <li><a href="{{ url('/edit') }}" style="color: red">Personal Information Edit</a></li>
                        <li><a href="{{ url('/edit0')}}" style="color: red">Driver License Class Edit</a></li>
                        <li><a href="{{ url('/edit4')}}" style="color: red">Language Edit</a></li>
                    </ul>
                </li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Evaluation <span class="caret"></span></a>
                    <ul class="dropdown-menu forAnimate" role="menu">
                        <li><a href="{{ url('/pending')}}" style="color: red">Pending remarks</a></li>
                    </ul>
                </li>
            </ul>
            <div id="sidebar-btn">
                <span></span>
                <span></span>
                <span></span>
            </div>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script>
        $(document).ready(function(){
            $('#sidebar-btn').click(function(){
                $('#sidebar').toggleClass('visible');
            });
        });
        </script>
    </body>
</html>
</code>```

test.css

```<code>body{
    margin:0px;
    padding:0px;
    font-family:"Helvetica Neue", Helvetica, Arial;
}

#sidebar{
    background:blue;
    width:200px;
    height:100%;
    display:block;
    position:fixed;
    left:-200px;
    top:0px;
    transition:left 0.3s linear;
}

#sidebar.visible{
    left:0px;
    transition:left 0.3s linear;
}

ul{
    margin:0px;
    padding:0px;
}

ul li{
    list-style:none;
}

ul li a{
    background:#0000FF;
    color:white;
    border-bottom:1px solid #111;
    display:block;
    width:180px;
    padding:10px;
    text-decoration: none;
}

#sidebar-btn{
    display:inline-block;
    vertical-align: middle;
    width:20px;
    height:15px;
    cursor:pointer;
    margin:20px;
    position:absolute;
    top:0px;
    right:-60px;
}

#sidebar-btn span{
    height:1px;
    background:white;
    margin-bottom:5px;
    display:block;
}

#sidebar-btn span:nth-child(2){
    width:75%;
}

#sidebar-btn span:nth-child(3){
    width:50%;
}

#navbar-toggle collapsed{
    background:#0000FF;
}

.navbar {
    background:#0000FF;
}

nav.sidebar .navbar-nav .open .dropdown-menu>li>a:hover,
nav.sidebar .navbar-nav .open .dropdown-menu>li>a:focus {
    color: white;
    background-color: transparent;
}
</code>```

答:
If you want to position the dropdown static, you can set the dropdown to absolute position.

ul{
    margin:0px;
    padding:0px;
    position:absolute;
    left:300px; /* adjust the left based on need */
}```

If you want to set dynamic position, Calculate the offset and set left position.Set offset dynamically using javascript

Body:
I have completed the sidebar menu already but I want it to dropdown coming from the right but mine is coming downwards. I try to search for those whose dropdown list comes out from the right but I can't find a lot of example. Can someone teach me what should I do to make it appear to the right side instead of coming downwards? Thanks in advance

As you can see in my screenshot, my dropdown is coming downwards only, I want it to appear at the right side. How do I do it?

sidebar.blade.php

<!DOCTYPE html>

        <title>SideBar Menu</title>
        <link href="{{ asset('css/test.css') }}" rel="stylesheet">

Summary

Deleted Records

Verification

Evalaluation

                    Edit User Information

Personal Information Edit

Driver License Class Edit

Language Edit

                    Evaluation

Pending remarks

test.css

body{
    margin:0px;
    padding:0px;
    font-family:"Helvetica Neue", Helvetica, Arial;
}

#sidebar{
    background:blue;
    width:200px;
    height:100%;
    display:block;
    position:fixed;
    left:-200px;
    top:0px;
    transition:left 0.3s linear;
}

#sidebar.visible{
    left:0px;
    transition:left 0.3s linear;
}

ul{
    margin:0px;
    padding:0px;
}

ul li{
    list-style:none;
}

ul li a{
    background:#0000FF;
    color:white;
    border-bottom:1px solid #111;
    display:block;
    width:180px;
    padding:10px;
    text-decoration: none;
}

#sidebar-btn{
    display:inline-block;
    vertical-align: middle;
    width:20px;
    height:15px;
    cursor:pointer;
    margin:20px;
    position:absolute;
    top:0px;
    right:-60px;
}

#sidebar-btn span{
    height:1px;
    background:white;
    margin-bottom:5px;
    display:block;
}

#sidebar-btn span:nth-child(2){
    width:75%;
}

#sidebar-btn span:nth-child(3){
    width:50%;
}

#navbar-toggle collapsed{
    background:#0000FF;
}

.navbar {
    background:#0000FF;
}

nav.sidebar .navbar-nav .open .dropdown-menu>li>a:hover,
nav.sidebar .navbar-nav .open .dropdown-menu>li>a:focus {
    color: white;
    background-color: transparent;
}

Body:
If you want to position the dropdown static, you can set the dropdown to absolute position.

ul{
    margin:0px;
    padding:0px;
    position:absolute;
    left:300px; /* adjust the left based on need */
}

If you want to set dynamic position, Calculate the offset and set left position.Set offset dynamically using javascript


问:
Navigation Drawer not opening when I clik on Hamburger button in mainActivity
Hello I am trying to implement Navigation Drawer Menu in my MainActivity, it shows hamburger button, but when I click on it, the menu is not opening. Following are my codes:

activity_main.xml:

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

<FrameLayout
    android:id="@+id/frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</FrameLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/navigation_view"
    app:headerLayout="@layout/header"
    android:layout_width="300dp"
    android:layout_height="match_parent"
    android:background="#fff"
    app:itemTextColor="#000"
    app:itemIconTint="#000"
    app:menu="@menu/main_menu"
    android:layout_gravity="start">

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

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

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
ActionBarDrawerToggle mToggle;
NavigationView navigationView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    drawerLayout=(DrawerLayout) findViewById(R.id.drawer);
    mToggle=new ActionBarDrawerToggle(this,drawerLayout,R.string.open,R.string.close);
    drawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    navigationView=(NavigationView)findViewById(R.id.navigation_view);
}
}
</code>```

Styles.xml:

```<code><resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

Anyone please help me. Thanks in advance...

答:
Try this </p>

```<code>Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
</code>```

Body:
Hello I am trying to implement Navigation Drawer Menu in my MainActivity, it shows hamburger button, but when I click on it, the menu is not opening. Following are my codes:

activity_main.xml:

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

<FrameLayout
    android:id="@+id/frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</FrameLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/navigation_view"
    app:headerLayout="@layout/header"
    android:layout_width="300dp"
    android:layout_height="match_parent"
    android:background="#fff"
    app:itemTextColor="#000"
    app:itemIconTint="#000"
    app:menu="@menu/main_menu"
    android:layout_gravity="start">

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

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

MainActivity.java

public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
ActionBarDrawerToggle mToggle;
NavigationView navigationView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    drawerLayout=(DrawerLayout) findViewById(R.id.drawer);
    mToggle=new ActionBarDrawerToggle(this,drawerLayout,R.string.open,R.string.close);
    drawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    navigationView=(NavigationView)findViewById(R.id.navigation_view);
}
}

Styles.xml:

<resources>

Anyone please help me. Thanks in advance...

Body:
Try this

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();


问:
Unit testing Rxjava observables that have a delay
I want to be able to unit test an Observable that has a delayed emission, but without actually waiting for the delay time. Is there a way to do this?

I'm currently using a CountDownHatch to delay the assert, and that works fine, but increases the test run time.

Example:

```<code>val myObservable: PublishSubject<Boolean> = PublishSubject.create<Boolean>()
fun myObservable(): Observable<Boolean> = myObservable.delay(3, TimeUnit.SECONDS)

@Test
fun testMyObservable() {
    val testObservable = myObservable().test()
    myObservable.onNext(true)

    // val lock = CountDownLatch(1)
    // lock.await(3100, TimeUnit.MILLISECONDS)
    testObservable.assertValue(true)
}
</code>```

答:
TestScheduler is perfect for this. It has a handy method advanceTimeBy(long, TimeUnit) allows you to control the timing. And Observable.delay has an overload method takes a Scheduler.

So just use the default Scheduler.computation() in the myObservable function, and use TestScheduler for unit testing.

Body:
I want to be able to unit test an Observable that has a delayed emission, but without actually waiting for the delay time. Is there a way to do this?

I'm currently using a CountDownHatch to delay the assert, and that works fine, but increases the test run time.

Example:

val myObservable: PublishSubject<Boolean> = PublishSubject.create<Boolean>()
fun myObservable(): Observable<Boolean> = myObservable.delay(3, TimeUnit.SECONDS)

@Test
fun testMyObservable() {
    val testObservable = myObservable().test()
    myObservable.onNext(true)

    // val lock = CountDownLatch(1)
    // lock.await(3100, TimeUnit.MILLISECONDS)
    testObservable.assertValue(true)
}


答:
You are setting home button enable. set it disable.

```<code>getSupportActionBar().setDisplayHomeAsUpEnabled(false);
</code>```

then initialize drawer

```<code> private void initNavigationDrawer(Toolbar toolbar) {
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
    drawerLayout.addDrawerListener(actionBarDrawerToggle);
}
</code>```

Title: Navigation Drawer not opening when I clik on Hamburger button in mainActivity

Body:
You are setting home button enable. set it disable.

getSupportActionBar().setDisplayHomeAsUpEnabled(false);

then initialize drawer

 private void initNavigationDrawer(Toolbar toolbar) {
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
    drawerLayout.addDrawerListener(actionBarDrawerToggle);
}


问:
could not get input field value in jquery
I am creating an input field using foreach loop like this

```<code><?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
</code>```

$data is Array

```<code>(
    [0] => Array
        (
            [asset_id] => abc-02
            [asset_name] => Freezer
        )

    [1] => Array
        (
            [asset_id] => xyz-01
            [asset_name] => Refrigerator
        )

    [2] => Array
        (
            [asset_id] => 300001
            [asset_name] => Generator
        )
)
</code>```

and in javascript, I am trying to get the value using this code but it always alerts first value of the input.

```<code><script type="text/javascript">
 $(document).ready(function () {
           var typename = $('#typename').val();
           alert(typename);
});
</script>
</code>```

i have to disable this input field when value is 'Generator'

答:
Try:

$('[readonly].form-control').each(function(i,e) {

    console.log($(e).val());

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="table-td-1">
  <input readonly class="form-control" name="model[]" id="typename" type="text" value="1">
  <input readonly class="form-control" name="model[]" id="typename" type="text" value="2">
  <input readonly class="form-control" name="model[]" id="typename" type="text" value="3">
  <input readonly class="form-control" name="model[]" id="typename" type="text" value="4">
  <input readonly class="form-control" name="model[]" id="typename" type="text" value="5">
</td></code>```

.val() called once will always produce only one value; .val() docs:

Get the current value of the first element in the set of matched elements .

HTML id attribute is supposed to be unique, try this instead.

```<code><?php
   $count = 0;
   foreach($data as $key=>$val) {
?>
    <td class="table-td-1">
        <input readonly class="form-control" name="model[]" id="typename_<?php echo $count++; ?>" type="text" value="<?php echo $val['asset']; ?>">
    </td>

<?php } ?>
</code>```

It'll produce different id attributes for each input, typename_0, typename_1, ..., typename_n, allowing you to for example:

$('[id^="typename_"]').each(function(i,e) {

    console.log($(e).val());

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <td class="table-td-1">
      <input readonly class="form-control" name="model[]" id="typename_0" type="text" value="1">
      <input readonly class="form-control" name="model[]" id="typename_1" type="text" value="2">
      <input readonly class="form-control" name="model[]" id="typename_2" type="text" value="3">
      <input readonly class="form-control" name="model[]" id="typename_3" type="text" value="4">
      <input readonly class="form-control" name="model[]" id="typename_4" type="text" value="5">
    </td></code>```

Where [id^="typename_"] is CSS attribute selector, matching all elements with an id attribute starting with typename_.

ContentLicense: CC BY-SA 4.0

Body:
I am creating an input field using foreach loop like this

<?php foreach($data as $key=>$val) { ?>

<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">

<?php } ?>

$data is Array

(
    [0] => Array
        (
            [asset_id] => abc-02
            [asset_name] => Freezer
        )

    [1] => Array
        (
            [asset_id] => xyz-01
            [asset_name] => Refrigerator
        )

    [2] => Array
        (
            [asset_id] => 300001
            [asset_name] => Generator
        )
)

and in javascript, I am trying to get the value using this code but it always alerts first value of the input.

i have to disable this input field when value is 'Generator'

Body:
Try:

$('[readonly].form-control').each(function(i,e) {

    console.log($(e).val());

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="table-td-1">
  <input readonly class="form-control" name="model[]" id="typename" type="text" value="1">
  <input readonly class="form-control" name="model[]" id="typename" type="text" value="2">
  <input readonly class="form-control" name="model[]" id="typename" type="text" value="3">
  <input readonly class="form-control" name="model[]" id="typename" type="text" value="4">
  <input readonly class="form-control" name="model[]" id="typename" type="text" value="5">
</td>

.val() called once will always produce only one value; .val() docs:

Get the current value of the first element in the set of matched elements .

HTML id attribute is supposed to be unique, try this instead.

<?php
   $count = 0;
   foreach($data as $key=>$val) {
?>
    <td class="table-td-1">
        <input readonly class="form-control" name="model[]" id="typename_<?php echo $count++; ?>" type="text" value="<?php echo $val['asset']; ?>">
    </td>

<?php } ?>

It'll produce different id attributes for each input, typename_0, typename_1, ..., typename_n, allowing you to for example:

$('[id^="typename_"]').each(function(i,e) {

    console.log($(e).val());

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <td class="table-td-1">
      <input readonly class="form-control" name="model[]" id="typename_0" type="text" value="1">
      <input readonly class="form-control" name="model[]" id="typename_1" type="text" value="2">
      <input readonly class="form-control" name="model[]" id="typename_2" type="text" value="3">
      <input readonly class="form-control" name="model[]" id="typename_3" type="text" value="4">
      <input readonly class="form-control" name="model[]" id="typename_4" type="text" value="5">
    </td>

Where [id^="typename_"] is CSS attribute selector, matching all elements with an id attribute starting with typename_.


答:
Here is with working solution for the drop-down menu opening in left instead of in downward position

```<code>#sidebar.visible{
    left:0px;
    transition:left 0.3s linear;
}

ul{
    margin:0px;
    padding:0px;
}

ul li{
    list-style:none;
}

ul li a{
    background:#0000FF ;
    color:white;
    border-bottom:1px solid #111;
    display:block;
    width:180px;
    padding:10px;
    text-decoration: none;
}

#sidebar-btn{
    display:inline-block;
    vertical-align: middle;
    width:20px;
    height:15px;
    cursor:pointer;
    margin:20px;
    position:absolute;
    top:0px;
    right:-60px;
}

#sidebar-btn span{
    height:1px;
    background:white;
    margin-bottom:5px;
    display:block;
}

#sidebar-btn span:nth-child(2){
    width:75%;
}

#sidebar-btn span:nth-child(3){
    width:50%;
}

#navbar-toggle collapsed{
    background:#0000FF ;

}

.navbar {background:#0000FF ;}

 nav.sidebar .navbar-nav .open .dropdown-menu>li>a:hover, nav.sidebar .navbar-nav .open .dropdown-menu>li>a:focus {
    color: white;
    background-color: transparent;
}
.dropdown-menu {
    position: absolute;
    top: 0;
    left: 180px;
    min-width: 180px;
}
</code>```

Feel free if you need any further help

Title: Sidebar menu dropdown coming down from the right

Body:
Here is with working solution for the drop-down menu opening in left instead of in downward position

#sidebar.visible{
    left:0px;
    transition:left 0.3s linear;
}

ul{
    margin:0px;
    padding:0px;
}

ul li{
    list-style:none;
}

ul li a{
    background:#0000FF ;
    color:white;
    border-bottom:1px solid #111;
    display:block;
    width:180px;
    padding:10px;
    text-decoration: none;
}

#sidebar-btn{
    display:inline-block;
    vertical-align: middle;
    width:20px;
    height:15px;
    cursor:pointer;
    margin:20px;
    position:absolute;
    top:0px;
    right:-60px;
}

#sidebar-btn span{
    height:1px;
    background:white;
    margin-bottom:5px;
    display:block;
}

#sidebar-btn span:nth-child(2){
    width:75%;
}

#sidebar-btn span:nth-child(3){
    width:50%;
}

#navbar-toggle collapsed{
    background:#0000FF ;

}

.navbar {background:#0000FF ;}

 nav.sidebar .navbar-nav .open .dropdown-menu>li>a:hover, nav.sidebar .navbar-nav .open .dropdown-menu>li>a:focus {
    color: white;
    background-color: transparent;
}
.dropdown-menu {
    position: absolute;
    top: 0;
    left: 180px;
    min-width: 180px;
}

Feel free if you need any further help


问:
How to implement `using` in javascript?
I would like to make something like this (similar to c#):

```<code>using("content/jquery.js");

$("div").fadeOut();
</code>```

So if content/jquery.js is not on a script in the head I would like to load it and continue the execution after it loads.

Is it possible to implement this or something similar? Note: I could have more than 1 using

答:
You can use getScript:</p>

```<code>$.getScript('test.js', function() {
  alert('Load was performed.');
});
</code>```

Title: How to implement `using` in javascript?

Body:
I would like to make something like this (similar to c#):

using("content/jquery.js");

$("div").fadeOut();

So if content/jquery.js is not on a script in the head I would like to load it and continue the execution after it loads.

Is it possible to implement this or something similar? Note: I could have more than 1 using

Body:
You can use getScript:

$.getScript('test.js', function() {
  alert('Load was performed.');
});


问:
How to write HTML to a file dynamically in Python
I have the following code:

```<code>for item in soup.select('.profile-detail'):
    f= open('htmlfile.html', 'w')
    f.write(item)
    f.close()
</code>```

I want to write items into "htmlfile.html" but it's giving me the error:

TypeError: write() argument must be str, not Tag

答:
Just use str() to get the whole tag content :

```<code>with open('htmlfile.html', 'w') as f:
    for item in soup.select('.profile-detail'):
        f.write(str(item) + '\n') # thanks jeteon :p, it's cleaner
</code>```

Body:
I have the following code:

for item in soup.select('.profile-detail'):
    f= open('htmlfile.html', 'w')
    f.write(item)
    f.close()

I want to write items into "htmlfile.html" but it's giving me the error:

TypeError: write() argument must be str, not Tag

Body:
Just use str() to get the whole tag content :

with open('htmlfile.html', 'w') as f:
    for item in soup.select('.profile-detail'):
        f.write(str(item) + '\n') # thanks jeteon :p, it's cleaner


问:
MongoDB client throws a FileNotFoundException in mscorlib
I'm using Visual Studio .NET 4.6 and Robomongo has no problem connecting to my database

My imports for MongoDB

```<code>using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Bson;
</code>```

The code that's executing:

```<code>MongoClient client = new MongoClient("mongodb://localhost");
MongoServer server = client.GetServer();
MongoDatabase mongoDatabase = server.GetDatabase("GameCollection");
</code>```

The full error message:

An unhandled exception of type 'System.IO.FileNotFoundException'
  occurred in mscorlib.dll

Additional information: Could not load file or assembly
  'System.Runtime.InteropServices.RuntimeInformation, Version=4.0.0.0,
  Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its
  dependencies. The system cannot find the file specified.

答:
After much experimentation, it seems web.config needs the following to work:

```<code><dependentAssembly>
   <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
   <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0" />
</dependentAssembly>
<dependentAssembly>
   <assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
   <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
</dependentAssembly>
</code>```

Whatever redirects NuGet was putting there were incorrect. This maybe isn't a MongoDB issue per se, perhaps issue with Microsoft Nuget packages/version stamps.

Body:
I'm using Visual Studio .NET 4.6 and Robomongo has no problem connecting to my database

My imports for MongoDB

using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Bson;

The code that's executing:

MongoClient client = new MongoClient("mongodb://localhost");
MongoServer server = client.GetServer();
MongoDatabase mongoDatabase = server.GetDatabase("GameCollection");

The full error message:

An unhandled exception of type 'System.IO.FileNotFoundException'
  occurred in mscorlib.dll

Additional information: Could not load file or assembly
  'System.Runtime.InteropServices.RuntimeInformation, Version=4.0.0.0,
  Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its
  dependencies. The system cannot find the file specified.

Body:
After much experimentation, it seems web.config needs the following to work:

<dependentAssembly>
   <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
   <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0" />
</dependentAssembly>
<dependentAssembly>
   <assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
   <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
</dependentAssembly>

Whatever redirects NuGet was putting there were incorrect. This maybe isn't a MongoDB issue per se, perhaps issue with Microsoft Nuget packages/version stamps.


问:
App Transport Security does not work any more with iOS 11 Xcode 9
I've been working on an app...since the iOS 11 update disabling ATS does not work anymore I've added the below in the info.plist

```<code><key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>
</code>```

I can't use the domain exception key as I am downloading images from unknown domains.
below is what I get when trying to download an image

```<code>Task <C3DC30F1-5869-46F6-ABA4-5E1EC8334FD8>.<0> HTTP load failed (error code: -1005 [4:-4])
NSURLConnection finished with error - code -1005
</code>```

答:
I am aware that IOS 11 not longer supports the following:

RC4 3DES-CBC AES-CBC

MD5 SHA-1

<2048-bit RSA Pub Keys - All TLS connections to servers

http://

SSLv3

TLS 1.0

TLS 1.1

Adding the following we can bypass the ATS (App Transport Security) error:

```<code><key>NSAppTransportSecurity</key> <dict>
     <key>NSExceptionDomains</key>
     <dict>
         <key>mydomain.com</key>
         <dict>
             <!--Include to allow subdomains-->
             <key>NSIncludesSubdomains</key>
             <true/>
             <key>NSExceptionRequiresForwardSecrecy</key>
             <false/>
         </dict>
     </dict> </dict>
</code>```

Reference link : iOS 11 ATS (App Transport Security) no longer accepts custom anchor certs?

Body:
I've been working on an app...since the iOS 11 update disabling ATS does not work anymore I've added the below in the info.plist

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>

I can't use the domain exception key as I am downloading images from unknown domains.
below is what I get when trying to download an image

Task <C3DC30F1-5869-46F6-ABA4-5E1EC8334FD8>.<0> HTTP load failed (error code: -1005 [4:-4])
NSURLConnection finished with error - code -1005

Body:
I am aware that IOS 11 not longer supports the following:

RC4 3DES-CBC AES-CBC

MD5 SHA-1

<2048-bit RSA Pub Keys - All TLS connections to servers

http://

SSLv3

TLS 1.0

TLS 1.1

Adding the following we can bypass the ATS (App Transport Security) error:

<key>NSAppTransportSecurity</key> <dict>
     <key>NSExceptionDomains</key>
     <dict>
         <key>mydomain.com</key>
         <dict>
             <!--Include to allow subdomains-->
             <key>NSIncludesSubdomains</key>
             <true/>
             <key>NSExceptionRequiresForwardSecrecy</key>
             <false/>
         </dict>
     </dict> </dict>

Reference link : iOS 11 ATS (App Transport Security) no longer accepts custom anchor certs?


问:
How to make other styles set as default when we changing class of element using JavaScript
I have created div and place it right margin of the page with position:fixed. I need to place the div to bottom margin when I call the JavaScript function. I tried to use classList.add() and classList.remove() to accomplish my task.

here is the CSS classes I created,

```<code>.example-right{
        position:fixed;
        top:50px;
        right:0px;
    }
.example-bottom{
        position:fixed;
        left:50px;
        bottom:0px;
    }
</code>```

This is JavaScript code what I tried,

```<code>function test(){
  document.getElementById('target').classList.remove('example-right');
  document.getElementById('target').classList.add('example-bottom');
}
</code>```

When I trigger the test() function it removes the example-right and replace it with example-bottom. But the div's top value is not going to change after the function is triggered. So, it is not place the div on bottom margin of the window. I can puttop:## px; to example-bottom. But when page is resizing and

Is it possible to Solve this problem using CSS. I know I can use document.getElementById('target').style.top = window.innerHeight- div_Height to change the top value. but I like to know is there any way to do it using css or another method. (otherwise I have to use JavaScript all the times when I need to change the position)

pure CSS and JavaScript only

答:
add this css

```<code>.example-right{
        position:fixed;
        top:50px;
        right:0px;
    }
.example-bottom{
        position:fixed;
        left:50px;
        bottom:0px;
        top:auto;
    }
</code>```

function test(){
  document.getElementById('target').classList.remove('example-right');
  document.getElementById('target').classList.add('example-bottom');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.example-right{
        position:fixed;
        top:50px;
        right:0px;
    }
.example-bottom{
        position:fixed;
        left:50px;
        bottom:0px;
        top:auto;
    }
    #target{
      width:200px;
      height:200px;
      background:red;
    }</code>```

<button onclick="test()">Click</button>```

Body:
I have created div and place it right margin of the page with position:fixed. I need to place the div to bottom margin when I call the JavaScript function. I tried to use classList.add() and classList.remove() to accomplish my task.

here is the CSS classes I created,

.example-right{
        position:fixed;
        top:50px;
        right:0px;
    }
.example-bottom{
        position:fixed;
        left:50px;
        bottom:0px;
    }

This is JavaScript code what I tried,

function test(){
  document.getElementById('target').classList.remove('example-right');
  document.getElementById('target').classList.add('example-bottom');
}

When I trigger the test() function it removes the example-right and replace it with example-bottom. But the div's top value is not going to change after the function is triggered. So, it is not place the div on bottom margin of the window. I can puttop:## px; to example-bottom. But when page is resizing and

Is it possible to Solve this problem using CSS. I know I can use document.getElementById('target').style.top = window.innerHeight- div_Height to change the top value. but I like to know is there any way to do it using css or another method. (otherwise I have to use JavaScript all the times when I need to change the position)

pure CSS and JavaScript only

Body:
add this css

.example-right{
        position:fixed;
        top:50px;
        right:0px;
    }
.example-bottom{
        position:fixed;
        left:50px;
        bottom:0px;
        top:auto;
    }

function test(){
  document.getElementById('target').classList.remove('example-right');
  document.getElementById('target').classList.add('example-bottom');
}

.example-right{
        position:fixed;
        top:50px;
        right:0px;
    }
.example-bottom{
        position:fixed;
        left:50px;
        bottom:0px;
        top:auto;
    }
    #target{
      width:200px;
      height:200px;
      background:red;
    }

<div id="target" class="example-right">

</div>
<br/>
<button onclick="test()">Click</button>


问:
How do I display a ratio in Excel in the format A:B?
I have an Excel spreadsheet of data like:

```<code>ColumnA ColumnB
33        11
25        5
6         4
</code>```

What i would like to do is add a third column which shows the ratio of columnA to columnB in the format of A:B. For example:

```<code>ColumnA ColumnB   Ratio
33        11       3:1
25        5    5:1
6         4    3:2
</code>```

How can this be done?

答:
The second formula on that page uses the GCD function of the Analysis ToolPak, you can add it from Tools > Add-Ins.

=A1/GCD(A1,B1)&":"&B1/GCD(A1,B1)

This is a more mathematical formula rather than a text manipulation based on.

OwnerDisplayName: Vincent

Body:
I have an Excel spreadsheet of data like:

ColumnA ColumnB
33        11
25        5
6         4

What i would like to do is add a third column which shows the ratio of columnA to columnB in the format of A:B. For example:

ColumnA ColumnB   Ratio
33        11       3:1
25        5    5:1
6         4    3:2

How can this be done?

LastEditorDisplayName: Vincent

OwnerDisplayName: Robin Day


问:
Java: static abstract (again) - best practice how to work around
I theoretically understand the point why there is no abstract static in Java, as explained for instance in Why can't static methods be abstract in Java .

But how do I solve such a problem then?

My application uses files of a few types, which I want to assign static properties like a description of that file type (like "data file", the other being "config file", etc.).
Obviously, I would put that into a static String so that the description is accessible without instancing a file (useful for the GUI f.i.).
On the other hand, obviously all file types should have some common methods like getStatus(), which obviously I want to inherit from a common superclass MyFileType.

getDescription() would of course be abstract in the superclass.

Tried using a combination of a superclass and an interface, but similar problem: A static implementation of an abstract method is not allowed.

How would a Java guru solve this?
Is it really such a bad implementation that I want to create?

Many thanks,
Philipp

答:
Instead of putting your static properties actually in static properties, put a reference to MyFileTypeDescription as a static property.

i.e.

```<code>class MyFileType {
   static MyFileTypeDescription description;
   ...
   <your regular attributes>
}
abstract class MyFileTypeDescription {
  String name;
  abstract String getDescription();
}
</code>```

Something along this way, if I understood your problem correctly.

Body:
Instead of putting your static properties actually in static properties, put a reference to MyFileTypeDescription as a static property.

i.e.

class MyFileType {
   static MyFileTypeDescription description;
   ...
   <your regular attributes>
}
abstract class MyFileTypeDescription {
  String name;
  abstract String getDescription();
}

Something along this way, if I understood your problem correctly.


问:
All My Arrays are Mutating, but Why?
When I create new Array(9) it doesn't seem to be actually creating new arrays because when I attempt to mutate single array instances using take, it mutates all the arrays. Clearly they're each referencing the same array rather than being their own new Array, but why? And how do I fix this? I've tried Array.prototype.slice() in various places, but all to no avail.

```<code>const Board = (fillWith = null) => ({
    winner: null,
    squares: new Array(9).fill(fillWith),
    winningSquares: []
});

const game = new Board( new Board() );

const take = (iA, iB, token) => {
  game.squares[iA].squares[iB] = token;
}

take(0,0,'x');
take(8,1,'o');

game.squares.map( (miniboard, i) => console.log({[i]: miniboard.squares}))
</code>```

Expected Result

```<code>{ 0: [ 'x', null, null, null, null, null, null, null, null ] }
{ 1: [ null, null, null, null, null, null, null, null, null ] }
{ 2: [ null, null, null, null, null, null, null, null, null ] }
{ 3: [ null, null, null, null, null, null, null, null, null ] }
{ 4: [ null, null, null, null, null, null, null, null, null ] }
{ 5: [ null, null, null, null, null, null, null, null, null ] }
{ 6: [ null, null, null, null, null, null, null, null, null ] }
{ 7: [ null, null, null, null, null, null, null, null, null ] }
{ 8: [ null, 'o', null, null, null, null, null, null, null ] }
</code>```

Actual Result

```<code>{ 0: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 1: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 2: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 3: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 4: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 5: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 6: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 7: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 8: [ 'x', 'o', null, null, null, null, null, null, null ] }
</code>```

UPDATE:

Okay, this has been marked a duplicate of , and some have complained it's been answered a gazillion times. I get it. It feels very familiar, and I'm fully aware that objects and arrays are copied by reference which is why I've attempted to use the new operator for creating new boards. I've also tried the Array.from solution referenced, but that didn't help either. Maybe there's something else going on here and the answer will come to me in the morning, but for now here's a reference to the updated code I tried (but did not work) just to show that I did try what has been suggested as the answer to my "duplicate" question.

```<code>const Board = (fillWith = null) => ({
    winner: null,
    squares: Array.from({length: 9}, () => fillWith),
    winningSquares: null
});
</code>```

答: fill gets a single instance and with it fills all rows. So your all rows refer to the same instance and because array is a reference type you have only on reference in each row. Instead of fill use map to return for each row its own array.

Title: All My Arrays are Mutating, but Why?

Body:
When I create new Array(9) it doesn't seem to be actually creating new arrays because when I attempt to mutate single array instances using take, it mutates all the arrays. Clearly they're each referencing the same array rather than being their own new Array, but why? And how do I fix this? I've tried Array.prototype.slice() in various places, but all to no avail.

const Board = (fillWith = null) => ({
    winner: null,
    squares: new Array(9).fill(fillWith),
    winningSquares: []
});

const game = new Board( new Board() );

const take = (iA, iB, token) => {
  game.squares[iA].squares[iB] = token;
}

take(0,0,'x');
take(8,1,'o');

game.squares.map( (miniboard, i) => console.log({[i]: miniboard.squares}))

Expected Result

{ 0: [ 'x', null, null, null, null, null, null, null, null ] }
{ 1: [ null, null, null, null, null, null, null, null, null ] }
{ 2: [ null, null, null, null, null, null, null, null, null ] }
{ 3: [ null, null, null, null, null, null, null, null, null ] }
{ 4: [ null, null, null, null, null, null, null, null, null ] }
{ 5: [ null, null, null, null, null, null, null, null, null ] }
{ 6: [ null, null, null, null, null, null, null, null, null ] }
{ 7: [ null, null, null, null, null, null, null, null, null ] }
{ 8: [ null, 'o', null, null, null, null, null, null, null ] }

Actual Result

{ 0: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 1: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 2: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 3: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 4: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 5: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 6: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 7: [ 'x', 'o', null, null, null, null, null, null, null ] }
{ 8: [ 'x', 'o', null, null, null, null, null, null, null ] }

UPDATE:

Okay, this has been marked a duplicate of , and some have complained it's been answered a gazillion times. I get it. It feels very familiar, and I'm fully aware that objects and arrays are copied by reference which is why I've attempted to use the new operator for creating new boards. I've also tried the Array.from solution referenced, but that didn't help either. Maybe there's something else going on here and the answer will come to me in the morning, but for now here's a reference to the updated code I tried (but did not work) just to show that I did try what has been suggested as the answer to my "duplicate" question.

const Board = (fillWith = null) => ({
    winner: null,
    squares: Array.from({length: 9}, () => fillWith),
    winningSquares: null
});


问:
Xamarin "XamarinShellPackage" did not load correctly
I have hit a problem with the new free version of Xamarin.

What I was finding is that I could not use the Storyboard. Whenever I tried to look at Main.storyboard I got the following error message:

Something went wrong - The iOS Designer Mac Agent is not available

And when I clicked “Start Designer Agent” on that same dialog it went away for a few seconds with a progress bar and then came back with the exact same error.

This was odd because I could run the project I have created and it ran fine on the emulator on the connected Mac so I was definitely connected to it. I could also debug the code fine as well. But I couldn’t edit the UI or the storyboard at all.

I contacted the Xamarin support email address and told them all of this and they suggested to update the various components thusly:

To update Xamarin on the Mac open Xamarin Studio and click on:

Xamarin Studio > Check for Updates...

I would advise doing the same for Xamarin for Visual Studio:

Visual Studio > Tools > Options > Xamarin > Other > Check for
  Updates...

Please also ensure that Xcode is up to date and that you've launched
  Xcode and accepted any agreements for any new version.

So I followed those instructions.

I checked on the Mac and the Xamarin Studio installation is up to date. I checked the Xcode on the Mac and it is the latest version. I went to do the update in Visual Studio for Xamarin and some things were out of date so I went through that update. I also rebooted afterwards and restarted Visual Studio.

Unfortunately it has made the problem much worse.

Previously I could at least open and run projects using Xamarin in Visual Studio 2015. What I was unable to do was use the storyboard designer.

Now I cannot do anything with Xamarin as now when I try to run Visual Studio with a Xamarin project I get the following dialog several times:

The XamarinShellPackage package did not load correctly.

As well as another similar dialog referring to “XamarinAndroidPackage” and now the solution in the solution explorer is unavailable for Xamarin projects and I cannot create a new one without getting these messages.

I have tried reinstalling Visual Studio 2015 but that has not helped.

I have tried escalating this problem with Xamarin but the best they could suggest is posting here on Stack Overflow as the best way of getting support for this. Any suggestions?

答: Try deleting the .vs folder from the root of the solution folder, that worked for me. Make sure VS is closed when you do it.


问:
'ul li' hover color with hyperlink inside
Consider:

ul {
  list-style-position: inside;
}

ul li {
  border-radius: 7px;
  line-height: 21px;
  padding: 0 9px;
  letter-spacing: 0.5px;
}

ul li a {
  color: #555;
}

ul li:hover {
  background: #0099cc;
  color: white;
}

ul li a:hover {
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='titlewrap'>
  <ul>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
  </ul>
</div></code>```

Hovering, li a color is changed to white, but when I move the pointer outside of a and still inside of li- color is again #555.

答:
Currently, you're setting color with ul li a, which has higher specificity than ul li:hover.

I believe what you're looking for is ul li:hover a instead of ul li a:hover.

ul {
  list-style-position: inside;
}

ul li {
  border-radius: 7px;
  line-height: 21px;
  padding: 0 9px;
  letter-spacing: 0.5px;
}

ul li a {
  color: #555;
}

ul li:hover {
  background: #0099cc;
  color: white;
}

ul li:hover a {
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='titlewrap'>
  <ul>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
  </ul>
</div></code>```

Body:
Consider:

ul {
  list-style-position: inside;
}

ul li {
  border-radius: 7px;
  line-height: 21px;
  padding: 0 9px;
  letter-spacing: 0.5px;
}

ul li a {
  color: #555;
}

ul li:hover {
  background: #0099cc;
  color: white;
}

ul li a:hover {
  color: white;
}

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

Hovering, li a color is changed to white, but when I move the pointer outside of a and still inside of li- color is again #555.

Body:
Currently, you're setting color with ul li a, which has higher specificity than ul li:hover.

I believe what you're looking for is ul li:hover a instead of ul li a:hover.

ul {
  list-style-position: inside;
}

ul li {
  border-radius: 7px;
  line-height: 21px;
  padding: 0 9px;
  letter-spacing: 0.5px;
}

ul li a {
  color: #555;
}

ul li:hover {
  background: #0099cc;
  color: white;
}

ul li:hover a {
  color: white;
}

<div class='titlewrap'>
  <ul>
    <li class='title'><a href='view.php?id=1' target='_blank'>lorem ipsum</a></li>
    <li class='title'><a href='view.php?id=2' target='_blank'>lorem ipsum</a></li>
    <li class='title'><a href='view.php?id=3' target='_blank'>lorem ipsum</a></li>
    <li class='title'><a href='view.php?id=4' target='_blank'>lorem ipsum</a></li>
  </ul>
</div>


问:
How do I pass data from login to another page
I am new to react-native and redux. I have successfully created a login function which calls a post-request api. The credentials insert by a user are matric no and password. I have another post-method api need to be called to display a list of data in another page after the user successfully logged on. However I dunno how to pass the matric no  to another page since there is no event that ought to trigger the user to enter their matric no i order to call the post-method api. Can somebody help me how to solve this?</p>

答:
you might want to use react redux. Using this u can acess anything from anywhere fast and simple.

Its a little hard to setup but once u have setup its easy to manage and u get info anywhere in the app refer this link: Getting started with Redux.

It covers different aspects of using redux. Starting off with a simple example of counter. It also deals with how to manage an api call where the result can be accessed anywhere from the app.

Good luck!


问:
what is the root of classpath for a java web application
I want to display some messages from properties file while user enter some incorrect information and submit the form, but I always got warning message from eclipse console like this:

```<code>WARNING: ResourceBundle [messages] not found for MessageSource: Can't find bundle for base name messages, locale en_US
Nov 15, 2017 9:32:42 AM org.springframework.context.support.ResourceBundleMessageSource getResourceBundle
</code>```

I config the MessageSource bean in WebConfig.java like this:

```<code>@Bean
public MessageSource messageSource()
{
    ResourceBundleMessageSource validationSource = new ResourceBundleMessageSource();
    validationSource.setBasename("messages");
    return validationSource;
}
</code>```

I put my message.properties like below:

when I right click on the properties file, it shows its path like this:

so, where is the correct place I should put this properties file? which path is the root of classpath in a java web application?

答:
Currently src is your root classpath.

You may want to create another "resources" folder and add it to your classpath.

Then move your property file in it.

Above is the usual directory layout for a Maven project.

Body:
I want to display some messages from properties file while user enter some incorrect information and submit the form, but I always got warning message from eclipse console like this:

WARNING: ResourceBundle [messages] not found for MessageSource: Can't find bundle for base name messages, locale en_US
Nov 15, 2017 9:32:42 AM org.springframework.context.support.ResourceBundleMessageSource getResourceBundle

I config the MessageSource bean in WebConfig.java like this:

@Bean
public MessageSource messageSource()
{
    ResourceBundleMessageSource validationSource = new ResourceBundleMessageSource();
    validationSource.setBasename("messages");
    return validationSource;
}

I put my message.properties like below:

when I right click on the properties file, it shows its path like this:

so, where is the correct place I should put this properties file? which path is the root of classpath in a java web application?


答:
there is a big mistake in your code, you can't use same id for multiple input fields, when the loop run multiple input fields will create with same id, you have to make the id dynamic, you can make the id dynamic by appending some unique value to the id each time you create an input field the use that id to fetch the data.

Please let me know if you need sample code.

Title: could not get input field value in jquery

Body:
I am creating an input field using foreach loop like this

<?php foreach($data as $key=>$val) { ?>

<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">

<?php } ?>

$data is Array

(
    [0] => Array
        (
            [asset_id] => abc-02
            [asset_name] => Freezer
        )

    [1] => Array
        (
            [asset_id] => xyz-01
            [asset_name] => Refrigerator
        )

    [2] => Array
        (
            [asset_id] => 300001
            [asset_name] => Generator
        )
)

and in javascript, I am trying to get the value using this code but it always alerts first value of the input.

i have to disable this input field when value is 'Generator'


答:
Use this instead

```<code>ul li:hover a {
  color: white;
}
</code>```

ul {
  list-style-position: inside;
}

ul li {
  border-radius: 7px;
  line-height: 21px;
  padding: 0 9px;
  letter-spacing: 0.5px;
}

ul li a {
  color: #555;
}

ul li:hover {
  background: #0099cc;
  color: white;
}

ul li:hover a {
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='titlewrap'>
  <ul>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
  </ul>
</div></code>```

Title: 'ul li' hover color with hyperlink inside

Body:
Use this instead

ul li:hover a {
  color: white;
}

ul {
  list-style-position: inside;
}

ul li {
  border-radius: 7px;
  line-height: 21px;
  padding: 0 9px;
  letter-spacing: 0.5px;
}

ul li a {
  color: #555;
}

ul li:hover {
  background: #0099cc;
  color: white;
}

ul li:hover a {
  color: white;
}

<div class='titlewrap'>
  <ul>
    <li class='title'><a href='view.php?id=1' target='_blank'>lorem ipsum</a></li>
    <li class='title'><a href='view.php?id=2' target='_blank'>lorem ipsum</a></li>
    <li class='title'><a href='view.php?id=3' target='_blank'>lorem ipsum</a></li>
    <li class='title'><a href='view.php?id=4' target='_blank'>lorem ipsum</a></li>
  </ul>
</div>


问:
Getting AWS instance id in laravel
Here Iam trying to print AWS instance ID in laravel blade. Iam already tried with these but always gives empty.

```<code>{{ shell_exec('ec2-metadata --instance-id | cut -d " " -f 2') }}

{{ exec('ec2-metadata --instance-id | cut -d " " -f 2') }}
 {{ shell_exec('ec2-metadata --instance-id') }}
{{ exec('ec2-metadata --instance-id') }}
{{ shell_exec('ec2-metadata --instance-id >2 /dev/null cut -d ""') }}
{{ exec('ec2-metadata --instance-id2 /dev/null cut -d ""') }}
</code>```

How to get AWS instance id in laravel? Thanks in advance

答:
Use the following statement to get aws instance id </p>

```<code>{{ shell_exec('ec2-metadata --instance-id 2> /dev/null | cut -d " " -f 2'); }}
</code>```

Title: Getting AWS instance id in laravel

Body:
Here Iam trying to print AWS instance ID in laravel blade. Iam already tried with these but always gives empty.

{{ shell_exec('ec2-metadata --instance-id | cut -d " " -f 2') }}

{{ exec('ec2-metadata --instance-id | cut -d " " -f 2') }}
 {{ shell_exec('ec2-metadata --instance-id') }}
{{ exec('ec2-metadata --instance-id') }}
{{ shell_exec('ec2-metadata --instance-id >2 /dev/null cut -d ""') }}
{{ exec('ec2-metadata --instance-id2 /dev/null cut -d ""') }}

How to get AWS instance id in laravel? Thanks in advance

Body:
Use the following statement to get aws instance id

{{ shell_exec('ec2-metadata --instance-id 2> /dev/null | cut -d " " -f 2'); }}


问:
How chunk_every method works in elixir?
Enum.chunk_every([1, 2, 3, 4, 5, 6], 2)

Gives output [[1, 2], [3, 4], [5, 6]] on console.

But,  Enum.chunk_every([1, 2, 3, 4, 5, 6, 7, 8], 2)

Gives [[1, 2], [3, 4], [5, 6], '\a\b']

Why does it return ascii characters for some integers?

答:
It's a not a matter of Enum.chunk_every/2, but rather the fact that characters that are "printable" in terms of ASCII table, are displayed as ASCII characters.

Check this answer.

To avoid that some people add 0 at the very end of very beginning of the list or you just ignore it - it case you need to check these integers you can:

```<code>a = [[1, 2], [3, 4], [5, 6], [7, 8]]
IO.inspect a, charlists: :as_lists
</code>```

Title: How chunk_every method works in elixir?

Body:
It's a not a matter of Enum.chunk_every/2, but rather the fact that characters that are "printable" in terms of ASCII table, are displayed as ASCII characters.

Check this answer.

To avoid that some people add 0 at the very end of very beginning of the list or you just ignore it - it case you need to check these integers you can:

a = [[1, 2], [3, 4], [5, 6], [7, 8]]
IO.inspect a, charlists: :as_lists


问:
Pivoting the data
This is my SQL statement

```<code>select  id , name, type,  value  from table1 a
INNER JOIN table2 b on a.id = b.id
where  b.type in ('display','contact','ship')
</code>```

which produces below result

```<code>ID  name     type           value
5   test     display        display1
5   test     contact        contact1
5   test     ship           ship1
6   test2    display        display2
6   test2    contact        contact2
6   test2    ship           ship2
</code>```

I need to get result in kind of pivoted format like this

```<code>id  name   display   contact   ship
5   test   display1  contact1 ship1
6   test2  display2  contact2 ship2
</code>```

I tried this solution : https://stackoverflow.com/a/6849706/2645738 ,but its giving me the same result (3 rows for each data). It's like i need to group by id and name,but don't know how to make display,contact,ship as columns.

Would you please help me for the same.

答:
If you want PIVOT:

```<code>DECLARE @DataSource TABLE
(
    [id] TINYINT
   ,[name] VARCHAR(12)
   ,[type] VARCHAR(12)
   ,[value] VARCHAR(12)
);

INSERT INTO @DataSource ([id], [name], [type], [value])
VALUES (5, 'test', 'display', 'display1')
      ,(5, 'test', 'contact', 'contact1')
      ,(5, 'test', 'ship', 'ship1')
      ,(6, 'test2', 'display', 'display2')
      ,(6, 'test2', 'contact', 'contact2')
      ,(6, 'test2', 'ship',  'ship2');

SELECT *
FROM @DataSource
PIVOT
(
    MAX([value]) FOR [type] IN ([display], [contact], [ship])
) PVT;
</code>```

Title: Pivoting the data

Body:
This is my SQL statement

select  id , name, type,  value  from table1 a
INNER JOIN table2 b on a.id = b.id
where  b.type in ('display','contact','ship')

which produces below result

ID  name     type           value
5   test     display        display1
5   test     contact        contact1
5   test     ship           ship1
6   test2    display        display2
6   test2    contact        contact2
6   test2    ship           ship2

I need to get result in kind of pivoted format like this

id  name   display   contact   ship
5   test   display1  contact1 ship1
6   test2  display2  contact2 ship2

I tried this solution : https://stackoverflow.com/a/6849706/2645738 ,but its giving me the same result (3 rows for each data). It's like i need to group by id and name,but don't know how to make display,contact,ship as columns.

Would you please help me for the same.

Body:
If you want PIVOT:

DECLARE @DataSource TABLE
(
    [id] TINYINT
   ,[name] VARCHAR(12)
   ,[type] VARCHAR(12)
   ,[value] VARCHAR(12)
);

INSERT INTO @DataSource ([id], [name], [type], [value])
VALUES (5, 'test', 'display', 'display1')
      ,(5, 'test', 'contact', 'contact1')
      ,(5, 'test', 'ship', 'ship1')
      ,(6, 'test2', 'display', 'display2')
      ,(6, 'test2', 'contact', 'contact2')
      ,(6, 'test2', 'ship',  'ship2');

SELECT *
FROM @DataSource
PIVOT
(
    MAX([value]) FOR [type] IN ([display], [contact], [ship])
) PVT;


问:
Kafka - java clients comparison
I want to use Kafka in my java program. Which of kafka java clients is best for which usecase? Can you point me differences between Kafka Streams, Kafka Connect and Kafka Spring (and others if they exists)?</p>

答:
For the simple use cases I would use the standard Kafka Clients from the Kafka distribution: Kafka Producer and Kafka Consumer. It would be enough to write simple applications.

If you want to build complex stream processing apps on top of Kafka - the Kafka Streams library is the best choice. With Kafka Streams you will be able to build very complex apps similar to Spark Streaming (with filter, map, flatMap etc functions).

Kafka Connect is a way to import/export data to/from Kafka. For instance with Kafka ElasticSearch-Connector you will be able to export your data from your Kafka topics to ElasticSearch directly and in real time.

Kafka Connect: https://www.confluent.io/product/connectors/x

Kafka Streams: https://kafka.apache.org/documentation/streams/

Kafka Clients: https://mvnrepository.com/artifact/org.apache.kafka/kafka-clients/0.11.0.0

Title: Kafka - java clients comparison


问:
How to detect if android phone has dual back camera
How do I detect if android phone has dual back camera

I tried

```<code>CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    try {
        for(String id: manager.getCameraIdList())
            Log.e("dualtest", id);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
</code>```

but it gives me only 2 ids 0 and 1.

答:
You can use Camera.getCameraInfo Like follows. If you use api lvl 9

```<code>List<Integer> camID = new ArrayList<Integer>();
        for(int i=0;i<Camera.getNumberOfCameras();i++){
            CameraInfo cameraInfo = new CameraInfo();
            Camera.getCameraInfo(i,cameraInfo);
            if(cameraInfo.facing==CameraInfo.CAMERA_FACING_BACK) {
                camID.add(i);
                break;
            }
        }
</code>```

If you are using api lvl 21 you can use Camera2 api

```<code>List<String> camID = new ArrayList<String>();

    CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    for(String cameraId:manager.getCameraIdList()){
        CameraCharacteristics cameraCharacteristics = manager.getCameraCharacteristics(cameraId);
        Integer facing = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING);
        if(facing==CameraMetadata.LENS_FACING_BACK) {
            camID.add(cameraId);
            break;
        }
    }
</code>```

Reference

https://developer.android.com/reference/android/hardware/camera2/CameraManager.html

https://developer.android.com/reference/android/hardware/Camera.html#getCameraInfo(int,%20android.hardware.Camera.CameraInfo)

Body:
How do I detect if android phone has dual back camera

I tried

CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    try {
        for(String id: manager.getCameraIdList())
            Log.e("dualtest", id);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

but it gives me only 2 ids 0 and 1.

Body:
You can use Camera.getCameraInfo Like follows. If you use api lvl 9

List<Integer> camID = new ArrayList<Integer>();
        for(int i=0;i<Camera.getNumberOfCameras();i++){
            CameraInfo cameraInfo = new CameraInfo();
            Camera.getCameraInfo(i,cameraInfo);
            if(cameraInfo.facing==CameraInfo.CAMERA_FACING_BACK) {
                camID.add(i);
                break;
            }
        }

If you are using api lvl 21 you can use Camera2 api

List<String> camID = new ArrayList<String>();

    CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    for(String cameraId:manager.getCameraIdList()){
        CameraCharacteristics cameraCharacteristics = manager.getCameraCharacteristics(cameraId);
        Integer facing = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING);
        if(facing==CameraMetadata.LENS_FACING_BACK) {
            camID.add(cameraId);
            break;
        }
    }

Reference

https://developer.android.com/reference/android/hardware/camera2/CameraManager.html

https://developer.android.com/reference/android/hardware/Camera.html#getCameraInfo(int,%20android.hardware.Camera.CameraInfo)


问:
Alphabet and code ascii
I am trying to create a program in c language that gets a number and a string, for example the number is 3 and the string is "Zig".
The output should be alphabet's codes + the number. If the character's number goes more than "Z" (90) it should start from "A" again. Similarily, for lower case characters, when going beyond "z" start again from "a".
input  : "Zig"

number : 3

output : "Clj"

I have a problem with the part that it should start from A(for capitals) & a again.
this is my code now ! I have a problem with rotation part how to start from A or a again :)

```<code>char a[50];

int n,i;
printf("enter your number:\t");

scanf("%d",&n);
printf("enter your string:\t");

fflush(stdin);

gets(a);

while('A'<= a[i] <= 'Z'){
    if(a[i]+n > 'Z'){

    }
    else{
    a[i]=a[i]+n;
}
i++;
}
while('a' <= a[i] <= 'z'){
    if(a[i]+n > 'z'){

}
    else{
        a[i]=a[i]+n;
    }
    i++;
}
printf("string:\n");
puts(a);
</code>```

}

答:
I have a problem with the part that it should start from A(for capitals) & a again

When you get to Z (decimal 90) you can easily subtract 25 (ASCII char "EM") to get back to A (decimal 65). Similarly you can repeat subtraction of 25 when you reach z and it will cycle back to

Title: Alphabet and code ascii

Body:
I am trying to create a program in c language that gets a number and a string, for example the number is 3 and the string is "Zig".
The output should be alphabet's codes + the number. If the character's number goes more than "Z" (90) it should start from "A" again. Similarily, for lower case characters, when going beyond "z" start again from "a".
input  : "Zig"

number : 3

output : "Clj"

I have a problem with the part that it should start from A(for capitals) & a again.
this is my code now ! I have a problem with rotation part how to start from A or a again :)

char a[50];

int n,i;
printf("enter your number:\t");

scanf("%d",&n);
printf("enter your string:\t");

fflush(stdin);

gets(a);

while('A'<= a[i] <= 'Z'){
    if(a[i]+n > 'Z'){

    }
    else{
    a[i]=a[i]+n;
}
i++;
}
while('a' <= a[i] <= 'z'){
    if(a[i]+n > 'z'){

}
    else{
        a[i]=a[i]+n;
    }
    i++;
}
printf("string:\n");
puts(a);

}


问:
How to retrieve the changed item in an ObservableList via ListChangeListener
There is ListChangeListener.Change.wasUpdated() which is used to detect changes within elements for ObservableLists created via ObservableList.observableArrayList(Callback<E,Observable[]> extractor).

How do I retrieve the exact item(s) that caused the change to be triggered?

Edit

Maybe the question isn't clear enough, I'll give an example.

```<code>class Foo {
    private StringProperty name = new SimpleStringProperty();
    public final StringProperty nameProperty() { return name; }
    public final String getName() { return name.get(); }
    public final void setName(String n) { name.set(n); }
    public Foo(String fooName) { setName(fooName); }
}

// Creates an ObservableList with an extractor
ObservableList<Foo> fooList = FXCollections.observableArrayList(foo -> new Observable[] { foo.nameProperty() });
Foo fooA = new Foo("Hello");
Foo fooB = new Foo("Kitty");
fooList.add(fooA);
fooList.add(fooB);

fooList.addListener(new ListChangeListener<Foo>() {
     public void onChanged(Change<Foo> c) {
         while (c.next()) {
            if (c.wasUpdated()) {
                // One or more of the elements in list has/have an internal change, but I have no idea which element(s)!
            }
        }
    }
});

fooB.setName("Mickey");
</code>```

fooB.setName() will trigger a change in the ListChangeListener, which the wasUpdated() condition would return true. However, I have no way to know that it is fooB which has changed within the listener.

This may seem trivial, but I have a map application where the list stores the things which the map has to render. When one of the item changes its position (i.e. lat/long), I need to re-plot on the map. If I have no idea which item has changed location, I'll have to redraw everything that I already have.

答:
Straight from the docs.

Typical usage is to observe changes on an ObservableList in order to hook or unhook (or add or remove a listener) or in order to maintain some invariant on every element in that ObservableList. A common code pattern for doing this looks something like the following:

```<code> ObservableList theList = ...;

 theList.addListener(new ListChangeListener<Item>() {
     public void onChanged(Change<tem> c) {
         while (c.next()) {
             if (c.wasPermutated()) {
                     for (int i = c.getFrom(); i < c.getTo(); ++i) {
                          //permutate
                     }
                 } else if (c.wasUpdated()) {
                          //update item
                 } else {
                     for (Item remitem : c.getRemoved()) {
                         remitem.remove(Outer.this);
                     }
                     for (Item additem : c.getAddedSubList()) {
                         additem.add(Outer.this);
                     }
                 }
             }
         }
     });

 }
</code>```

Body:
There is ListChangeListener.Change.wasUpdated() which is used to detect changes within elements for ObservableLists created via ObservableList.observableArrayList(Callback<E,Observable[]> extractor).

How do I retrieve the exact item(s) that caused the change to be triggered?

Edit

Maybe the question isn't clear enough, I'll give an example.

class Foo {
    private StringProperty name = new SimpleStringProperty();
    public final StringProperty nameProperty() { return name; }
    public final String getName() { return name.get(); }
    public final void setName(String n) { name.set(n); }
    public Foo(String fooName) { setName(fooName); }
}

// Creates an ObservableList with an extractor
ObservableList<Foo> fooList = FXCollections.observableArrayList(foo -> new Observable[] { foo.nameProperty() });
Foo fooA = new Foo("Hello");
Foo fooB = new Foo("Kitty");
fooList.add(fooA);
fooList.add(fooB);

fooList.addListener(new ListChangeListener<Foo>() {
     public void onChanged(Change<Foo> c) {
         while (c.next()) {
            if (c.wasUpdated()) {
                // One or more of the elements in list has/have an internal change, but I have no idea which element(s)!
            }
        }
    }
});

fooB.setName("Mickey");

fooB.setName() will trigger a change in the ListChangeListener, which the wasUpdated() condition would return true. However, I have no way to know that it is fooB which has changed within the listener.

This may seem trivial, but I have a map application where the list stores the things which the map has to render. When one of the item changes its position (i.e. lat/long), I need to re-plot on the map. If I have no idea which item has changed location, I'll have to redraw everything that I already have.

Body:
Straight from the docs.

Typical usage is to observe changes on an ObservableList in order to hook or unhook (or add or remove a listener) or in order to maintain some invariant on every element in that ObservableList. A common code pattern for doing this looks something like the following:

 ObservableList theList = ...;

 theList.addListener(new ListChangeListener<Item>() {
     public void onChanged(Change<tem> c) {
         while (c.next()) {
             if (c.wasPermutated()) {
                     for (int i = c.getFrom(); i < c.getTo(); ++i) {
                          //permutate
                     }
                 } else if (c.wasUpdated()) {
                          //update item
                 } else {
                     for (Item remitem : c.getRemoved()) {
                         remitem.remove(Outer.this);
                     }
                     for (Item additem : c.getAddedSubList()) {
                         additem.add(Outer.this);
                     }
                 }
             }
         }
     });

 }


问:
What does "~[]" do?
I saw the following line of code here .

```<code>puts("sigprocmask(SIG_UNBLOCK, ~[], []) = 0");
</code>```

I don't understand, what does empty array script([]) do?

Also, What is the purpose of ~[] in C?

答: The syntax ~[] is part of Javascript bitwise NOT empty array expression. C does not have any such operator.</p>

Title: What does "~[]" do?

Body:
I saw the following line of code here .

puts("sigprocmask(SIG_UNBLOCK, ~[], []) = 0");

I don't understand, what does empty array script([]) do?

Also, What is the purpose of ~[] in C?


问:
Windows Phone 7 WebBrowserTask problem with escaped urls
I'm trying to open a web page via the instapaper or google mobilizers.

So I pass to the webbrowser task the UrlEncoded url:
http://www.instapaper.com/m?u=http%3A%2F%2Ftwitter.com%2FT_Jako%2Fstatuses%2F27119375731400704

which seems perfectly fine to me.

I generate it by doing

```<code>serviceUrl + Uri.EscapeDataString(url.ToString())
</code>```

The problem is IE probably unescapes the parameter before requesting the page, so I get a 404 page.

I don't understand what I am doing wrong, or if it is a bug on WP7 and if there is a workaround for it.

[UPDATE]:
This is definitely a bug, that also got confirmed by a guy from the WP7 team.
I blogged about that too:
http://codeclimber.net.nz/archive/2011/01/19/WP7-Tip-Always-Encode-Urls-for-the-WebBrowserTask.aspx

Thank you
Simone

答:
It's definitely a bug.

I had problems passing Twitter statuses in French. Double escaping the URL worked for me :

```<code>string url = http://twitter.com/?status=testÉÇÀéçà
var wb = new WebBrowserTask();
wb.URL = Uri.EscapeUriString(Uri.EscapeUriString(url));
wb.Show();
</code>```

Body:
I'm trying to open a web page via the instapaper or google mobilizers.

So I pass to the webbrowser task the UrlEncoded url:
http://www.instapaper.com/m?u=http%3A%2F%2Ftwitter.com%2FT_Jako%2Fstatuses%2F27119375731400704

which seems perfectly fine to me.

I generate it by doing

serviceUrl + Uri.EscapeDataString(url.ToString())

The problem is IE probably unescapes the parameter before requesting the page, so I get a 404 page.

I don't understand what I am doing wrong, or if it is a bug on WP7 and if there is a workaround for it.

[UPDATE]:
This is definitely a bug, that also got confirmed by a guy from the WP7 team.
I blogged about that too:
http://codeclimber.net.nz/archive/2011/01/19/WP7-Tip-Always-Encode-Urls-for-the-WebBrowserTask.aspx

Thank you
Simone

Body:
It's definitely a bug.

I had problems passing Twitter statuses in French. Double escaping the URL worked for me :

string url = http://twitter.com/?status=testÉÇÀéçà
var wb = new WebBrowserTask();
wb.URL = Uri.EscapeUriString(Uri.EscapeUriString(url));
wb.Show();


问:
How to detect SQL errors in c++ code at compile time
So, I want SQL errors to prevent C++ code from building successfully.

What I was thinking was compiling via some cmake script or something that would grep the cpp files for SQL and validate the SQL.

I know I could add some kind of runtime error checking but I don't want the following code to build sucessfully (not a question about pqxx, but SQL errors in C++ in general):

```<code>#include <iostream>
#include <pqxx/pqxx>

using namespace std;
using namespace pqxx;

int main() {
    connection conn("dbname=d user=u");

    conn.prepare("invalid_sql", "SELECT 1 FROM WHERE a = $1");

    nontransaction txn(conn);

    txn.prepared("invalid_sql")(1.0).exec();

    cout << "the process already died due to invalid SQL" << endl;

    return 0;
}
</code>```

答:
You can, sort-of...

One approach is Boost meta_parsing, another is using C++11's user-defined literal types. I couldn't find a worked example for SQL, but perhaps as C++11 matures someone will come up with one.

Body:
So, I want SQL errors to prevent C++ code from building successfully.

What I was thinking was compiling via some cmake script or something that would grep the cpp files for SQL and validate the SQL.

I know I could add some kind of runtime error checking but I don't want the following code to build sucessfully (not a question about pqxx, but SQL errors in C++ in general):

#include <iostream>
#include <pqxx/pqxx>

using namespace std;
using namespace pqxx;

int main() {
    connection conn("dbname=d user=u");

    conn.prepare("invalid_sql", "SELECT 1 FROM WHERE a = $1");

    nontransaction txn(conn);

    txn.prepared("invalid_sql")(1.0).exec();

    cout << "the process already died due to invalid SQL" << endl;

    return 0;
}


问:
made a program in python but get TypeError: 'method' object is not subscriptable
```<code>import pyowm
import datetime
import csv

W = pyowm.OWM("****************************")
myHouse = W.weather_at_place("St. albert,Canada")
myWeather = myHouse.get_weather()
wind = myWeather.get_wind()
windspeed = wind["speed"]
windangle = wind["deg"]
humidity = myWeather.get_humidity()
temperature = myWeather.get_temperature("celsius")
high = temperature["temp_max"]
low = temperature["temp_min"]
current = temperature["temp"]
date = datetime.datetime.now().strftime("%D")
time = datetime.datetime.now().strftime("%H")

done=0

while True:
    if datetime.datetime.now().strftime("%S") == "00" and done == 0:
        done=1
        csvfile = open("weatherCSV.csv", "w")
        writeCSV = csv.writer(csvfile, delimiter=",")

        myWeather = myHouse.get_weather()
        wind = myWeather.get_wind
        windspeed = wind["speed"]
        windangle = wind["deg"]
        humidity = myWeather.get_humidity()
        temperature = myWeather.get_temperature("celsius")
        high = temperature["temp_max"]
        low = temperature["temp_min"]
        current = temperature["temp"]
        date = datetime.datetime.now().strftime("%D")
        time = datetime.datetime.now().strftime("%H")

        writeCSV.writerow([current,high,low,windspeed,windangle,humidity,date,time])
        csvfile.close()
        print("Added to file")

    if datetime.datetime.now().strftime("%S") == "30" and done == 1:
        done=0
</code>```

this is my program, it should be fine since wind is a dictionnary and temperature works just fine but i get error:

```<code>...$ python weather.py
Traceback (most recent call last):
  File "weather.py", line 29, in <module>
    windspeed = wind["speed"]
TypeError: 'method' object is not subscriptable
</code>```

by the way line 29 is:

```<code>windspeed = wind["speed"]
</code>```

inside the while True: and the if ... : loops. I would very much like to know why this doesn't work and how to make it work because it seems to be running that code just fine the first time, outside the loops.
  this is running on python 3.6.1 on the latest MacOs.

答:
It’s hard to help you since we don’t know what type of your variable. You can try to either print type of your wind object to see or print(wind) itself. My guess is wind here is returned as a method and not exactly dictionary type as you want.

Also inside the loop your get_wind is missing () which makes Python does not understand you are calling the method and think you are calling variable inside the object

Body:
import pyowm
import datetime
import csv

W = pyowm.OWM("****************************")
myHouse = W.weather_at_place("St. albert,Canada")
myWeather = myHouse.get_weather()
wind = myWeather.get_wind()
windspeed = wind["speed"]
windangle = wind["deg"]
humidity = myWeather.get_humidity()
temperature = myWeather.get_temperature("celsius")
high = temperature["temp_max"]
low = temperature["temp_min"]
current = temperature["temp"]
date = datetime.datetime.now().strftime("%D")
time = datetime.datetime.now().strftime("%H")

done=0

while True:
    if datetime.datetime.now().strftime("%S") == "00" and done == 0:
        done=1
        csvfile = open("weatherCSV.csv", "w")
        writeCSV = csv.writer(csvfile, delimiter=",")

        myWeather = myHouse.get_weather()
        wind = myWeather.get_wind
        windspeed = wind["speed"]
        windangle = wind["deg"]
        humidity = myWeather.get_humidity()
        temperature = myWeather.get_temperature("celsius")
        high = temperature["temp_max"]
        low = temperature["temp_min"]
        current = temperature["temp"]
        date = datetime.datetime.now().strftime("%D")
        time = datetime.datetime.now().strftime("%H")

        writeCSV.writerow([current,high,low,windspeed,windangle,humidity,date,time])
        csvfile.close()
        print("Added to file")

    if datetime.datetime.now().strftime("%S") == "30" and done == 1:
        done=0

this is my program, it should be fine since wind is a dictionnary and temperature works just fine but i get error:

...$ python weather.py
Traceback (most recent call last):
  File "weather.py", line 29, in <module>
    windspeed = wind["speed"]
TypeError: 'method' object is not subscriptable

by the way line 29 is:

windspeed = wind["speed"]

inside the while True: and the if ... : loops. I would very much like to know why this doesn't work and how to make it work because it seems to be running that code just fine the first time, outside the loops.
  this is running on python 3.6.1 on the latest MacOs.


问:
How to access file in parent directory using python?
I am trying to access a text file in the parent directory,

Eg : python script is in codeSrc & the text file is in mainFolder.

script path:

```<code>G:\mainFolder\codeSrc\fun.py
</code>```

desired file path:

```<code>G:\mainFolder\foo.txt
</code>```

I am currently using this syntax with python 2.7x,

```<code>import os
filename = os.path.dirname(os.getcwd())+"\\foo.txt"
</code>```

Although this works fine, is there a better (prettier :P) way to do this?

答:
To get a path to a file in the parent directory of the current script you can do:</p>

```<code>import os
file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'foo.txt')
</code>```

Body:
I am trying to access a text file in the parent directory,

Eg : python script is in codeSrc & the text file is in mainFolder.

script path:

G:\mainFolder\codeSrc\fun.py

desired file path:

G:\mainFolder\foo.txt

I am currently using this syntax with python 2.7x,

import os
filename = os.path.dirname(os.getcwd())+"\\foo.txt"

Although this works fine, is there a better (prettier :P) way to do this?

Body:
To get a path to a file in the parent directory of the current script you can do:

import os
file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'foo.txt')


问:
Get an object's position in another object's coordinate system
Is there a way in MEL or Python in Maya to get one object's position in the coordinate system of another object? I have a camera in a scene that may be rotated in any direction and am trying to measure the distance in its local Z axis to the vertices of various objects in the scene. This obviously needs to be fast, since it will likely be run thousands of times across the scene.

In Maxscript the command would be something like

```<code>" in coordsys $camera "
</code>```

but I have yet to find something like this in Maya. If there's no direct command to do this, does anyone have a way to calculate it using matrix math?

答:
Use this MEL script to calculate the distance from camera1 to nurbsSphere1 primitive:

```<code>vector $p1 = `getAttr camera1.translate`;
vector $p2 = `getAttr nurbsSphere1.translate`;
vector $result = $p1 - $p2;
print (mag($result))
</code>```

Printed result must be like this:

```<code># MEL 40.1965
</code>```

Or use this Python script to calculate the distance from camera1 to nurbsSphere1 primitive:

```<code>import maya.cmds as cmds
import math

distance = math.sqrt(pow((float)(cmds.getAttr("nurbsSphere1.tx") - cmds.getAttr("camera1.tx")),2) +
                     pow((float)(cmds.getAttr("nurbsSphere1.ty") - cmds.getAttr("camera1.ty")),2) +
                     pow((float)(cmds.getAttr("nurbsSphere1.tz") - cmds.getAttr("camera1.tz")),2) )
print(distance)
</code>```

Printed result must be like this:

```<code># Python 40.1964998512
</code>```

Body:
Is there a way in MEL or Python in Maya to get one object's position in the coordinate system of another object? I have a camera in a scene that may be rotated in any direction and am trying to measure the distance in its local Z axis to the vertices of various objects in the scene. This obviously needs to be fast, since it will likely be run thousands of times across the scene.

In Maxscript the command would be something like

" in coordsys $camera "

but I have yet to find something like this in Maya. If there's no direct command to do this, does anyone have a way to calculate it using matrix math?

Body:
Use this MEL script to calculate the distance from camera1 to nurbsSphere1 primitive:

vector $p1 = `getAttr camera1.translate`;
vector $p2 = `getAttr nurbsSphere1.translate`;
vector $result = $p1 - $p2;
print (mag($result))

Printed result must be like this:

# MEL 40.1965

Or use this Python script to calculate the distance from camera1 to nurbsSphere1 primitive:

import maya.cmds as cmds
import math

distance = math.sqrt(pow((float)(cmds.getAttr("nurbsSphere1.tx") - cmds.getAttr("camera1.tx")),2) +
                     pow((float)(cmds.getAttr("nurbsSphere1.ty") - cmds.getAttr("camera1.ty")),2) +
                     pow((float)(cmds.getAttr("nurbsSphere1.tz") - cmds.getAttr("camera1.tz")),2) )
print(distance)

Printed result must be like this:

# Python 40.1964998512