问:
Fragment over listview activity
I am pretty new to android development, so please don't flame me for stupid questions/mistakes!

I have a listview inside my activity, but i want to open up a fragment when a frame in the listview is clicked on. I have the onclick working, but it is not launching the new activity.

I'll include my code below.

This is the oncreate

```<code>protected void onCreate (Bundle savedInstanceState)
{
    //Fragment fragment_blank2=new SomeFragment();
    e = myBadData.getData();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.event_list);
    events=(ListView) findViewById(R.id.dayList);
    ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,e);
    events.setAdapter(adapter);
    events.setOnItemClickListener(this);
}
</code>```

this is the onclick

```<code>public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
    myBadData.setId(i);
    Fragment fr = new event_description();

    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();

    fragmentTransaction.add(R.id.eventdescription, fr);
}
</code>```

this is the XML of the fragment

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id = "@+id/eventdescription"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="layout.BlankFragment">

<!-- TODO: Update blank fragment layout -->

    <TextView
        android:layout_width="match_parent"
        android:layout_height="137dp"
        android:text="@string/event_name"
        android:textSize="26sp"
        android:layout_gravity="top"
        android:gravity="top|center"
        android:paddingTop="10dp"
        android:id="@+id/textView"
        android:background="@android:color/holo_orange_light"
        android:textColor="@android:color/black"
        android:layout_weight="1.08" />
    <TextView
        android:text="@string/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/date"
        android:layout_marginTop="@dimen/activity_top_margin"
        android:layout_marginLeft="@dimen/activity_side_margin"
        android:textSize="18sp"
        android:drawableTint="@android:color/background_dark" />
    <TextView
        android:text="@string/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/time"
        android:layout_marginTop="70dp"
        android:layout_marginLeft="@dimen/activity_side_margin"
        android:textSize="18sp" />
    <TextView
        android:text="@string/cost"
        android:layout_gravity="right"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/cost"
        android:layout_marginTop="@dimen/activity_top_margin"
        android:layout_marginRight="70dp"
        android:textSize="18sp"/>
    <TextView
        android:text="@string/address"
        android:layout_gravity="right"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/address"
        android:layout_marginTop="70dp"
        android:layout_marginRight="60dp"
        android:textSize="18sp" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="135dp"
        android:layout_marginLeft="10dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:weightSum="1">

            <TextView
                android:id="@+id/tv_long"
                android:paddingTop="10dp"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="@string/sample_text"
                android:textSize="18sp"
                android:layout_weight="1.08">
            </TextView>
        </LinearLayout>
    </ScrollView>

    <Button
        android:text="@string/add_to_calendar"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:id="@+id/button2"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="95dp"/>
</FrameLayout>
</code>```

here is the class of the fragment

```<code>public class event_description extends Fragment
{
    @Nullable
    //@Override
    public View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate (R.layout.event_description, container, false);
        Bundle args = getArguments();
        String arg = args.getString(eventList.KEY_NAME);
        //return super.(R.layout.event_description, container, false);
        return view;
    }

    public View getView() {
      return getView();
    }
}
</code>```

答:
For Your Activity XML

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/my_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- TODO: Update blank fragment layout -->

    <ListView
        android:id="@+id/dayList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

   </FrameLayout>
</code>```

And Pass Activity's Container in FramgmentTransaction

```<code>public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
    myBadData.setId(i);
    Fragment fr = new event_description();

    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();

    //Your Container of Activity
    fragmentTransaction.add(R.id.my_frame, fr);

    fragmentTransaction.commit();
}
</code>```

and Don't forgot to commint it.

No need to use framgment's FrameLayout as a container..

Title: Fragment over listview activity

Body:
I am pretty new to android development, so please don't flame me for stupid questions/mistakes!

I have a listview inside my activity, but i want to open up a fragment when a frame in the listview is clicked on. I have the onclick working, but it is not launching the new activity.

I'll include my code below.

This is the oncreate

protected void onCreate (Bundle savedInstanceState)
{
    //Fragment fragment_blank2=new SomeFragment();
    e = myBadData.getData();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.event_list);
    events=(ListView) findViewById(R.id.dayList);
    ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,e);
    events.setAdapter(adapter);
    events.setOnItemClickListener(this);
}

this is the onclick

public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
    myBadData.setId(i);
    Fragment fr = new event_description();

    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();

    fragmentTransaction.add(R.id.eventdescription, fr);
}

this is the XML of the fragment

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id = "@+id/eventdescription"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="layout.BlankFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="137dp"
        android:text="@string/event_name"
        android:textSize="26sp"
        android:layout_gravity="top"
        android:gravity="top|center"
        android:paddingTop="10dp"
        android:id="@+id/textView"
        android:background="@android:color/holo_orange_light"
        android:textColor="@android:color/black"
        android:layout_weight="1.08" />
    <TextView
        android:text="@string/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/date"
        android:layout_marginTop="@dimen/activity_top_margin"
        android:layout_marginLeft="@dimen/activity_side_margin"
        android:textSize="18sp"
        android:drawableTint="@android:color/background_dark" />
    <TextView
        android:text="@string/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/time"
        android:layout_marginTop="70dp"
        android:layout_marginLeft="@dimen/activity_side_margin"
        android:textSize="18sp" />
    <TextView
        android:text="@string/cost"
        android:layout_gravity="right"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/cost"
        android:layout_marginTop="@dimen/activity_top_margin"
        android:layout_marginRight="70dp"
        android:textSize="18sp"/>
    <TextView
        android:text="@string/address"
        android:layout_gravity="right"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/address"
        android:layout_marginTop="70dp"
        android:layout_marginRight="60dp"
        android:textSize="18sp" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="135dp"
        android:layout_marginLeft="10dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:weightSum="1">

            <TextView
                android:id="@+id/tv_long"
                android:paddingTop="10dp"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="@string/sample_text"
                android:textSize="18sp"
                android:layout_weight="1.08">
            </TextView>
        </LinearLayout>
    </ScrollView>

    <Button
        android:text="@string/add_to_calendar"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:id="@+id/button2"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="95dp"/>
</FrameLayout>

here is the class of the fragment

public class event_description extends Fragment
{
    @Nullable
    //@Override
    public View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate (R.layout.event_description, container, false);
        Bundle args = getArguments();
        String arg = args.getString(eventList.KEY_NAME);
        //return super.(R.layout.event_description, container, false);
        return view;
    }

    public View getView() {
      return getView();
    }
}

Body:
For Your Activity XML

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/my_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- TODO: Update blank fragment layout -->

    <ListView
        android:id="@+id/dayList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

   </FrameLayout>

And Pass Activity's Container in FramgmentTransaction

public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
    myBadData.setId(i);
    Fragment fr = new event_description();

    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();

    //Your Container of Activity
    fragmentTransaction.add(R.id.my_frame, fr);

    fragmentTransaction.commit();
}

and Don't forgot to commint it.

No need to use framgment's FrameLayout as a container..


来源: stackexchange

问:
Jquery - Finding closest matching span isn't working
I am trying to set a variable to match the text displayed inside the closest matching span. I've tried about 10 different ways, and when I alert it (to show what it's getting) it always either displays nothing or it says undefined.

Here is the html

```<code><div class="list-group-item">
<span class="list-group-item-heading commenter-name">Test Name</span><span class="pull-right"><a id="78564610">Reply</a> <span class="small text-muted">Mar 29 2017, 00:59:57</span></span>
<p class="list-group-item-text">First comment on page.</p>
</div>
</code>```

Here is the relevant jQuery (minus the on document ready etc)

```<code>$("a").click(function() {

    var $test = $(this).closest('.commenter-name').text();

alert($test);
</code>```

I am trying to get $test to have the content of the span with the class 'commenter-name' - So $test should be set to "Test Name" in this case; but I always either get an empty response or undefined.

If I change it to something like this

```<code>var $test = $(this).closest('span').text();
</code>```

It shows everything inside the CURRENT span (it would show Reply Mar 29 2017, 00:59:57), but for whatever reason I can't refer to that other span with the name in it.

There are several sets of the above HTML, but I don't see why that should matter since I've been trying both closest, parents, parent, prev, and find.

答:
$("a").click(function() {

  var $test = $(this).parent().prev('.commenter-name').text();

  alert($test);
})```
<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>
<div class="list-group-item">
  <span class="list-group-item-heading commenter-name">Test Name</span><span class="pull-right">Reply <span class="small text-muted">Mar 29 2017, 00:59:57</span></span>
  <p class="list-group-item-text">First comment on page.</p>
</div></code>```

Since the target span is prev of parent of a use $(this).parent().prev('.commenter-name').text();

ContentLicense: CC BY-SA 3.0

Body:
I am trying to set a variable to match the text displayed inside the closest matching span. I've tried about 10 different ways, and when I alert it (to show what it's getting) it always either displays nothing or it says undefined.

Here is the html

Test NameReply Mar 29 2017, 00:59:57

First comment on page.

Here is the relevant jQuery (minus the on document ready etc)

$("a").click(function() {

    var $test = $(this).closest('.commenter-name').text();

alert($test);

I am trying to get $test to have the content of the span with the class 'commenter-name' - So $test should be set to "Test Name" in this case; but I always either get an empty response or undefined.

If I change it to something like this

var $test = $(this).closest('span').text();

It shows everything inside the CURRENT span (it would show Reply Mar 29 2017, 00:59:57), but for whatever reason I can't refer to that other span with the name in it.

There are several sets of the above HTML, but I don't see why that should matter since I've been trying both closest, parents, parent, prev, and find.

Body:
$("a").click(function() {

  var $test = $(this).parent().prev('.commenter-name').text();

  alert($test);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-group-item">
  <span class="list-group-item-heading commenter-name">Test Name</span><span class="pull-right"><a id="78564610">Reply</a> <span class="small text-muted">Mar 29 2017, 00:59:57</span></span>
  <p class="list-group-item-text">First comment on page.</p>
</div>

Since the target span is prev of parent of a use $(this).parent().prev('.commenter-name').text();


问:
how to multiply ith maximum element in two list , and then get summation of the results
list1=[1,2,3,4,5,6,7]
list2=[6,4,5]
I want to compute multiplication of ith maximum element pair from the two list, and then summation of the results, like 6*7+5*6+4*5.
Is there any python trick with short coding.</p>

答:
There are already some descent answers posted, but I wanted to expand on some additional capability with functools and itertools that @delta referred to.
Python 2.x solution:

```<code>from functools import partial # helps with less typing & faster lookup
from itertools import izip # izip is a lazy memory efficient version of zip

In [33]: list1, list2 = [1,2,3,4,5,6,7], [6,4,5]
In [34]: des_sort = partial(sorted, reverse=True) #
In [35]: sum(a*b for a,b in izip(des_sort(list1), des_sort(list2)))
Out[35]: 92
</code>```

Note the execution of sum() using generator expression instead of list comprehension using sum([...]).

There's the numpy/pandas route for more math intensive operations; it is slower for small lists, but efficient for large numpy ndarray type.

Of course all of the speed/memory benefits make sense only for larger data sets otherwise any of the other solutions work just as well.

```<code>In [39]: import pandas as pd
In [40]: pd.DataFrame([des_sort(list1), des_sort(list2)]).fillna(0).prod().sum() # performs dot product
Out[40]: 92.0
</code>```

Body:
There are already some descent answers posted, but I wanted to expand on some additional capability with functools and itertools that @delta referred to.
Python 2.x solution:

from functools import partial # helps with less typing & faster lookup
from itertools import izip # izip is a lazy memory efficient version of zip

In [33]: list1, list2 = [1,2,3,4,5,6,7], [6,4,5]
In [34]: des_sort = partial(sorted, reverse=True) #
In [35]: sum(a*b for a,b in izip(des_sort(list1), des_sort(list2)))
Out[35]: 92

Note the execution of sum() using generator expression instead of list comprehension using sum([...]).

There's the numpy/pandas route for more math intensive operations; it is slower for small lists, but efficient for large numpy ndarray type.

Of course all of the speed/memory benefits make sense only for larger data sets otherwise any of the other solutions work just as well.

In [39]: import pandas as pd
In [40]: pd.DataFrame([des_sort(list1), des_sort(list2)]).fillna(0).prod().sum() # performs dot product
Out[40]: 92.0


问:
Invalid date in safari
```<code> alert(new Date('2010-11-29'));
</code>```

chrome, ff doesn't have problems with this, but safari cries "invalid date". Why ?

edit : ok, as per the comments below, I used string parsing and tried this :

```<code>alert(new Date('11-29-2010')); //doesn't work in safari
alert(new Date('29-11-2010')); //doesn't work in safari
alert(new Date('2010-29-11')); //doesn't work in safari
</code>```

edit Mar 22 2018 : Seems like people are still landing here - Today, I would use moment or date-fns and be done with it. Date-fns is very much pain free and light as well.

答:
The pattern yyyy-MM-dd isn't an officially supported format for Date constructor. Firefox seems to support it, but don't count on other browsers doing the same.

Here are some supported strings:

MM-dd-yyyy

yyyy/MM/dd

MM/dd/yyyy

MMMM dd, yyyy

MMM dd, yyyy

DateJS seems like a good library for parsing non standard date formats.

Edit: just checked ECMA-262 standard. Quoting from section 15.9.1.15:

Date Time String Format

ECMAScript defines a string
interchange format for date-times
based upon a simplification of the ISO
8601  Extended Format.  The format is
as follows: YYYY-MM-DDTHH:mm:ss.sssZ
Where the fields are as follows:

YYYY is the decimal digits of the year in the Gregorian calendar.

"-" (hyphon) appears literally twice in the string.

MM  is the month of the year from 01 (January) to 12 (December).

DD  is the day of the month from 01 to 31.

"T" appears literally in the string, to indicate the beginning of
the time element.

HH  is the number of complete hours that have passed since midnight as two
decimal digits.

":" (colon) appears literally twice in the string.

mm  is the number of complete minutes since the start of the hour as
two decimal digits.

ss  is the number of complete seconds since the start of the minute
as two decimal digits.

"." (dot) appears literally in the string.

sss is the number of complete milliseconds since the start of the
second as three decimal digits. Both
the "." and the milliseconds field may
be omitted.

Z  is the time zone offset specified as "Z" (for UTC) or either "+" or "-"
followed by a time expression hh:mm

This format includes date-only forms:

YYYY

YYYY-MM

YYYY-MM-DD

It also includes time-only forms with
an optional time zone offset appended:

THH:mm

THH:mm:ss

THH:mm:ss.sss

Also included are "date-times" which
may be any combination of the above.

So, it seems that YYYY-MM-DD is included in the standard, but for some reason, Safari doesn't support it.

Update: after looking at datejs documentation, using it, your problem should be solved using code like this:

```<code>var myDate1 = Date.parseExact("29-11-2010", "dd-MM-yyyy");
var myDate2 = Date.parseExact("11-29-2010", "MM-dd-yyyy");
var myDate3 = Date.parseExact("2010-11-29", "yyyy-MM-dd");
var myDate4 = Date.parseExact("2010-29-11", "yyyy-dd-MM");
</code>```

Title: Invalid date in safari

Body:
 alert(new Date('2010-11-29'));

chrome, ff doesn't have problems with this, but safari cries "invalid date". Why ?

edit : ok, as per the comments below, I used string parsing and tried this :

alert(new Date('11-29-2010')); //doesn't work in safari
alert(new Date('29-11-2010')); //doesn't work in safari
alert(new Date('2010-29-11')); //doesn't work in safari

edit Mar 22 2018 : Seems like people are still landing here - Today, I would use moment or date-fns and be done with it. Date-fns is very much pain free and light as well.

Body:
The pattern yyyy-MM-dd isn't an officially supported format for Date constructor. Firefox seems to support it, but don't count on other browsers doing the same.

Here are some supported strings:

MM-dd-yyyy

yyyy/MM/dd

MM/dd/yyyy

MMMM dd, yyyy

MMM dd, yyyy

DateJS seems like a good library for parsing non standard date formats.

Edit: just checked ECMA-262 standard. Quoting from section 15.9.1.15:

Date Time String Format

ECMAScript defines a string
interchange format for date-times
based upon a simplification of the ISO
8601  Extended Format.  The format is
as follows: YYYY-MM-DDTHH:mm:ss.sssZ
Where the fields are as follows:

YYYY is the decimal digits of the year in the Gregorian calendar.

"-" (hyphon) appears literally twice in the string.

MM  is the month of the year from 01 (January) to 12 (December).

DD  is the day of the month from 01 to 31.

"T" appears literally in the string, to indicate the beginning of
the time element.

HH  is the number of complete hours that have passed since midnight as two
decimal digits.

":" (colon) appears literally twice in the string.

mm  is the number of complete minutes since the start of the hour as
two decimal digits.

ss  is the number of complete seconds since the start of the minute
as two decimal digits.

"." (dot) appears literally in the string.

sss is the number of complete milliseconds since the start of the
second as three decimal digits. Both
the "." and the milliseconds field may
be omitted.

Z  is the time zone offset specified as "Z" (for UTC) or either "+" or "-"
followed by a time expression hh:mm

This format includes date-only forms:

YYYY

YYYY-MM

YYYY-MM-DD

It also includes time-only forms with
an optional time zone offset appended:

THH:mm

THH:mm:ss

THH:mm:ss.sss

Also included are "date-times" which
may be any combination of the above.

So, it seems that YYYY-MM-DD is included in the standard, but for some reason, Safari doesn't support it.

Update: after looking at datejs documentation, using it, your problem should be solved using code like this:

var myDate1 = Date.parseExact("29-11-2010", "dd-MM-yyyy");
var myDate2 = Date.parseExact("11-29-2010", "MM-dd-yyyy");
var myDate3 = Date.parseExact("2010-11-29", "yyyy-MM-dd");
var myDate4 = Date.parseExact("2010-29-11", "yyyy-dd-MM");

ContentLicense: CC BY-SA 4.0


问:
Unable to route in ruby on rails as I encounter specific error

I'm using rails 5.0 and I get the

PostsController#index is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []

NOTE! For XHR/Ajax or API requests while trying to input my url/posts.

my routing.rb file is below:

```<code>Rails.application.routes.draw do
    get 'posts/index' => 'posts#index'
    resources: posts
end
</code>```

my posts_controller.rb looks like below:

```<code>class PostsController < ApplicationController
    def index

    end
end
</code>```

I want to know specifically what I'm doing wrong. I've just started to learning Ruby on Rails.

答:
The issue is template missing you are missing the template file index.html.erb

I have notice that on your snapshot you named the template file as index.html.erb.txt

remove the .txt and rename to index.html.erb Then it should work

Also you don't need to declare the routes as

get 'posts/index' => 'posts#index'

Just declare the resources: posts is enough. You may check the routes using the rake routes command on your rails console

Body:
I'm using rails 5.0 and I get the

PostsController#index is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []

NOTE! For XHR/Ajax or API requests while trying to input my url/posts.

my routing.rb file is below:

Rails.application.routes.draw do
    get 'posts/index' => 'posts#index'
    resources: posts
end

my posts_controller.rb looks like below:

class PostsController < ApplicationController
    def index

    end
end

I want to know specifically what I'm doing wrong. I've just started to learning Ruby on Rails.


答: Template is missing. You need to create a file ie index.html.erb under directory /app/views/posts/index.html</p>

Title: Unable to route in ruby on rails as I encounter specific error


答:
.closest() doesn't literally means closest. the method traverse up the hierarchy. As its not the parent of ANCHOR you are not getting the result;

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

Use

```<code>var $test = $(this)
            .closest('.list-group-item') //Target  common parent
            .find('.commenter-name') //target the element
            .text();
</code>```

$("a").click(function(e) {
  e.preventDefault();
  var $test = $(this).closest('.list-group-item').find('.commenter-name').text();
  console.log($test);
});```
<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>
<div class="list-group-item">
  <span class="list-group-item-heading commenter-name">Test Name</span><span class="pull-right">Reply <span class="small text-muted">Mar 29 2017, 00:59:57</span></span>
  <p class="list-group-item-text">First comment on page.</p>
</div></code>```

Title: Jquery - Finding closest matching span isn't working

Body:
.closest() doesn't literally means closest. the method traverse up the hierarchy. As its not the parent of ANCHOR you are not getting the result;

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

Use

var $test = $(this)
            .closest('.list-group-item') //Target  common parent
            .find('.commenter-name') //target the element
            .text();

$("a").click(function(e) {
  e.preventDefault();
  var $test = $(this).closest('.list-group-item').find('.commenter-name').text();
  console.log($test);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-group-item">
  <span class="list-group-item-heading commenter-name">Test Name</span><span class="pull-right"><a href="#" id="78564610">Reply</a> <span class="small text-muted">Mar 29 2017, 00:59:57</span></span>
  <p class="list-group-item-text">First comment on page.</p>
</div>


问:
Visual Studio 2017 -TFS - Organise folder structure output
I'd like to organise my file in the same structure that it is built:

Solution1

project1

project2

Currently I dealt with the output path of each project (..\bin\NameProject) to have this:

Solution1

project1

project2

But in each project (so in project1 and project2), I find all the DLLs/executables from all projects.
I want that the output of project1 receives only DLLs/executable from project1, the same thing for project2.

Then, I think to fix that with build process template (https://msdn.microsoft.com/en-us/library/dd647551(v=vs.120).aspx), so I have this structure:

*BuildProcessTemplate

-BuildProcessSource

Templates (with my CustomTemplate.xaml inside)

Solution1

-project1

-project2

But I don't know how this step could help me. Maybe it's not the good way.
Do you have an idea?

Thank you for helping me!

EDIT

What I want as ouput exactly for instance:

```<code>Solution1
  project1
     including all output (DLLs) from project 1
  project2
     including all output (DLLs) from project 2
</code>```

答:
Actually, you don't need to customize your build process template. You could add this MSBuild parameter in your build definition and have a try. For more detail, please refer to this blog.

```<code> /p:GenerateProjectSpecificOutputFolder=True
</code>```

And the Output Location still set to SingleFolder.

Here is another case which have the similar question with you, you could also refer to those replies in this link. What's the best way to get TFS to output each project to its own directory?

Body:
I'd like to organise my file in the same structure that it is built:

Solution1

project1

project2

Currently I dealt with the output path of each project (..\bin\NameProject) to have this:

Solution1

project1

project2

But in each project (so in project1 and project2), I find all the DLLs/executables from all projects.
I want that the output of project1 receives only DLLs/executable from project1, the same thing for project2.

Then, I think to fix that with build process template (https://msdn.microsoft.com/en-us/library/dd647551(v=vs.120).aspx), so I have this structure:

*BuildProcessTemplate

-BuildProcessSource

Templates (with my CustomTemplate.xaml inside)

Solution1

-project1

-project2

But I don't know how this step could help me. Maybe it's not the good way.
Do you have an idea?

Thank you for helping me!

EDIT

What I want as ouput exactly for instance:

Solution1
  project1
     including all output (DLLs) from project 1
  project2
     including all output (DLLs) from project 2

Body:
Actually, you don't need to customize your build process template. You could add this MSBuild parameter in your build definition and have a try. For more detail, please refer to this blog.

 /p:GenerateProjectSpecificOutputFolder=True

And the Output Location still set to SingleFolder.

Here is another case which have the similar question with you, you could also refer to those replies in this link. What's the best way to get TFS to output each project to its own directory?


问:
Login Validation of an imageview in android
validation: Login Form :
I am able validate the email :if there is error, it should not go to next page.

But,There is one field. Imageview.  i picked  an image from the gallery and set it to imageview.  there is also no probem.

When there is no  image in Imageview,  it should rise the error because of no image which is like email validation.
How validate Imageview like login validation

it should not move to next page ...

..How is it possible. any help? thank's in advance.
I can validate successfully with below code like that Imageview which i want.

```<code>enter code here

public class MainActivity extends AppCompatActivity
  implements View.OnClickListener {

//The view objects
private EditText editTextName, editTextEmail, editTextMobile,
        editTextDob, editTextAge;

private Button buttonSubmit;

//defining AwesomeValidation object
private AwesomeValidation awesomeValidation;

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

    //initializing awesomevalidation object
    /*        awesomeValidation.addValidation(this, R.id.editTextName, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.nameerror);

    * The library provides 3 types of validation
    * BASIC
    * COLORATION
    * UNDERLABEL
    * */
    awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);

    //initializing view objects
    editTextName = (EditText) findViewById(R.id.editTextName);
    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextMobile = (EditText) findViewById(R.id.editTextMobile);
    editTextDob = (EditText) findViewById(R.id.editTextDob);
    editTextAge = (EditText) findViewById(R.id.editTextAge);

    buttonSubmit = (Button) findViewById(R.id.buttonSubmit);

    //adding validation to edittexts
    awesomeValidation.addValidation(this, R.id.editTextEmail, Patterns.EMAIL_ADDRESS, R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextMobile, "^[2-9]{2}[0-9]{8}$", R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextDob, "^(?:(?:31(\\/|-|\\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$", R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextAge, Range.closed(13, 60), R.string.ageerror);

    buttonSubmit.setOnClickListener(this);
}

private void submitForm() {
    //first validate the form then move ahead
    //if this becomes true that means validation is successfull
    if (awesomeValidation.validate()) {
        Toast.makeText(this, "Validation Successfull", Toast.LENGTH_LONG).show();
        //process the data further
    }
}

@Override
public void onClick(View view) {
    if (view == buttonSubmit) {
        submitForm();
    }
}
}
</code>```

答:
You can you following code:

Open Gallery:

```<code>private void openGallery() {
        Intent pOpenGalleryIntent = new Intent();
        pOpenGalleryIntent.setType("image/*");
        pOpenGalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(pOpenGalleryIntent, getString(R.string.app_name)),1);
    }
</code>```

OnActivityResult():

```<code>@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Uri pSelectedImageUri = null;
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                pSelectedImageUri = data.getData();
                //Set imageView

            }

    } else {
         //Validation fail
    }
}
</code>```

Body:
validation: Login Form :
I am able validate the email :if there is error, it should not go to next page.

But,There is one field. Imageview.  i picked  an image from the gallery and set it to imageview.  there is also no probem.

When there is no  image in Imageview,  it should rise the error because of no image which is like email validation.
How validate Imageview like login validation

it should not move to next page ...

..How is it possible. any help? thank's in advance.
I can validate successfully with below code like that Imageview which i want.

enter code here

public class MainActivity extends AppCompatActivity
  implements View.OnClickListener {

//The view objects
private EditText editTextName, editTextEmail, editTextMobile,
        editTextDob, editTextAge;

private Button buttonSubmit;

//defining AwesomeValidation object
private AwesomeValidation awesomeValidation;

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

    //initializing awesomevalidation object
    /*        awesomeValidation.addValidation(this, R.id.editTextName, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.nameerror);

    * The library provides 3 types of validation
    * BASIC
    * COLORATION
    * UNDERLABEL
    * */
    awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);

    //initializing view objects
    editTextName = (EditText) findViewById(R.id.editTextName);
    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextMobile = (EditText) findViewById(R.id.editTextMobile);
    editTextDob = (EditText) findViewById(R.id.editTextDob);
    editTextAge = (EditText) findViewById(R.id.editTextAge);

    buttonSubmit = (Button) findViewById(R.id.buttonSubmit);

    //adding validation to edittexts
    awesomeValidation.addValidation(this, R.id.editTextEmail, Patterns.EMAIL_ADDRESS, R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextMobile, "^[2-9]{2}[0-9]{8}$", R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextDob, "^(?:(?:31(\\/|-|\\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$", R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextAge, Range.closed(13, 60), R.string.ageerror);

    buttonSubmit.setOnClickListener(this);
}

private void submitForm() {
    //first validate the form then move ahead
    //if this becomes true that means validation is successfull
    if (awesomeValidation.validate()) {
        Toast.makeText(this, "Validation Successfull", Toast.LENGTH_LONG).show();
        //process the data further
    }
}

@Override
public void onClick(View view) {
    if (view == buttonSubmit) {
        submitForm();
    }
}
}

Body:
You can you following code:

Open Gallery:

private void openGallery() {
        Intent pOpenGalleryIntent = new Intent();
        pOpenGalleryIntent.setType("image/*");
        pOpenGalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(pOpenGalleryIntent, getString(R.string.app_name)),1);
    }

OnActivityResult():

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Uri pSelectedImageUri = null;
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                pSelectedImageUri = data.getData();
                //Set imageView

            }

    } else {
         //Validation fail
    }
}


问:
Angular2 Pass data between two components via service
Hi I'm trying to pass selected value(from options) from first component to second component but I am having trouble getting the values in second component.

I am currently using services to do so and am console.logging everythign to see if I'm passing the value.

Everything loads as I intend until second component.

Below is my code

First Component HTML

```<code> <p class="fonts-title"> Select Region</p>
 <div class="selectcontainer">
    <select (change)="passValue1()" formControlName="region" class="form- control"  class="selectionbox" [(ngModel)]="selected_region" required>
  <option *ngFor="let region of regions | filterregion" [ngValue]="region">
{{region.areaName}}
</option>
</select>
</code>```

First Component

```<code>export class SearchSelectComponent implements OnInit {

  constructor(
    private passData: TeacherPassDataService) { }

  selected_region: string;

  passValue1(val1) {
    this.passData.setValue1(val1=this.selected_region['areaCode'])
  }
</code>```

Service

```<code>@Injectable()
export class TeacherPassDataService {

    value1: string;

    constructor() {
        this.value1="",
    }

    setValue1(val1: string) {
        this.value1 = val1
        console.log(this.getValue1()) //this prints selected_region value from the first component as I intented
    }

    getValue1() {
        return this.value1;
    }

}
</code>```

However, in second component,

```<code>constructor(
        private getVal: TeacherPassDataService) {
    }

   getVal1() {
       return this.getVal.getValue1(),
       this.firstVal=this.getVal1(),
       console.log(this.getVal.getValue1()) //this prints 'undefined'
    }
</code>```

Why I am getting undefined in the second component when I am setting the value correctly using service?

Please Help!

Thank you in advance

答:
Probably you are not adding the service as a Provider inside the appModule,</p>

```<code>@NgModule({
 providers: [
 TeacherPassDataService
 ]
})
</code>```

Body:
Hi I'm trying to pass selected value(from options) from first component to second component but I am having trouble getting the values in second component.

I am currently using services to do so and am console.logging everythign to see if I'm passing the value.

Everything loads as I intend until second component.

Below is my code

First Component HTML

 Select Region

    <select (change)="passValue1()" formControlName="region" class="form- control"  class="selectionbox" [(ngModel)]="selected_region" required>
  <option *ngFor="let region of regions | filterregion" [ngValue]="region">
{{region.areaName}}
</option>
</select>

First Component

export class SearchSelectComponent implements OnInit {

  constructor(
    private passData: TeacherPassDataService) { }

  selected_region: string;

  passValue1(val1) {
    this.passData.setValue1(val1=this.selected_region['areaCode'])
  }

Service

@Injectable()
export class TeacherPassDataService {

    value1: string;

    constructor() {
        this.value1="",
    }

    setValue1(val1: string) {
        this.value1 = val1
        console.log(this.getValue1()) //this prints selected_region value from the first component as I intented
    }

    getValue1() {
        return this.value1;
    }

}

However, in second component,

constructor(
        private getVal: TeacherPassDataService) {
    }

   getVal1() {
       return this.getVal.getValue1(),
       this.firstVal=this.getVal1(),
       console.log(this.getVal.getValue1()) //this prints 'undefined'
    }

Why I am getting undefined in the second component when I am setting the value correctly using service?

Please Help!

Thank you in advance

Body:
Probably you are not adding the service as a Provider inside the appModule,

@NgModule({
 providers: [
 TeacherPassDataService
 ]
})


问:
Bug in std::variant implementation of gcc7
Consider this code:

```<code>#include <variant>

constexpr auto cc = 'c';
constexpr std::variant<const int*,const char*> pp{&cc}; // passes
constexpr std::variant<const int&,const char&> rr{cc};  // FAILS ?!
</code>```

With g++ (GCC) 7.0.0 20161023 (experimental) the last line fails with error message:

```<code>variant|199 col 9| error: call to non-constexpr function ‘void* operator new(std::size_t, void*)’
||        { ::new (&_M_storage) _Type(std::forward<_Args>(__args)...); }
</code>```

pointing to constructor:

```<code>template<typename... _Args>
constexpr _Uninitialized(in_place_index_t<0>, _Args&&... __args)
: _M_storage{} // This was added manually
{ ::new (&_M_storage) _Type(std::forward<_Args>(__args)...); }
</code>```

Actually, before this there were two more issues:

First it was complaining call to non-constexpr function ‘std::_Enable_default_constructor<false, _Tag>::_Enable_default_constructor(std::_Enable_default_constructor_tag) I've fixed it by making constexpr the constructor _Enable_default_constructor<false, _Tag>::_Enable_default_constructor(_Enable_default_constructor_tag) { }

Then it was complaining _M_storage’ must be initialized by mem-initializer in ‘constexpr’ constuctor I've fixed it by adding : _M_storage{} to the member initialization list, though I don't think it should complain as the added line should be generated implicitly.

So the first question is: this is certainly a bug right?

And the second question is: how can I workaround it by changing the library codes before gcc will fix it?

答: That's "fixed" in the standard by disallowing references as variant alternatives (for now). GCC 7.0.1's snapshot from 2017-03-29 seems to do that correctly.</p>

Body:
Consider <a href="http://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,options:(colouriseAsm:'0',compileOnChange:'0'),source:'%23include+%3Cvariant%3E%0A%0Aconstexpr+auto+cc+%3D+!'c!'%3B%0Aconstexpr+std::variant%3Cconst+int*,const+char*%3E+pp%7B%26cc%7D%3B%0Aconstexpr+std::variant%3Cconst+int%26,const+char%26%3E+rr%7Bcc%7D%3B++//+FAILS+%3F!!'),l:'5',n:'1',o:'C%2B%2B+source+%231',t:'0')),k:50,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g7snapshot,filters:(b:'0',commentOnly:'0',directives:'0',intel:'0'),options:'-std%3Dc%2B%2B1z+-O3'),l:'5',n:'0',o:'%231+with+x86-64+gcc+7+(snapshot)',t:'0')),k:50,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="nofollow">this code:

#include <variant>

constexpr auto cc = 'c';
constexpr std::variant<const int*,const char*> pp{&cc}; // passes
constexpr std::variant<const int&,const char&> rr{cc};  // FAILS ?!

With g++ (GCC) 7.0.0 20161023 (experimental) the last line fails with error message:

variant|199 col 9| error: call to non-constexpr function ‘void* operator new(std::size_t, void*)’
||        { ::new (&_M_storage) _Type(std::forward<_Args>(__args)...); }

pointing to constructor:

template<typename... _Args>
constexpr _Uninitialized(in_place_index_t<0>, _Args&&... __args)
: _M_storage{} // This was added manually
{ ::new (&_M_storage) _Type(std::forward<_Args>(__args)...); }

Actually, before this there were two more issues:

First it was complaining call to non-constexpr function ‘std::_Enable_default_constructor<false, _Tag>::_Enable_default_constructor(std::_Enable_default_constructor_tag) I've fixed it by making constexpr the constructor _Enable_default_constructor<false, _Tag>::_Enable_default_constructor(_Enable_default_constructor_tag) { }

Then it was complaining _M_storage’ must be initialized by mem-initializer in ‘constexpr’ constuctor I've fixed it by adding : _M_storage{} to the member initialization list, though I don't think it should complain as the added line should be generated implicitly.

So the first question is: this is certainly a bug right?

And the second question is: how can I workaround it by changing the library codes before gcc will fix it?


问:
Odoo template page doesn't update when xml changes
Just started Odoo for a client, and I have a major problem with a template.

a simple template that has some divs and headers.
I also have a record for it to show in the main menu.

Everything works when i first create it.
However if it happens that i want to add or change some html, those changes don't show on the website page (even after I refresh/upgrade the theme).
The website builder allows me to change the text and whatnot, but that's not what I need. I want to be able to change the html structure from the XML. But as soon as the page is created the first time... I'm not allowed to. The page will only display the page as first created.

Hope it's clear and thank you in advance for any help.

Joe

答:
This is a major problem we are facing now. If I change the template by overriding the original website template My localhost is updated with new content and in production and live server it is not getting updated. I mainly made changes in website.layout template.
I also Found a solution, but that is not an efficient and practical way. For that I followed the steps below:

Activate Developer mode

Go to settings --> User Interface --> Views.
Search the template in the view and delete the proper ones and installed My custom module again.

But I can't say this is an efficient method and sometimes the record will arise error if we try to delete a template with relation.


问:
Connecting an OBi (OBi202) to Twilio SIP?
I am looking to connect Twilio SIP to an OBi202 endpoint.  It seems like it would be easy considering the Twilio SIP support and the OBi is a SIP endpoint...

I found the settings for the RTP port range, server, and credential information, but beyond that I am stuck and cannot connect.  Can anyone provide some guidance for connecting an OBi to Twilio?

Edit: I did manage to figure out the inbound routing, although as Devin said, it requires a third party.  I setup a free account with iptel.org.  They provide registration and allowed me to connect my OBi to their pure SIP service.  Using the  verbs I can dial incoming calls to my Twilio numbers directly to my Obi!  I am still testing, but appears to work great so far.

Edit:  I have played around with the iptel service for outgoing.  I can successfully pass a SIP call from my OBi to Twilio, but then I get a bit stuck. I seem to get double charged for the incoming SIP call to Twilio, then the  for the outgoing redirect does not seem to work.  I will post more details once I debug further...

答: It is now possible to do this with Twilio and Obihai. Please visit the Obihai or Twilio website for step by step instructions.</p>


问:
sizeof operator in c
please can anybody help me to implement sizeof() operator in c..

i know the usage .. but i was not able to implement it.

答:
You can't implement sizeof in C; it's a basic operator (you can't implement + either).

You could write a macro that has a limited subset of sizeof's behavior, by doing something along the lines of:

```<code>#define thisIsAHorribleHackDontDoThis(a) \
    ((size_t)((intptr_t)(&a + 1) - (intptr_t)&a))
</code>```

but that only works if a is an lvalue (and it's horrible to behold).  sizeof is not so limited, and that's why you should use it instead of reinventing a wheel that isn't actually round.

Title: sizeof operator in c

Body:
You can't implement sizeof in C; it's a basic operator (you can't implement + either).

You could write a macro that has a limited subset of sizeof's behavior, by doing something along the lines of:

#define thisIsAHorribleHackDontDoThis(a) \
    ((size_t)((intptr_t)(&a + 1) - (intptr_t)&a))

but that only works if a is an lvalue (and it's horrible to behold).  sizeof is not so limited, and that's why you should use it instead of reinventing a wheel that isn't actually round.

ContentLicense: CC BY-SA 2.5


问:
SQL Server database - get last record
How do I we get last row in SQL Server if we don't have primary id and numeric column? For example we only have a name and a few other columns in the table</p>

答:
Maybe if you have a column for insertedDate you could do something like this:

```<code>select top (1) * from tableName order by insertedDate DESC
</code>```

If not, for future use if you don't want an ID column, maybe you can add a default constraint for inserted date to pick from the system date, so you wouldn't have to add anything when you insert.

Title: SQL Server database - get last record

Body:
Maybe if you have a column for insertedDate you could do something like this:

select top (1) * from tableName order by insertedDate DESC

If not, for future use if you don't want an ID column, maybe you can add a default constraint for inserted date to pick from the system date, so you wouldn't have to add anything when you insert.


问:
Oracle - Compare two similar tables in same database
I have two tables PROD_DEMO and PROD_IMP in the same oracle database. Both share the same structure and constraints. Both table has a primary key PROD_CODE.

I have to show all the records from PROD_IMP table with one addition column STATUS showing if the record is updated or added in the PROD_IMP table.

I have written below query to achieve this but I am sure this require some improvement to make it faster.

```<code>select imp.*, decode(c.record_count, 2, 'U', 1, 'A', null) from prod_imp imp
left join
    (Select prod_code, count(1) as record_count from
        (
            (SELECT * FROM prod_demo UNION SELECT * FROM prod_imp)
            MINUS
            (SELECT * FROM prod_demo INTERSECT SELECT * FROM prod_imp)

        ) group by prod_code) c
on imp.prod_code = c.prod_code;
</code>```

I know this query will also list records which are deleted from PROD_DEMO table but in my case that won't happen.

The execution plan is shown below:

Both tables can have thousands of records. Now my question is how can I improve the performance of this query.

答:
The straight forward way is to select from prod_imp (because it is demanded to show all its records) and look up prod_demo in order to determine each record's status:

```<code>select
  i.*,
  case when d.prod_code is null then 'added'
       when decode(i.col1, d.col1, 0, 1) = 1
         or decode(i.col2, d.col2, 0, 1) = 1
         or ... then 'updated'
       else 'unaltered'
  end as status
from prod_imp i
left join prod_demo d on d.prod_code = i.prod_code;
</code>```

This should be about as fast as it can get.

Body:
I have two tables PROD_DEMO and PROD_IMP in the same oracle database. Both share the same structure and constraints. Both table has a primary key PROD_CODE.

I have to show all the records from PROD_IMP table with one addition column STATUS showing if the record is updated or added in the PROD_IMP table.

I have written below query to achieve this but I am sure this require some improvement to make it faster.

select imp.*, decode(c.record_count, 2, 'U', 1, 'A', null) from prod_imp imp
left join
    (Select prod_code, count(1) as record_count from
        (
            (SELECT * FROM prod_demo UNION SELECT * FROM prod_imp)
            MINUS
            (SELECT * FROM prod_demo INTERSECT SELECT * FROM prod_imp)

        ) group by prod_code) c
on imp.prod_code = c.prod_code;

I know this query will also list records which are deleted from PROD_DEMO table but in my case that won't happen.

The execution plan is shown below:

Both tables can have thousands of records. Now my question is how can I improve the performance of this query.

Body:
The straight forward way is to select from prod_imp (because it is demanded to show all its records) and look up prod_demo in order to determine each record's status:

select
  i.*,
  case when d.prod_code is null then 'added'
       when decode(i.col1, d.col1, 0, 1) = 1
         or decode(i.col2, d.col2, 0, 1) = 1
         or ... then 'updated'
       else 'unaltered'
  end as status
from prod_imp i
left join prod_demo d on d.prod_code = i.prod_code;

This should be about as fast as it can get.


问:
copy a descendant node and place it after the current node
In the below xml. I want to do following

match wrapper/item whose child or descendant is <olr>.

If found, copy <olr> and all its following-siblings, and paste it
after the current node i.e. end of wrapper/item. (other word,<olr> and its following-siblings will always be direct child of <wrapper>)

rest should be copied as it is.

Input XML:

```<code><root>
<wrapper>
    <item>
        <item>1.1</item>
        <item>
            <olr>outlier1</olr>
        </item>
    </item>
    <item>
        <item>2.1</item>
        <item>
            <item>
                <item>
                    <item>preceedingsibling1</item>
                    <item>preceedingsibling2</item>
                    <olr>outlier2</olr>
                    <item>followingsibling1</item>
                    <item>followingsibling2</item>
                </item>
            </item>
        </item>
    </item>
    <item>
        <item>3.1</item>
        <item>
            <item>
                <item>3.3.1</item>
            </item>
        </item>
    </item>
</wrapper>
</code>```

```<code><root>
<wrapper>
    <item>
        <item>1.1</item>
        <item>
        </item>
    </item>
    <olr>outlier1</olr>
    <item>
        <item>2.1</item>
        <item>
            <item>
                <item>
                    <item>preceedingsibling1</item>
                    <item>preceedingsibling2</item>
                </item>
            </item>
        </item>
    </item>
    <olr>outlier2</olr>
    <item>followingsibling1</item>
    <item>followingsibling2</item>
    <item>
        <item>3.1</item>
        <item>
            <item>
                <item>3.3.1</item>
            </item>
        </item>
    </item>
</wrapper>
</code>```

I am trying something:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="item[descendant::olr]">
    <xsl:apply-templates select="node() except descendant::olr"/>
    <!-- ? not sure what to do here        -->
</xsl:template>
</code>```

答:
The below XSLT-2.0 solution would do this:

```<code><xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    version="2.0">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

    <!-- identity transform template with mode='olr' -->
    <xsl:template match="@* | node()" mode="olr">
        <xsl:copy>
            <xsl:apply-templates select="@*, node()[1]" mode="olr"/>
        </xsl:copy>
        <xsl:apply-templates select="following-sibling::node()[1]" mode="olr"/>
    </xsl:template>

    <!-- identity transform template -->
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@*, node()[1]"/>
        </xsl:copy>
        <xsl:apply-templates select="following-sibling::node()[1]"/>
    </xsl:template>

    <!-- copy the olr and it's following-elements in the current element -->
    <xsl:template match="wrapper/item[descendant::olr]">
        <xsl:copy>
            <xsl:apply-templates select="@*, node()[1]" />
        </xsl:copy>
        <xsl:apply-templates select="descendant::olr[not(preceding-sibling::olr)]" mode="olr"/>
        <xsl:apply-templates select="following-sibling::node()[1]"/>
    </xsl:template>

    <!-- "do nothing for olr" template -->
    <xsl:template match="olr[ancestor::item/parent::wrapper]"/>

</xsl:stylesheet>
</code>```

There are two identity transform templates(1st and 2nd) to copy the elements as-is, recursively.

The third template matches the wrapper/item with descendant::olr and specially processes olr(and its following-siblings) by copying it as its own following-sibling.

The fourth template is to do nothing for olr in the normal process.

Body:
In the below xml. I want to do following

match wrapper/item whose child or descendant is <olr>.

If found, copy <olr> and all its following-siblings, and paste it
after the current node i.e. end of wrapper/item. (other word,<olr> and its following-siblings will always be direct child of <wrapper>)

rest should be copied as it is.

Input XML:

<root>
<wrapper>
    <item>
        <item>1.1</item>
        <item>
            <olr>outlier1</olr>
        </item>
    </item>
    <item>
        <item>2.1</item>
        <item>
            <item>
                <item>
                    <item>preceedingsibling1</item>
                    <item>preceedingsibling2</item>
                    <olr>outlier2</olr>
                    <item>followingsibling1</item>
                    <item>followingsibling2</item>
                </item>
            </item>
        </item>
    </item>
    <item>
        <item>3.1</item>
        <item>
            <item>
                <item>3.3.1</item>
            </item>
        </item>
    </item>
</wrapper>

<root>
<wrapper>
    <item>
        <item>1.1</item>
        <item>
        </item>
    </item>
    <olr>outlier1</olr>
    <item>
        <item>2.1</item>
        <item>
            <item>
                <item>
                    <item>preceedingsibling1</item>
                    <item>preceedingsibling2</item>
                </item>
            </item>
        </item>
    </item>
    <olr>outlier2</olr>
    <item>followingsibling1</item>
    <item>followingsibling2</item>
    <item>
        <item>3.1</item>
        <item>
            <item>
                <item>3.3.1</item>
            </item>
        </item>
    </item>
</wrapper>

I am trying something:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="item[descendant::olr]">
    <xsl:apply-templates select="node() except descendant::olr"/>

</xsl:template>

Body:
The below XSLT-2.0 solution would do this:

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    version="2.0">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

    <!-- identity transform template with mode='olr' -->
    <xsl:template match="@* | node()" mode="olr">
        <xsl:copy>
            <xsl:apply-templates select="@*, node()[1]" mode="olr"/>
        </xsl:copy>
        <xsl:apply-templates select="following-sibling::node()[1]" mode="olr"/>
    </xsl:template>

    <!-- identity transform template -->
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@*, node()[1]"/>
        </xsl:copy>
        <xsl:apply-templates select="following-sibling::node()[1]"/>
    </xsl:template>

    <!-- copy the olr and it's following-elements in the current element -->
    <xsl:template match="wrapper/item[descendant::olr]">
        <xsl:copy>
            <xsl:apply-templates select="@*, node()[1]" />
        </xsl:copy>
        <xsl:apply-templates select="descendant::olr[not(preceding-sibling::olr)]" mode="olr"/>
        <xsl:apply-templates select="following-sibling::node()[1]"/>
    </xsl:template>

    <!-- "do nothing for olr" template -->
    <xsl:template match="olr[ancestor::item/parent::wrapper]"/>

</xsl:stylesheet>

There are two identity transform templates(1st and 2nd) to copy the elements as-is, recursively.

The third template matches the wrapper/item with descendant::olr and specially processes olr(and its following-siblings) by copying it as its own following-sibling.

The fourth template is to do nothing for olr in the normal process.


问:
How to make one APK for the both mobile and tablet?
I want to make only one APK for mobile and tablet both. but i want that when user install the app for the mobile the layout and images of the tablet should not be installed.and same for the tablet when user install the app for the tablet the layout and images of the mobile should not be installed.</p>

```<code>Can anyone tell me how can i do this ?? any help would be apperciated.
</code>```

答:
I think don't try that

when use the images into project Android studio Create assets and compile them into all Layout and when user install apk, android install all of them but use specific layout by device property.

Body:
I want to make only one APK for mobile and tablet both. but i want that when user install the app for the mobile the layout and images of the tablet should not be installed.and same for the tablet when user install the app for the tablet the layout and images of the mobile should not be installed.

Can anyone tell me how can i do this ?? any help would be apperciated.


问:
Linux capabilities with yocto
I want to give several files Linux capabilities (e.g. CAP_NET_ADMIN).
I am using Yocto and my file system should be read-only and must not be changed after flashing the software (this means pkg_postinst with setcap that would usually work is not possible).

Is there any other way to give capabilities to files without changing the file structure after booting the target?

答:
pkg_postinst scripts already get executed while building the read-only rootfs, so this approach works. You must ensure that the commands that you call in the script are available in the build host, though, otherwise execution of the script will fail and it gets deferred to the first boot on the device. How to ensure that the setcap command is available depends on the Yocto release, this will change in Yocto 2.3. Here's a complete example recipe:

```<code>LICENSE = "MIT"

do_install () {
    install -d ${D}/${bindir}
    touch ${D}/${bindir}/foobar
}

pkg_postinst_${PN} () {
    setcap cap_chown+e "$D/${bindir}/foobar"
}
# Dependency when installing on the target.
RDEPENDS_${PN} = "libcap"
# Dependency for rootfs construction, Yocto > 2.3.
PACKAGE_WRITE_DEPS = "libcap-native"
# Dependency for rootfs construction, Yocto <= 2.3 (untested).
# Enabling this makes builds slightly less efficient with
# Yocto > 2.3 because it implies that libcap-native is
# needed for building this recipe, which isn't the case.
# DEPENDS += "libcap-native"
</code>```

Be careful to preserve xattrs. The default .tar image format drops them. From the top of https://github.com/01org/meta-intel-iot-security/blob/master/meta-security-framework/classes/xattr-images.bbclass:

```<code># xattr support is expected to be compiled into mtd-utils. We just need to
# use it.
EXTRA_IMAGECMD_jffs2_append = " --with-xattr"

# By default, OE-core uses tar from the host, which may or may not have the
# --xattrs parameter which was introduced in 1.27. For image building we
# use a recent enough tar instead.
#
# The GNU documentation does not specify whether --xattrs-include is necessary.
# In practice, it turned out to be not needed when creating archives and
# required when extracting, but it seems prudent to use it in both cases.
IMAGE_DEPENDS_tar_append = " tar-replacement-native"
EXTRANATIVEPATH += "tar-native"
IMAGE_CMD_TAR = "tar --xattrs --xattrs-include=*"
</code>```

Put this into your image recipe, if it matters.

Title: Linux capabilities with yocto

Body:
pkg_postinst scripts already get executed while building the read-only rootfs, so this approach works. You must ensure that the commands that you call in the script are available in the build host, though, otherwise execution of the script will fail and it gets deferred to the first boot on the device. How to ensure that the setcap command is available depends on the Yocto release, this will change in Yocto 2.3. Here's a complete example recipe:

LICENSE = "MIT"

do_install () {
    install -d ${D}/${bindir}
    touch ${D}/${bindir}/foobar
}

pkg_postinst_${PN} () {
    setcap cap_chown+e "$D/${bindir}/foobar"
}
# Dependency when installing on the target.
RDEPENDS_${PN} = "libcap"
# Dependency for rootfs construction, Yocto > 2.3.
PACKAGE_WRITE_DEPS = "libcap-native"
# Dependency for rootfs construction, Yocto <= 2.3 (untested).
# Enabling this makes builds slightly less efficient with
# Yocto > 2.3 because it implies that libcap-native is
# needed for building this recipe, which isn't the case.
# DEPENDS += "libcap-native"

Be careful to preserve xattrs. The default .tar image format drops them. From the top of https://github.com/01org/meta-intel-iot-security/blob/master/meta-security-framework/classes/xattr-images.bbclass:

# xattr support is expected to be compiled into mtd-utils. We just need to
# use it.
EXTRA_IMAGECMD_jffs2_append = " --with-xattr"

# By default, OE-core uses tar from the host, which may or may not have the
# --xattrs parameter which was introduced in 1.27. For image building we
# use a recent enough tar instead.
#
# The GNU documentation does not specify whether --xattrs-include is necessary.
# In practice, it turned out to be not needed when creating archives and
# required when extracting, but it seems prudent to use it in both cases.
IMAGE_DEPENDS_tar_append = " tar-replacement-native"
EXTRANATIVEPATH += "tar-native"
IMAGE_CMD_TAR = "tar --xattrs --xattrs-include=*"

Put this into your image recipe, if it matters.


问:
(Ruby) First x Recursive Nums
I want to write a recursive method that returns the first num recursive numbers.

Here is my code so far:

```<code>def recursive_factorials(num)
  return [1] if num == 1
  arr = recursive_factorials(num-1)
  arr << num * arr.last
end
</code>```

Not sure what I'm doing wrong. The expected result for num = 6 is [1, 1, 2, 6, 24, 120], and I get [1, 2, 6, 24, 120, 720], so I may be close but really have no idea.

Any help would be appreciated. Also, if I am not using recursion properly please let me out.

答:
Here is an example:</p>

```<code>def recursive_factorials(num, acc = [])
  acc << (num < 2 ? 1 : (num - 1) * recursive_factorials(num - 1, acc).last)
end
recursive_factorials 6
#⇒ [1, 1, 2, 6, 24, 120]
</code>```

Title: (Ruby) First x Recursive Nums

Body:
I want to write a recursive method that returns the first num recursive numbers.

Here is my code so far:

def recursive_factorials(num)
  return [1] if num == 1
  arr = recursive_factorials(num-1)
  arr << num * arr.last
end

Not sure what I'm doing wrong. The expected result for num = 6 is [1, 1, 2, 6, 24, 120], and I get [1, 2, 6, 24, 120, 720], so I may be close but really have no idea.

Any help would be appreciated. Also, if I am not using recursion properly please let me out.

Body:
Here is an example:

def recursive_factorials(num, acc = [])
  acc << (num < 2 ? 1 : (num - 1) * recursive_factorials(num - 1, acc).last)
end
recursive_factorials 6
#⇒ [1, 1, 2, 6, 24, 120]


问:
Display black blank screen while showing folderwisw all photo from gallery
Hi I developed one app where I want to display folder wise all photos from storage. I implemented the code for it but the problem is that when activity is created it display black blank screen for 5 sec and then display all folder.

Here is my code:

```<code>public class ImageWithFolder extends AppCompatActivity implements AdapterView.OnItemClickListener {

  List<GridViewItem> gridItems = new ArrayList<GridViewItem>();
  String redirect;
  GridView gridView;
  Bitmap bitmap;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_imagefolder);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar1);
    setSupportActionBar(toolbar);
    final ActionBar ab = getSupportActionBar();
    assert ab != null;
    ab.setDisplayHomeAsUpEnabled(true);
    Intent ii = getIntent();
    redirect = ii.getStringExtra("next_activity");
    gridView = (GridView) findViewById(R.id.gridView);
    setGridAdapter();
  }

  private void setGridAdapter() {

    createGridItems(Environment.getExternalStorageDirectory().getAbsolutePath());
    MyGridAdapter adapter = new MyGridAdapter(this, gridItems);
    gridView.setAdapter(adapter);
    gridView.setOnItemClickListener(this);

  }

  private void createGridItems(String directoryPath) {

    File[] files = new File(directoryPath).listFiles(new ImageFileFilter());
    for (File file : files) {
      if (file.isDirectory()) {
        if (file.listFiles((new DirFilter())).length > 0) {
          createGridItems(file.getAbsolutePath());
        }
        if (file.listFiles((new ImageFilter())).length > 0) {
          gridItems.add(new GridViewItem(file.getAbsolutePath(), true, null));
        }

      }
    }
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home: {
        finish();
      }
      return true;
    }
    return super.onOptionsItemSelected(item);
  }

  private boolean isImageFile(String filePath) {
    if (filePath.endsWith(".jpg") || filePath.endsWith(".png") || filePath.endsWith(".jpeg")) {
      return true;
    }
    return false;
  }

  @Override
  public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    if (redirect.equalsIgnoreCase("1")) {
      Intent ii = new Intent(ImageWithFolder.this, SelectPhotos.class);
      ii.putExtra("path", gridItems.get(i).getPath());
      startActivity(ii);
    } else if (redirect.equalsIgnoreCase("2")) {
      Intent ii = new Intent(ImageWithFolder.this, AlbumSelectPhotos.class);
      ii.putExtra("path", gridItems.get(i).getPath());
      startActivity(ii);
    }
  }

  private class ImageFileFilter implements FileFilter {

    @Override
    public boolean accept(File file) {
      if (file.isDirectory()) {
        return true;
      } else if (isImageFile(file.getAbsolutePath())) {
        return true;
      }
      return false;
    }
  }

  private class ImageFilter implements FileFilter {

    @Override
    public boolean accept(File file) {
      if (isImageFile(file.getAbsolutePath())) {
        return true;
      }
      return false;
    }
  }

  private class DirFilter implements FileFilter {
    @Override
    public boolean accept(File file) {
      if (file.isDirectory()) {
        return true;
      }
      return false;
    }
  }

}
</code>```

I am not getting what is going wrong with the code.

Can anyone give solution regarding black screen appear at the first time.

Thanks in advance.

答:
Put your read file method in async..

```<code>Call Aysnc:

new LoadData().execute()

public class LoadData extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(Void... params) {
             createGridItems(Environment.getExternalStorageDirectory().getAbsolutePath());
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            MyGridAdapter adapter = new MyGridAdapter(this, gridItems);
            gridView.setAdapter(adapter);
            gridView.setOnItemClickListener(this);
        }
    }
</code>```

If you are comfortable with RxJava then use Observal, This is the best soluton.

Body:
Hi I developed one app where I want to display folder wise all photos from storage. I implemented the code for it but the problem is that when activity is created it display black blank screen for 5 sec and then display all folder.

Here is my code:

public class ImageWithFolder extends AppCompatActivity implements AdapterView.OnItemClickListener {

  List<GridViewItem> gridItems = new ArrayList<GridViewItem>();
  String redirect;
  GridView gridView;
  Bitmap bitmap;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_imagefolder);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar1);
    setSupportActionBar(toolbar);
    final ActionBar ab = getSupportActionBar();
    assert ab != null;
    ab.setDisplayHomeAsUpEnabled(true);
    Intent ii = getIntent();
    redirect = ii.getStringExtra("next_activity");
    gridView = (GridView) findViewById(R.id.gridView);
    setGridAdapter();
  }

  private void setGridAdapter() {

    createGridItems(Environment.getExternalStorageDirectory().getAbsolutePath());
    MyGridAdapter adapter = new MyGridAdapter(this, gridItems);
    gridView.setAdapter(adapter);
    gridView.setOnItemClickListener(this);

  }

  private void createGridItems(String directoryPath) {

    File[] files = new File(directoryPath).listFiles(new ImageFileFilter());
    for (File file : files) {
      if (file.isDirectory()) {
        if (file.listFiles((new DirFilter())).length > 0) {
          createGridItems(file.getAbsolutePath());
        }
        if (file.listFiles((new ImageFilter())).length > 0) {
          gridItems.add(new GridViewItem(file.getAbsolutePath(), true, null));
        }

      }
    }
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home: {
        finish();
      }
      return true;
    }
    return super.onOptionsItemSelected(item);
  }

  private boolean isImageFile(String filePath) {
    if (filePath.endsWith(".jpg") || filePath.endsWith(".png") || filePath.endsWith(".jpeg")) {
      return true;
    }
    return false;
  }

  @Override
  public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    if (redirect.equalsIgnoreCase("1")) {
      Intent ii = new Intent(ImageWithFolder.this, SelectPhotos.class);
      ii.putExtra("path", gridItems.get(i).getPath());
      startActivity(ii);
    } else if (redirect.equalsIgnoreCase("2")) {
      Intent ii = new Intent(ImageWithFolder.this, AlbumSelectPhotos.class);
      ii.putExtra("path", gridItems.get(i).getPath());
      startActivity(ii);
    }
  }

  private class ImageFileFilter implements FileFilter {

    @Override
    public boolean accept(File file) {
      if (file.isDirectory()) {
        return true;
      } else if (isImageFile(file.getAbsolutePath())) {
        return true;
      }
      return false;
    }
  }

  private class ImageFilter implements FileFilter {

    @Override
    public boolean accept(File file) {
      if (isImageFile(file.getAbsolutePath())) {
        return true;
      }
      return false;
    }
  }

  private class DirFilter implements FileFilter {
    @Override
    public boolean accept(File file) {
      if (file.isDirectory()) {
        return true;
      }
      return false;
    }
  }

}

I am not getting what is going wrong with the code.

Can anyone give solution regarding black screen appear at the first time.

Thanks in advance.

Body:
Put your read file method in async..

Call Aysnc:

new LoadData().execute()

public class LoadData extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(Void... params) {
             createGridItems(Environment.getExternalStorageDirectory().getAbsolutePath());
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            MyGridAdapter adapter = new MyGridAdapter(this, gridItems);
            gridView.setAdapter(adapter);
            gridView.setOnItemClickListener(this);
        }
    }

If you are comfortable with RxJava then use Observal, This is the best soluton.