问:
A collection of closest values from two arrays
I'm looking for optimization of an algorithm to solve a simple problem which may be hard to explain. I'm not looking for a speed or performance but simplicity and clarity when you read the code. Maybe someone has more clever solution than mine. I imagine one-liner would probably be an overkill.

I have two collections of cells ordered by date. Each of the cell can have a price value. We can assume that there can't be a price in two cells for the same date. I want to have one collection of dates, but where is no price for the date:

which collection have a closest price from the past

if there is no price in the past, look in the future

Here's what I have so far (it gives accurate results):

const array1 = [
  { date: '2019-11-10' },
  { date: '2019-11-11' },
  { date: '2019-11-12' },
  { date: '2019-11-13' },
  { date: '2019-11-14' },
  { date: '2019-11-15', price: 10 },
  { date: '2019-11-16' },
];

const array2 = [
  { date: '2019-11-10' },
  { date: '2019-11-11' },
  { date: '2019-11-12', price: 10 },
  { date: '2019-11-13' },
  { date: '2019-11-14' },
  { date: '2019-11-15' },
  { date: '2019-11-16' },
];

const merged = Object.values(array1).map((element, index) => {
  let filled;
  if (element.price) {
    filled = 1;
  }
  if (array2[index].price) {
    filled = 2;
  }
  if (filled) {
    return {
      date: element.date,
      filled
    }
  } else {
    return {
      date: element.date
    }
  }
});

const first = merged.find(element => element.filled);

let currentFill = first && first.filled;

const emptyMap = merged.map((element, index, array) => {
  if (!element.filled) {
    return {
      date: element.date,
      empty: currentFill
    }
  }
  currentFill = element.filled;
  return element;
})

console.log(emptyMap);```

答:
To my understanding, what will probably make the code most difficult to read is the last statement: "if there is no price in the past, look in the future".

This requirement means that instead of going forward only through the collections and only applying values from previously handled elements where necessary, you have to also look ahead until something happens.

For greatest simplicity, I recommend to go once from front to back, ignoring the "look ahead" part, and then, in the resulting collection, go once from back to front copying the last reached (i. e. earliest) filled element to the ones in front:

const array1 = [
  { date: '2019-11-10' },
  { date: '2019-11-11' },
  { date: '2019-11-12' },
  { date: '2019-11-13' },
  { date: '2019-11-14' },
  { date: '2019-11-15', price: 10 },
  { date: '2019-11-16' },
]

const array2 = [
  { date: '2019-11-10' },
  { date: '2019-11-11' },
  { date: '2019-11-12', price: 10 },
  { date: '2019-11-13' },
  { date: '2019-11-14' },
  { date: '2019-11-15' },
  { date: '2019-11-16' },
]

const length = array1.length
const result = new Array(length)
let emptySource = undefined

// First run: from earlier to more recent
// Applies value for "empty" when price was available once
for (let i = 0; i < length; ++i) {
  let e1 = array1[i]
  let e2 = array2[i]
  const date = e1.date
  if (e1.price) {
    result[i] = {
      'date': date,
      'filled': 1
    }
    emptySource = 1
  } else if (e2.price) {
    result[i] = {
      'date': date,
      'filled': 2
    }
    emptySource = 2
  } else {
    result[i] = {
      'date': date,
      'empty': emptySource
    }
  }
}

// Second run: from more recent to earlier
// Finds the earliest element ever "filled",
// then applies its value to all still unset "empty" elements
// (which necessarily all have a lower index)
for (let i = length - 1; i >= 0; --i) {
  const e = result[i]
  if (e.filled) {
    emptySource = e.filled
  } else if (e.empty === undefined) {
    e.empty = emptySource
  }
}

console.log(result)
```


来源: stackexchange

问:
Bottom Sheet Above Bottom Navigation
My goal is to place a "bottom sheet" on top of a BottomNavigationView like this:

But it stays the following way. Both views collapse:

This is the xml of my main activity:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:background="@drawable/tierrota"
tools:context="com.example.juanjose.myapplication.ViajesActivity">

<!-- include main content -->
<include layout="@layout/bottomsheet" />

<!-- include bottom sheet -->
<include layout="@layout/bottom_navigation" />

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

Code of bottom_navigation:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">

<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:itemBackground="@color/colorClarito"
    app:itemIconTint="@drawable/nav_item_color_state"
    app:itemTextColor="@drawable/nav_item_color_state"
    app:menu="@menu/bottom_navigation_main" />

</RelativeLayout>
</code>```

And code of bottom sheet

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/bottom_sheet"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:behavior_hideable="false"
app:behavior_peekHeight="80dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior">

<TextView
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:background="@color/colorBackgroundSemi"
    android:gravity="center"
    android:text="Bandeja de entrada"
    android:fontFamily="@font/eraslght"
    android:textColor="@color/colorLetra"
    app:layout_anchor="@+id/bottom_navigation"
    app:layout_anchorGravity="top"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:text="coisa2"
    android:textColor="@android:color/white" />

</LinearLayout>
</code>```

I am new with these two elements. Is there someone who knows any way to achieve what I'm looking for?

I want my "bottom sheet" to act as such and can expand. My ultimate goal is to add a RecyclerView inside the BottomSheet.

答:
If you also have a CollapsingToolBar/Toolbar arrangement, this is the best solution for you:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/cord_main_content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:fitsSystemWindows="true"
        app:layout_constraintBottom_toTopOf="@id/home_bottom_navigation_view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/home_appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/home_frag_toolbar"
                style="@style/Widget.Toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:logo="@drawable/ic_infinet_logo_white"
                app:navigationIcon="@drawable/ic_back_arrow" />

        </com.google.android.material.appbar.AppBarLayout>

        <FrameLayout
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:id="@+id/home_frag_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <FrameLayout
            android:id="@+id/bottom_sheet_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white"
            android:clickable="true"
            app:behavior_hideable="true"
            app:behavior_peekHeight="@dimen/mini_player_height"
            app:behavior_skipCollapsed="false"
            app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

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

            <fragment
                android:id="@+id/player_mini_frag_container"
                android:name="com.kokonetworks.kokonet.player.PlayMusicMiniFragment"
                android:layout_width="match_parent"
                android:layout_height="@dimen/mini_player_height" />

        </FrameLayout>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/home_bottom_navigation_view"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_alignParentBottom="true"
        android:background="@color/colorPrimary"
        app:itemBackground="@color/colorPrimary"
        app:itemHorizontalTranslationEnabled="false"
        app:itemIconTint="@drawable/nav_item_background"
        app:itemTextColor="@drawable/nav_item_background"
        app:labelVisibilityMode="auto"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/home_bottom_navigation_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>
```

It ensures that:

BottomSheet is a child of the CoordinatorLayout

BottomNavigation is still rested at the bottom

CollapsingToolbar/AppBarLayout arrangement is still in place as expected

ContentLicense: CC BY-SA 3.0

Title: Bottom Sheet Above Bottom Navigation

Body:
My goal is to place a "bottom sheet" on top of a BottomNavigationView like this:

But it stays the following way. Both views collapse:

This is the xml of my main activity:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:background="@drawable/tierrota"
tools:context="com.example.juanjose.myapplication.ViajesActivity">

<include layout="@layout/bottomsheet" />

<include layout="@layout/bottom_navigation" />

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

Code of bottom_navigation:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">

<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:itemBackground="@color/colorClarito"
    app:itemIconTint="@drawable/nav_item_color_state"
    app:itemTextColor="@drawable/nav_item_color_state"
    app:menu="@menu/bottom_navigation_main" />

</RelativeLayout>

And code of bottom sheet

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/bottom_sheet"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:behavior_hideable="false"
app:behavior_peekHeight="80dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior">

<TextView
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:background="@color/colorBackgroundSemi"
    android:gravity="center"
    android:text="Bandeja de entrada"
    android:fontFamily="@font/eraslght"
    android:textColor="@color/colorLetra"
    app:layout_anchor="@+id/bottom_navigation"
    app:layout_anchorGravity="top"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:text="coisa2"
    android:textColor="@android:color/white" />

</LinearLayout>

I am new with these two elements. Is there someone who knows any way to achieve what I'm looking for?

I want my "bottom sheet" to act as such and can expand. My ultimate goal is to add a RecyclerView inside the BottomSheet.

Body:
If you also have a CollapsingToolBar/Toolbar arrangement, this is the best solution for you:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/cord_main_content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:fitsSystemWindows="true"
        app:layout_constraintBottom_toTopOf="@id/home_bottom_navigation_view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/home_appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/home_frag_toolbar"
                style="@style/Widget.Toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:logo="@drawable/ic_infinet_logo_white"
                app:navigationIcon="@drawable/ic_back_arrow" />

        </com.google.android.material.appbar.AppBarLayout>

        <FrameLayout
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:id="@+id/home_frag_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <FrameLayout
            android:id="@+id/bottom_sheet_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white"
            android:clickable="true"
            app:behavior_hideable="true"
            app:behavior_peekHeight="@dimen/mini_player_height"
            app:behavior_skipCollapsed="false"
            app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

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

            <fragment
                android:id="@+id/player_mini_frag_container"
                android:name="com.kokonetworks.kokonet.player.PlayMusicMiniFragment"
                android:layout_width="match_parent"
                android:layout_height="@dimen/mini_player_height" />

        </FrameLayout>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/home_bottom_navigation_view"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_alignParentBottom="true"
        android:background="@color/colorPrimary"
        app:itemBackground="@color/colorPrimary"
        app:itemHorizontalTranslationEnabled="false"
        app:itemIconTint="@drawable/nav_item_background"
        app:itemTextColor="@drawable/nav_item_background"
        app:labelVisibilityMode="auto"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/home_bottom_navigation_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>

It ensures that:

BottomSheet is a child of the CoordinatorLayout

BottomNavigation is still rested at the bottom

CollapsingToolbar/AppBarLayout arrangement is still in place as expected

ContentLicense: CC BY-SA 4.0


问:
React JS - Fetch with custom method
I am building a web app with react, and when I try to request to my API using a custom method (AUTH) it says I requested with the OPTIONS method.
here is my code

```<code>    await fetch(apiUrl + '/' + formState.values.email + '/' + formState.values.password,{method: 'AUTH', body: ""}).then(async (res) => {
      if (res.status === 200) {
        await res.json().then((data) => {
          localStorage.setItem('user_data', JSON.stringify(data.user_data));
          localStorage.setItem('user_auth', JSON.stringify(data.user_auth));
        });
      }
    }).then(() => {
      router.history.push('/');
    })
</code>```

but in by backend service it says different, here is the screenshot of my backend

Can Anyone help me with this problem ?

答:
You should enable CORS in your Server Application to handle origin header for external
requests.</p>

Title: React JS - Fetch with custom method

Body:
I am building a web app with react, and when I try to request to my API using a custom method (AUTH) it says I requested with the OPTIONS method.
here is my code

    await fetch(apiUrl + '/' + formState.values.email + '/' + formState.values.password,{method: 'AUTH', body: ""}).then(async (res) => {
      if (res.status === 200) {
        await res.json().then((data) => {
          localStorage.setItem('user_data', JSON.stringify(data.user_data));
          localStorage.setItem('user_auth', JSON.stringify(data.user_auth));
        });
      }
    }).then(() => {
      router.history.push('/');
    })

but in by backend service it says different, here is the screenshot of my backend

Can Anyone help me with this problem ?


问:
android - Kotlin - how to access a solid color inside a background's custom Button
I have a simple Kotlin project, with the following code :

inside an activity screen, I have a list view :

```<code>    <ListView
        android:layout_marginTop="90dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ordersListView"
        android:divider="@null"
        android:choiceMode="singleChoice"
        android:listSelector="@android:color/holo_orange_light"
        />
</code>```

this listView uses a custom row UI :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@color/white_color">

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="110dp"
        android:gravity="center_vertical"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:paddingLeft="10dp"
        android:text="Name" />

    <Button
        android:id="@+id/send_0"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="60dp"
        android:background="@drawable/blue_button"
        android:text="0" />

    <Button
        android:id="@+id/send_1"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:background="@drawable/blue_button"
        android:text="1" />

    <Button
        android:id="@+id/send_2"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="60dp"
        android:background="@drawable/blue_button"
        android:text="2" />

    <Button
        android:id="@+id/send_3"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:background="@drawable/blue_button"
        android:text="3" />
</RelativeLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_marginTop="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:background="@color/colorAccent"/>

</LinearLayout>

</code>```

the Button with id = send_0 uses a custom shape, using that code :

filename = v24/blue_button.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <solid android:color="#2E9BCA"
        android:id="@+id/solid_bng"/>

    <stroke
        android:height="1.0dip"
        android:width="1.0dip"
        android:color="#80ee82ee" />

    <corners
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
</shape>
</code>```

now, I want to change the "solid_bng" color
when I click on the Button with id = "send_0".

how can I do that ?

not sure if it is needed : I provide also my customAdapter code :
thanks for any help

:o)

Olivier

filename : CustomAdapter.kt

```<code>package fr.ormaa.o_service

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import java.util.ArrayList

class CustomAdapter(private val context: Context, private val imageModelArrayList: ArrayList<ImageModel>) : BaseAdapter() {

    override fun getViewTypeCount(): Int {
        return count
    }

    override fun getItemViewType(position: Int): Int {

        return position
    }

    override fun getCount(): Int {
        return imageModelArrayList.size
    }

    override fun getItem(position: Int): Any {
        return imageModelArrayList[position]
    }

    override fun getItemId(position: Int): Long {
        return 0
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {

        var convertView = convertView
        val holder: ViewHolder

        convertView = convertView

        if (convertView == null) {

            holder = ViewHolder()

            val inflater = context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

            convertView = inflater.inflate(R.layout.meal_item, null, true)

            holder?.tvname = convertView!!.findViewById(R.id.name) as TextView
            holder?.iv = convertView.findViewById(R.id.imgView) as ImageView

            holder?.send0 = convertView.findViewById(R.id.send_0) as Button
            holder?.send1 = convertView.findViewById(R.id.send_1) as Button
            holder?.send2 = convertView.findViewById(R.id.send_2) as Button
            holder?.send3 = convertView.findViewById(R.id.send_3) as Button

            convertView.tag = holder
        } else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = convertView.tag as ViewHolder
        }

        holder?.tvname!!.setText(imageModelArrayList[position].getNames())
        holder?.iv!!.setImageResource(imageModelArrayList[position].getImage_drawables())

        holder?.send0?.setOnTouchListener(zero_clicked)

        return convertView
    }

    private val zero_clicked = View.OnTouchListener { _, _ ->

        Toast.makeText(context,  "zero clicked", Toast.LENGTH_LONG).show()

        false
    }
    private val one_clicked = View.OnTouchListener { _, _ ->

        false
    }
    private val two_clicked = View.OnTouchListener { _, _ ->

        false
    }
    private val three_clicked = View.OnTouchListener { _, _ ->
        false
    }

    private inner class ViewHolder {

        var tvname: TextView? = null
        internal var iv: ImageView? = null

        var send0: Button? = null
        var send1: Button? = null
        var send2: Button? = null
        var send3: Button? = null

    }

}

</code>```

答:
Since you already have an access to your button in this file, you should call the setBackgroundColor() function, to which you can give the target color.

https://developer.android.com/guide/topics/ui/controls/button gives some useful information on how buttons work.
https://developer.android.com/reference/com/google/android/material/button/MaterialButton gives more details about Material Buttons.

Body:
I have a simple Kotlin project, with the following code :

inside an activity screen, I have a list view :

    <ListView
        android:layout_marginTop="90dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ordersListView"
        android:divider="@null"
        android:choiceMode="singleChoice"
        android:listSelector="@android:color/holo_orange_light"
        />

this listView uses a custom row UI :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@color/white_color">

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="110dp"
        android:gravity="center_vertical"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:paddingLeft="10dp"
        android:text="Name" />

    <Button
        android:id="@+id/send_0"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="60dp"
        android:background="@drawable/blue_button"
        android:text="0" />

    <Button
        android:id="@+id/send_1"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:background="@drawable/blue_button"
        android:text="1" />

    <Button
        android:id="@+id/send_2"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="60dp"
        android:background="@drawable/blue_button"
        android:text="2" />

    <Button
        android:id="@+id/send_3"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:background="@drawable/blue_button"
        android:text="3" />
</RelativeLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_marginTop="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:background="@color/colorAccent"/>

</LinearLayout>

the Button with id = send_0 uses a custom shape, using that code :

filename = v24/blue_button.xml

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <solid android:color="#2E9BCA"
        android:id="@+id/solid_bng"/>

    <stroke
        android:height="1.0dip"
        android:width="1.0dip"
        android:color="#80ee82ee" />

    <corners
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
</shape>

now, I want to change the "solid_bng" color
when I click on the Button with id = "send_0".

how can I do that ?

not sure if it is needed : I provide also my customAdapter code :
thanks for any help

:o)

Olivier

filename : CustomAdapter.kt

package fr.ormaa.o_service

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import java.util.ArrayList

class CustomAdapter(private val context: Context, private val imageModelArrayList: ArrayList<ImageModel>) : BaseAdapter() {

    override fun getViewTypeCount(): Int {
        return count
    }

    override fun getItemViewType(position: Int): Int {

        return position
    }

    override fun getCount(): Int {
        return imageModelArrayList.size
    }

    override fun getItem(position: Int): Any {
        return imageModelArrayList[position]
    }

    override fun getItemId(position: Int): Long {
        return 0
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {

        var convertView = convertView
        val holder: ViewHolder

        convertView = convertView

        if (convertView == null) {

            holder = ViewHolder()

            val inflater = context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

            convertView = inflater.inflate(R.layout.meal_item, null, true)

            holder?.tvname = convertView!!.findViewById(R.id.name) as TextView
            holder?.iv = convertView.findViewById(R.id.imgView) as ImageView

            holder?.send0 = convertView.findViewById(R.id.send_0) as Button
            holder?.send1 = convertView.findViewById(R.id.send_1) as Button
            holder?.send2 = convertView.findViewById(R.id.send_2) as Button
            holder?.send3 = convertView.findViewById(R.id.send_3) as Button

            convertView.tag = holder
        } else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = convertView.tag as ViewHolder
        }

        holder?.tvname!!.setText(imageModelArrayList[position].getNames())
        holder?.iv!!.setImageResource(imageModelArrayList[position].getImage_drawables())

        holder?.send0?.setOnTouchListener(zero_clicked)

        return convertView
    }

    private val zero_clicked = View.OnTouchListener { _, _ ->

        Toast.makeText(context,  "zero clicked", Toast.LENGTH_LONG).show()

        false
    }
    private val one_clicked = View.OnTouchListener { _, _ ->

        false
    }
    private val two_clicked = View.OnTouchListener { _, _ ->

        false
    }
    private val three_clicked = View.OnTouchListener { _, _ ->
        false
    }

    private inner class ViewHolder {

        var tvname: TextView? = null
        internal var iv: ImageView? = null

        var send0: Button? = null
        var send1: Button? = null
        var send2: Button? = null
        var send3: Button? = null

    }

}


问:
SQL: SELECT rows with max date from created table
I´m wondering how to create a query that returns SERIALID, QTY, but only for the last INVOICEDATE.

To combine information from two tables I use UNION.

```<code>SELECT ab.SERIALID, ab.QTY, ab.INVOICEDATE
FROM (SELECT a.INVOICEDATE, a.SERIALID, a.QTY
      FROM SALESTRANS a
      UNION
      SELECT b.INVOICEDATE, b.SERIALID, b.QTY
      FROM SERVICETRANS b
     ) ab
</code>```

I have two tables combined with UNION and my table looks:

I would like to make a query that returns SERIALID, QTY, but only for the last INVOICEDDATE.

The result I would like to get:

Thanks in advance!

答:
Many databases support LEAST()/GREATEST().  Perhaps the most efficient method assuming there are no duplicates is:

```<code>WITH i AS (
      SELECT sat.INVOICEDATE, sat.SERIALID, sat.QTY
      FROM SALESTRANS sat
      UNION ALL
      SELECT set.INVOICEDATE, set.SERIALID, set.QTY
      FROM SERVICETRANS sat
     )
SELECT i.*
FROM (SELECT i.*,
             ROW_NUMBER() OVER (PARTITION BY SERIALID ORDER BY INVOICEDATE DESC) as seqnum
      FROM i
     ) i
WHERE seqnum = 1;
</code>```

Note that if there are two invoices on the same date, this arbitrarily returns one of them.  Use RANK() if you want both.

Note that this uses UNION ALL, not UNION.  UNION incurs overhead for removing duplicates.  That does not seem useful for a query like this.

Depending on your database (and data), there are possibly alternative ways of expressing this query, some might have better performance characteristics.

Body:
I´m wondering how to create a query that returns SERIALID, QTY, but only for the last INVOICEDATE.

To combine information from two tables I use UNION.

SELECT ab.SERIALID, ab.QTY, ab.INVOICEDATE
FROM (SELECT a.INVOICEDATE, a.SERIALID, a.QTY
      FROM SALESTRANS a
      UNION
      SELECT b.INVOICEDATE, b.SERIALID, b.QTY
      FROM SERVICETRANS b
     ) ab

I have two tables combined with UNION and my table looks:

I would like to make a query that returns SERIALID, QTY, but only for the last INVOICEDDATE.

The result I would like to get:

Thanks in advance!

Body:
Many databases support LEAST()/GREATEST().  Perhaps the most efficient method assuming there are no duplicates is:

WITH i AS (
      SELECT sat.INVOICEDATE, sat.SERIALID, sat.QTY
      FROM SALESTRANS sat
      UNION ALL
      SELECT set.INVOICEDATE, set.SERIALID, set.QTY
      FROM SERVICETRANS sat
     )
SELECT i.*
FROM (SELECT i.*,
             ROW_NUMBER() OVER (PARTITION BY SERIALID ORDER BY INVOICEDATE DESC) as seqnum
      FROM i
     ) i
WHERE seqnum = 1;

Note that if there are two invoices on the same date, this arbitrarily returns one of them.  Use RANK() if you want both.

Note that this uses UNION ALL, not UNION.  UNION incurs overhead for removing duplicates.  That does not seem useful for a query like this.

Depending on your database (and data), there are possibly alternative ways of expressing this query, some might have better performance characteristics.


问:
Why are braces needed for preprocessor in order to have statement?
Having this code:

```<code>#define GREATER(a, b, res) ( \ /* no braces here */
    asm("cmp %1, %2\n\t" \
         "jge 0f\n\t" \
         "movl %1, %0\n\t" \
         "jmp 1f\n" \
         "0:\n\t" \
         "movl %2, %0\n" \
         "1:" \
         : "=r"(res) \
         : "r"(a), "r"(b)); )
</code>```

Error:
c.c:4:2: error: expected expression before ‘asm’
  asm("cmp %1, %2\n\t" \

But this one (only changed braces, everything else is left - the code is otherwise correct):

```<code>#define GREATER(a, b, res) ({ \ /* used braces here - correct */
    asm("cmp %1, %2\n\t" \
         "jge 0f\n\t" \
         "movl %1, %0\n\t" \
         "jmp 1f\n" \
         "0:\n\t" \
         "movl %2, %0\n" \
         "1:" \
         : "=r"(res) \
         : "r"(a), "r"(b)); })
</code>```

Will compile with no error.
But the only changed is added braces. So why are they needed? What does the preprocessor assume to be statement? (If only means being in braces.) I have seen other macro functions declared only in parenthesis (no curly braces), so why this one should have ones?

答:
The preprocessor directives are not involved in this issue. The issues are:

asm(…) is a GCC extension to the C language. GCC treats asm, which must be followed by a ;, as a statement.

Parentheses are parts of expressions. When you write (…), the contents of the parentheses should be an expression. Since asm is not an expression, (asm(…);) is an error.

GCC has an extension called statement expressions, in which ({…}) has a value like an expression but may contain statements. Inside ({…}), you may put statements inside the braces, and GCC will evaluate them and use the value of the last expression statement1 in them as the value of the ({…}) expression. (The last statement in ({…}) should be an expression statement, as opposed to some other kind of statement, just as a for loop.)

Thus ({ asm(…); }) is accepted as an expression.

However, although GCC accepts it, it is violating the statement in GCC’s documentation that “The last thing in the compound statement should be an expression followed by a semicolon…”. It does not look like your macro is intended to be used as an expression; it puts a result in res but does not itself have a value. In this case, you can make it simply a statement by removing the parentheses from your original code:

```<code>#define GREATER(a, b, res) \
    asm("cmp %1, %2\n\t" \
         "jge 0f\n\t" \
         "movl %1, %0\n\t" \
         "jmp 1f\n" \
         "0:\n\t" \
         "movl %2, %0\n" \
         "1:" \
         : "=r"(res) \
         : "r"(a), "r"(b));
</code>```

Additionally, people often prefer to leave off the final ; in such macros, because then the macro can be written like a statement when used in source code:

```<code>GREATER(a, b, res);
</code>```

instead of looking odd to people who are accustomed to statements ending with ;:

```<code>GREATER(a, b, res)
</code>```

(Although with the ; in the definition, you can still write GREATER(a, b, res);, but this expands to have ;;, and that can cause problems, because if (foo) GREATER(a, b, res); else… will fail to associate that else with that if because of the extra ;.)

Footnote

1 A statement expression is an expression followed by a ;.

Body:
Having this code:

#define GREATER(a, b, res) ( \ /* no braces here */
    asm("cmp %1, %2\n\t" \
         "jge 0f\n\t" \
         "movl %1, %0\n\t" \
         "jmp 1f\n" \
         "0:\n\t" \
         "movl %2, %0\n" \
         "1:" \
         : "=r"(res) \
         : "r"(a), "r"(b)); )

Error:
c.c:4:2: error: expected expression before ‘asm’
  asm("cmp %1, %2\n\t" \

But this one (only changed braces, everything else is left - the code is otherwise correct):

#define GREATER(a, b, res) ({ \ /* used braces here - correct */
    asm("cmp %1, %2\n\t" \
         "jge 0f\n\t" \
         "movl %1, %0\n\t" \
         "jmp 1f\n" \
         "0:\n\t" \
         "movl %2, %0\n" \
         "1:" \
         : "=r"(res) \
         : "r"(a), "r"(b)); })

Will compile with no error.
But the only changed is added braces. So why are they needed? What does the preprocessor assume to be statement? (If only means being in braces.) I have seen other macro functions declared only in parenthesis (no curly braces), so why this one should have ones?

Body:
The preprocessor directives are not involved in this issue. The issues are:

asm(…) is a GCC extension to the C language. GCC treats asm, which must be followed by a ;, as a statement.

Parentheses are parts of expressions. When you write (…), the contents of the parentheses should be an expression. Since asm is not an expression, (asm(…);) is an error.

GCC has an extension called statement expressions, in which ({…}) has a value like an expression but may contain statements. Inside ({…}), you may put statements inside the braces, and GCC will evaluate them and use the value of the last expression statement1 in them as the value of the ({…}) expression. (The last statement in ({…}) should be an expression statement, as opposed to some other kind of statement, just as a for loop.)

Thus ({ asm(…); }) is accepted as an expression.

However, although GCC accepts it, it is violating the statement in GCC’s documentation that “The last thing in the compound statement should be an expression followed by a semicolon…”. It does not look like your macro is intended to be used as an expression; it puts a result in res but does not itself have a value. In this case, you can make it simply a statement by removing the parentheses from your original code:

#define GREATER(a, b, res) \
    asm("cmp %1, %2\n\t" \
         "jge 0f\n\t" \
         "movl %1, %0\n\t" \
         "jmp 1f\n" \
         "0:\n\t" \
         "movl %2, %0\n" \
         "1:" \
         : "=r"(res) \
         : "r"(a), "r"(b));

Additionally, people often prefer to leave off the final ; in such macros, because then the macro can be written like a statement when used in source code:

GREATER(a, b, res);

instead of looking odd to people who are accustomed to statements ending with ;:

GREATER(a, b, res)

(Although with the ; in the definition, you can still write GREATER(a, b, res);, but this expands to have ;;, and that can cause problems, because if (foo) GREATER(a, b, res); else… will fail to associate that else with that if because of the extra ;.)

Footnote

1 A statement expression is an expression followed by a ;.


问:
AttributeError: module 'cv2.cv2' has no attribute 'release'
I come from RDBMS background and just starting on python. below is a simple code i written to invoke my web cam via python

```<code>import cv2

vid = cv2.VideoCapture(0)
 while vid == True:
     print("Connected....");
if cv2.waitKey(0) : break

cv2.release();
</code>```

but i am getting error

```<code>AttributeError: module 'cv2.cv2' has no attribute 'release'
</code>```

while executing it. I am running this code using python3.5 and on linux 14.04 platform. I can see cv2 package installed via help("modules") list and it gets imported as well without error . however i dont see it in the interpreter list of pycharm. please help.

答:
import cv2
import numpy

img = cv2.imread("lena.jpg", 1)
cv2.imshow("image", img)
cv2.waitKeyEx(0)
cv2.destroyAllWindows()

Body:
I come from RDBMS background and just starting on python. below is a simple code i written to invoke my web cam via python

import cv2

vid = cv2.VideoCapture(0)
 while vid == True:
     print("Connected....");
if cv2.waitKey(0) : break

cv2.release();

but i am getting error

AttributeError: module 'cv2.cv2' has no attribute 'release'

while executing it. I am running this code using python3.5 and on linux 14.04 platform. I can see cv2 package installed via help("modules") list and it gets imported as well without error . however i dont see it in the interpreter list of pycharm. please help.


问:
Xquartz and MacOS Sierra
I am facing issue to make some of my applications that run under XQuartz work. This happened after I have updated my OS to Sierra version. I didn't have these issues with the previous OS versions.
when I try to Open any of my application like Winskin, and other applications in my field. I get the error message that is titled The application X11 could not be opened. and follows with An error occurred while starting the X11 server: "Failed to activate core devices." this for Winskin. in another application, ADF, ADF I got "An error occurred while starting the X11 server: "Unrecognized option: -iglx".
I looked it up online, I haven't find a solution yet. Any advice would be appreciated.
Thank you !

答:
The problem is likely that the remote machine wants to use "Indirect GLX", and that is disabled on your Mac.  From this web page:  https://www.visitusers.org/index.php?title=Re-enabling_INdirect_glx_on_your_X_server, the instructions for MacOS are to run this in your terminal:

```<code>defaults write org.macosforge.xquartz.X11 enable_iglx -bool true
</code>```

You have to restart XQuartz after this, and things should work again.

Do note however, that the reason IGLX is normally disabled is that it's a likely security risk:  make sure you trust the application that's running remotely if you choose to do this.  See this commit to xorg for some discussion: https://gitlab.freedesktop.org/xorg/xserver/commit/d0da0e9c3bb8fe0cd4879ecb24d21715bfaa209b.

Title: Xquartz and MacOS Sierra

Body:
The problem is likely that the remote machine wants to use "Indirect GLX", and that is disabled on your Mac.  From this web page:  https://www.visitusers.org/index.php?title=Re-enabling_INdirect_glx_on_your_X_server, the instructions for MacOS are to run this in your terminal:

defaults write org.macosforge.xquartz.X11 enable_iglx -bool true

You have to restart XQuartz after this, and things should work again.

Do note however, that the reason IGLX is normally disabled is that it's a likely security risk:  make sure you trust the application that's running remotely if you choose to do this.  See this commit to xorg for some discussion: https://gitlab.freedesktop.org/xorg/xserver/commit/d0da0e9c3bb8fe0cd4879ecb24d21715bfaa209b.


问:
Is there a way to assign automatic values to a 2D array in Python with a specific pattern without filling the whole array with just one value?
I'm trying to create a really basic snake-like console game just to test Python's functionality, yet I'm having issues with an algorithm I created for setting up the game map. I need the map borders to be set up as '#' and the map body as a space ' ' but for some reason the whole map is being shown as hashes, even after printing out the results in the decisive if function. Here's the code:

```<code>class GameMap:
def __init__(self):
    self.border_icon = '#'
    self.body_icon = ' '
    self.x_size = 0
    self.y_size = 0
    self.map_grid = []

def create_grid(self, map_size):
    if map_size == 1:
        self.x_size = 40
        self.y_size = 20
    elif map_size == 2:
        self.x_size = 80
        self.y_size = 40
    else:
        self.x_size = 120
        self.y_size = 60

    self.map_grid = [[None]*self.x_size]*self.y_size

    for row in range(self.y_size):
        for column in range(self.x_size):
            if row==0 or row==self.y_size-1 or column==0 or column==self.x_size-1:
                print('set: '+self.border_icon)
                self.map_grid[row][column] = self.border_icon
            else:
                print('set: '+self.body_icon)
                self.map_grid[row][column] = self.body_icon

def setup(self, map_type):
    map_templates = {
        1: 'Small Map (40x20)',
        2: 'Medium Map (80x40)',
        3: 'Big Map (120x60)'
    }
    if map_type not in map_templates:
        print('Invalid map type, starting a game with the default configuration...')
        map_type = 1

    print('Starting game: '+map_templates.get(map_type,'Invalid map type'))
    self.create_grid(map_type)
</code>```

This is the map class, in order to access it I just create a map object and call for the setup.
The issue is that whenever I display the matrix, the whole map is filled with '#' and no spaces whatsoever. Is there a reason for this?

答:
I just changed that block:

```<code> for row in range(self.y_size):
    for column in range(self.x_size):
        if row==0 or row==self.y_size-1 or column==0 or column==self.x_size-1:
            print('set: '+self.border_icon)
            self.map_grid[row][column] = self.border_icon
        else:
            print('set: '+self.body_icon)
            self.map_grid[row][column] = self.body_icon
</code>```

and I think it works

```<code>    row=0
    column=0
    while(row<=self.x_size):
        while(column<=self.y_size):
            if row==0 or row==self.x_size:
                print("#",end="")
            elif column==0 or column==self.y_size:
                print("#",end="")
            else:
                print(" ",end="")
            column=column+1
        column=0
        print()
        row=row+1
</code>```

Body:
I'm trying to create a really basic snake-like console game just to test Python's functionality, yet I'm having issues with an algorithm I created for setting up the game map. I need the map borders to be set up as '#' and the map body as a space ' ' but for some reason the whole map is being shown as hashes, even after printing out the results in the decisive if function. Here's the code:

class GameMap:
def __init__(self):
    self.border_icon = '#'
    self.body_icon = ' '
    self.x_size = 0
    self.y_size = 0
    self.map_grid = []

def create_grid(self, map_size):
    if map_size == 1:
        self.x_size = 40
        self.y_size = 20
    elif map_size == 2:
        self.x_size = 80
        self.y_size = 40
    else:
        self.x_size = 120
        self.y_size = 60

    self.map_grid = [[None]*self.x_size]*self.y_size

    for row in range(self.y_size):
        for column in range(self.x_size):
            if row==0 or row==self.y_size-1 or column==0 or column==self.x_size-1:
                print('set: '+self.border_icon)
                self.map_grid[row][column] = self.border_icon
            else:
                print('set: '+self.body_icon)
                self.map_grid[row][column] = self.body_icon

def setup(self, map_type):
    map_templates = {
        1: 'Small Map (40x20)',
        2: 'Medium Map (80x40)',
        3: 'Big Map (120x60)'
    }
    if map_type not in map_templates:
        print('Invalid map type, starting a game with the default configuration...')
        map_type = 1

    print('Starting game: '+map_templates.get(map_type,'Invalid map type'))
    self.create_grid(map_type)

This is the map class, in order to access it I just create a map object and call for the setup.
The issue is that whenever I display the matrix, the whole map is filled with '#' and no spaces whatsoever. Is there a reason for this?

Body:
I just changed that block:

 for row in range(self.y_size):
    for column in range(self.x_size):
        if row==0 or row==self.y_size-1 or column==0 or column==self.x_size-1:
            print('set: '+self.border_icon)
            self.map_grid[row][column] = self.border_icon
        else:
            print('set: '+self.body_icon)
            self.map_grid[row][column] = self.body_icon

and I think it works

    row=0
    column=0
    while(row<=self.x_size):
        while(column<=self.y_size):
            if row==0 or row==self.x_size:
                print("#",end="")
            elif column==0 or column==self.y_size:
                print("#",end="")
            else:
                print(" ",end="")
            column=column+1
        column=0
        print()
        row=row+1


问:
Complex JS onclick events from multiple elements
Ok ( the title may be misleading ) however it is the best i can come up with.

What we want to achieve ?

Ok we have an svg map, of Australia.

On click of a state on that map, the map state changes colour to selected. ( in our case Pink )
At the same time ( a useless button ) which is on page load blank, changes its value to that of the state.
Simultaneously a drop down menu, with the state names in, which on page load has the value , Please Select , changes its value to that of the state.

So : here is what happens.

User visits page and sees map. They also see drop down select box.

They can choose to either click the select dropdown, or click the map.

Scenario 1.
They click the map, and click on the state QUEENSLAND , which has a value of QLD.

On clicking the state, the state changes from grey to pink.
The select drop down, changes from Please select, to Queensland
The gray button changes from blank to QLD

Here is an image:

Ok what we have working is.

The map click events work, and propagate the grey button values, so thats all fine.
The select element works, in so far as if we select a state on the map it changes select box value.

What we dont have working is.

on click of map, we cannot propagate BOTH the select drop down and the gray button values.

we cannot on using the select drop down box, change the "select" state of the map , ie, doesnt change from grey to pink. Also it doesnt change the value of the button from its current value.

So here is some code:

Its SVG so here is the wrap element for the map.

```<code><a xlink:href="javascript:void goToOption(document.australia.state,'WA')" target="_top">
    <path
        id="WA"
        class="territory"
        fill="#a9a9a9"
        onmouseup="clickTerritory(evt)"
        d="m 38.318056,168.24244 c -4.79245,0.99662 -8.64245,1.61598 l -7,1.12612 -8.18526,4.91727 -8.18526,4.91727 -5.31474,-0.0902 c -2.92311,-0.0496 -6.88974,-0.54005 -8.81474,-1.08988 z"/></a>
</code>```

Here is the JS that controls the map click events:

```<code>function prepare(){}
function ready(){
    svgdoc = document.sv.getSVGDocument();
    svgRoot = svgdoc.documentElement;
}
function onTerritoryClick(territory){
    document.getElementById("territory-name").innerHTML=territory;
}

var selected_territory = "None";

  function init(evt) {
    if (window.svgDocument == null)
    {
        svgDocument = evt.target.ownerDocument;
    }
  }

  function clickTerritory(evt) {
    var clicked_territory;

    if (evt.target.parentNode.getAttributeNS(null, "id") != "australia-map")
    {
        // Hack to deal with groups
        clicked_territory = evt.target.parentNode;
    } else {
        clicked_territory = evt.target;
    }

    if (selected_territory != clicked_territory) {
        if (selected_territory != "None") {
            // Unselect previous territory
            selected_territory.setAttributeNS(null, "fill", "#a9a9a9");
        }
        selected_territory = clicked_territory;
        selected_territory.setAttributeNS(null, "fill", "#ec008c");
        top.onTerritoryClick(selected_territory.getAttributeNS(null, "id"));
    }
  }
</code>```

Here is the JS to handle the select box, which fires the href.

```<code>function goToOption(sel, val) {
  var opt, o = 0;
  while (opt = sel[o++]) if (opt.value == val) sel.selectedIndex = o - 1;
}
</code>```

Here is the button html:

```<code><div class="selected-state left">
    <button id="territory-name" class="mystate grayNohover button" style="position:absolute;top:250px;left:50px">ALL</button>
</div>
</code>```

Here is the select menu html:

```<code><select name="state" id="speedF" style="width:180px;">
<option value="">Please Select</option>
<option value="QLD">Queensland</option>
<option value="NT">Northern Territory</option>
<option value="WA">Western Australia</option>
<option value="SA">South Australia</option>
<option value="NSW">New South Wales</option>
<option value="VIC">Victoria</option>
<option value="ACT">A.C.T.</option>
<option value="TAS">Tasmania</option>
</select>
</code>```

sample: http://sitehelp.com.au/demos/svgmap2/

Version 2: http://dev.30.com.au/422-svg/

答:
For problem 2: add an onchange event to the dropdown.

```<code><select onchange="handlechange()">
</code>```

The handlechange function can get the value and use it to call clickterritory()

I'm not seeing question 1, as it appears to be working for me in your demos.

Body:
Ok ( the title may be misleading ) however it is the best i can come up with.

What we want to achieve ?

Ok we have an svg map, of Australia.

On click of a state on that map, the map state changes colour to selected. ( in our case Pink )
At the same time ( a useless button ) which is on page load blank, changes its value to that of the state.
Simultaneously a drop down menu, with the state names in, which on page load has the value , Please Select , changes its value to that of the state.

So : here is what happens.

User visits page and sees map. They also see drop down select box.

They can choose to either click the select dropdown, or click the map.

Scenario 1.
They click the map, and click on the state QUEENSLAND , which has a value of QLD.

On clicking the state, the state changes from grey to pink.
The select drop down, changes from Please select, to Queensland
The gray button changes from blank to QLD

Here is an image:

Ok what we have working is.

The map click events work, and propagate the grey button values, so thats all fine.
The select element works, in so far as if we select a state on the map it changes select box value.

What we dont have working is.

on click of map, we cannot propagate BOTH the select drop down and the gray button values.

we cannot on using the select drop down box, change the "select" state of the map , ie, doesnt change from grey to pink. Also it doesnt change the value of the button from its current value.

So here is some code:

Its SVG so here is the wrap element for the map.

    <path
        id="WA"
        class="territory"
        fill="#a9a9a9"
        onmouseup="clickTerritory(evt)"
        d="m 38.318056,168.24244 c -4.79245,0.99662 -8.64245,1.61598 l -7,1.12612 -8.18526,4.91727 -8.18526,4.91727 -5.31474,-0.0902 c -2.92311,-0.0496 -6.88974,-0.54005 -8.81474,-1.08988 z"/>

Here is the JS that controls the map click events:

function prepare(){}
function ready(){
    svgdoc = document.sv.getSVGDocument();
    svgRoot = svgdoc.documentElement;
}
function onTerritoryClick(territory){
    document.getElementById("territory-name").innerHTML=territory;
}

var selected_territory = "None";

  function init(evt) {
    if (window.svgDocument == null)
    {
        svgDocument = evt.target.ownerDocument;
    }
  }

  function clickTerritory(evt) {
    var clicked_territory;

    if (evt.target.parentNode.getAttributeNS(null, "id") != "australia-map")
    {
        // Hack to deal with groups
        clicked_territory = evt.target.parentNode;
    } else {
        clicked_territory = evt.target;
    }

    if (selected_territory != clicked_territory) {
        if (selected_territory != "None") {
            // Unselect previous territory
            selected_territory.setAttributeNS(null, "fill", "#a9a9a9");
        }
        selected_territory = clicked_territory;
        selected_territory.setAttributeNS(null, "fill", "#ec008c");
        top.onTerritoryClick(selected_territory.getAttributeNS(null, "id"));
    }
  }

Here is the JS to handle the select box, which fires the href.

function goToOption(sel, val) {
  var opt, o = 0;
  while (opt = sel[o++]) if (opt.value == val) sel.selectedIndex = o - 1;
}

Here is the button html:

    <button id="territory-name" class="mystate grayNohover button" style="position:absolute;top:250px;left:50px">ALL</button>

Here is the select menu html:

<select name="state" id="speedF" style="width:180px;">
<option value="">Please Select</option>
<option value="QLD">Queensland</option>
<option value="NT">Northern Territory</option>
<option value="WA">Western Australia</option>
<option value="SA">South Australia</option>
<option value="NSW">New South Wales</option>
<option value="VIC">Victoria</option>
<option value="ACT">A.C.T.</option>
<option value="TAS">Tasmania</option>
</select>

sample: http://sitehelp.com.au/demos/svgmap2/

Version 2: http://dev.30.com.au/422-svg/

Body:
For problem 2: add an onchange event to the dropdown.

<select onchange="handlechange()">

The handlechange function can get the value and use it to call clickterritory()

I'm not seeing question 1, as it appears to be working for me in your demos.


问:
Append a json object to another json object java
I have a two json objects

```<code>JSONObject org_query = new JSONObject("{\"query\": {\"bool\": {\"must\": [], \"must_not\": [], \"should\": []}}}");

JSONObject query_form = new JSONObject("{\"match_phrase\": {\"Sales Channel\": \"Online\"}}");
</code>```

I want to append the second object to first one inside the key must and form a new JSON object.

Required Output:

```<code>{"query":{"bool":{"must_not":[],"should":[],"must":[{"match_phrase": {"Sales Channel": "Online"}}]}}}
</code>```

I tried this,

```<code>org_query["query"]["bool"]["must"].append(query_form);
</code>```

But shows error.

```<code>array type expected found org.json.jsonarray java
</code>```

How to make it

答:
You can use small json library</p>

```<code>JsonValue org_query = JsonParser.parse("{\"query\": {\"bool\": {\"must\": [], \"must_not\": [], \"should\": []}}}");
JsonValue query_form = JsonParser.parse("{\"match_phrase\": {\"Sales Channel\": \"Online\"}}");
JsonValue must = org_query.findFirst(SPM.path("query", "bool", "must"));
must.asArray().add(query_form);
String result = org_query.toCompactString();
</code>```

Body:
I have a two json objects

JSONObject org_query = new JSONObject("{\"query\": {\"bool\": {\"must\": [], \"must_not\": [], \"should\": []}}}");

JSONObject query_form = new JSONObject("{\"match_phrase\": {\"Sales Channel\": \"Online\"}}");

I want to append the second object to first one inside the key must and form a new JSON object.

Required Output:

{"query":{"bool":{"must_not":[],"should":[],"must":[{"match_phrase": {"Sales Channel": "Online"}}]}}}

I tried this,

org_query["query"]["bool"]["must"].append(query_form);

But shows error.

array type expected found org.json.jsonarray java

How to make it

Body:
You can use small json library

JsonValue org_query = JsonParser.parse("{\"query\": {\"bool\": {\"must\": [], \"must_not\": [], \"should\": []}}}");
JsonValue query_form = JsonParser.parse("{\"match_phrase\": {\"Sales Channel\": \"Online\"}}");
JsonValue must = org_query.findFirst(SPM.path("query", "bool", "must"));
must.asArray().add(query_form);
String result = org_query.toCompactString();


问:
Keep WatchKit Extension code (git repo) separated from the existing iPhone code (repo)
I wanted to add a WatchKit Extension (with SwiftUI supported on iOS13+) to my existing app (target iOS12) while keeping both codebase separated (two repos).

How can I separate the WatchKit Extension code from the Mobile One?

Will my Watch App with SwiftUI only work for users with WatchOS 6 and iOS13 without affecting the existing users with iOS12?

How about the app binary size increase?

Thanks for reading!

答:
I am not sure if there is a simpler solution, but this one should work:

Separation of both apps:

If you open in Xcode the Source Control navigator, you see that Branches, Tags and Remotes belong to a main entry in the Project navigator, i.e. to a Xcode project. So in order to have separate repos, you need separate Xcode projects to which you can assign separate repos.

You can however have multiple projects in one workspace, so that all files are available in this workspace.

To have one standalone app, and one app with a watch extension, just setup a workspace with your standalone app, and add another new project.  This new project needs all files of the original app plus the watch extension.

Since you need files from one project also in the other, you could drag them from one project to the new one, but then they will be copied (a green + badge is shown during dragging). Usually this is not what you want, since you usually don’t want to maintain two copies separately. Instead, you can show such a file in the finder, and then drag it from the finder to the new project. In this case, you have the option only to copy the reference.

Independence of both apps:

Since you have two separate projects, you can set the deployment target in the target’s build settings as required.

Size:

Each project will get separate products, the standalone app only an xxx.app, and the new project xxx.app, Watch.app, and Watch Extension.appex. So there should be no overhead.

EDIT (due to the comment of Ouadie in his question):

I am not sure if I understand your problem:

With the procedure above, you get a single workspace with two separate projects that share part of the files.

The „mobile project“ is the same as you use right now. It has only a single target (despite of test targets) that is built exclusively with the sources required. It has thus the same size as now.

The „watch project“ is new. It has 3 targets, the „mobile“ target, the Watch target, and the Watch Extension target (despite of test targets). It is built with the shared sources, and the additional watch extension sources. Its size is thus larger, but the increase depends of course on your sources.

Since you have 2 repos, the projects are decoupled, but both repos share some files. If you want to decouple them completely, you could copy the files from your current project to your new project (instead of copying only references), but then you had to maintain 2 copies.

I hope this helps!


问:
How to enforce resource level permissions with OData
I've been reading through documentation on OData, but I haven't been able to find anything about resource level access control.

In an OData example, the person russellwhyte is fetching trip 1003.  But how can I verify that the requester has access to both People = 'russellwhyte' and Trip = 1003?  What if the requester had access to 'rusellwhyte', but changed trip 1003, to 1004 which belongs to another person, and therefore the request should be rejected because 1004 belongs to another person, and because the requester doesn't have access to trip 1004.

```<code>GET
serviceRoot/People('russellwhyte')/Trips(1003)
</code>```

The request above could be rejected for three reasons,

The requester doesn't have permission to access russelwhyte's data.

The requester doesn't have permission to access trip 1003.

The requester changes the trip Id to an invalid one, 1004.  (1004 belong to another person)

If this was a simple route definition ([Route("people/{personId}/trips/{tripId}")]) I could grab both Ids from the request then perform the necessary permission checks, but I haven't found its equivalent for OData.

答:
When trips is evaluated, it should already have the filter of personId, for instance if the tripId was not specified then the query that is executed should be something similar to this Linq to Entities expression

```<code>from p in db.People
where p.Id == personId
select p.Trips
</code>```

So when tripId is present, the only difference should be that the response applies a further filter over the top of the previous query.

This way, when the wrong tripId or personId is provided, the result would be either an empty object or Http 404, Not Found. (depending on your implementation)

You have not mentioned what middleware, OData version or ORM you are using so it's all speculation, on OData v4 using the ASP.Net ODataLib, I had to implement my own logic on each controller that I wanted to support this type of nested navigation but the convention was the same, each navigation route level added a new criteria to the select query over the top of the query provided by the parent route's controller.

Body:
I've been reading through documentation on OData, but I haven't been able to find anything about resource level access control.

In an OData example, the person russellwhyte is fetching trip 1003.  But how can I verify that the requester has access to both People = 'russellwhyte' and Trip = 1003?  What if the requester had access to 'rusellwhyte', but changed trip 1003, to 1004 which belongs to another person, and therefore the request should be rejected because 1004 belongs to another person, and because the requester doesn't have access to trip 1004.

GET
serviceRoot/People('russellwhyte')/Trips(1003)

The request above could be rejected for three reasons,

The requester doesn't have permission to access russelwhyte's data.

The requester doesn't have permission to access trip 1003.

The requester changes the trip Id to an invalid one, 1004.  (1004 belong to another person)

If this was a simple route definition ([Route("people/{personId}/trips/{tripId}")]) I could grab both Ids from the request then perform the necessary permission checks, but I haven't found its equivalent for OData.

Body:
When trips is evaluated, it should already have the filter of personId, for instance if the tripId was not specified then the query that is executed should be something similar to this Linq to Entities expression

from p in db.People
where p.Id == personId
select p.Trips

So when tripId is present, the only difference should be that the response applies a further filter over the top of the previous query.

This way, when the wrong tripId or personId is provided, the result would be either an empty object or Http 404, Not Found. (depending on your implementation)

You have not mentioned what middleware, OData version or ORM you are using so it's all speculation, on OData v4 using the ASP.Net ODataLib, I had to implement my own logic on each controller that I wanted to support this type of nested navigation but the convention was the same, each navigation route level added a new criteria to the select query over the top of the query provided by the parent route's controller.


问:
How to open a Python pickle file, append to it, save it, and close it?
Here is my code:

```<code> import pickle

 class User:
     def __init__(self, username, password):
         self.username = username
         self.password = password

     def set_password(self):
         self.password = input("Enter NEW password > ")

     def __get_password(self):
         return self.password

     def __get_username(self):
         return self.username

     def change_password(self):
         my_password = input("Enter your CURRENT password > ")
         if my_password == User.__get_password(self):
             self.set_password()
         else:
             print("Please try again")

     def display_details(self):
         print()
         print("Username and password")
         print("---------------------")
         print("username is: ", User.__get_username(self))
         print("password is: ", User.__get_password(self))
         print()

     def __repr__(self):
         return f'username: {self.username}'

 users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]

 try:
     foo = pickle.load(open("users.pickle", "rb"))
 except (OSError, IOError) as f:
     foo = 3
     pickle.dump(foo, open("users.pickle", "wb"))

 # with open('users.pickle', 'wb') as f:
 #     pickle.dump(users, f)

 def find_user(name):
     for user in users:
         if user.username == name:
             return user

 def add_user():
     user = input("Enter NEW user > ")
     password = input(f"Enter password for {user} > ")
     users.append(User(user, password))

 def delete_user():
     delete_user = input("Enter the user you wish to remove > ")
     user = find_user(delete_user)
     if user:
         users.remove(user)
         print('done')
     else:
         print(f'user {delete_user} not found')

 def change_password():
     my_password = input("Enter your CURRENT password > ")
     change_password()

 def display_users():
     for user in users:
         print(user)

 def invalid_entry():  # Response for invalid entries to menu.
     print("Invalid entry, please try again")
     print()

 def menu():  # Display menu, prompt for and accept keyboard choice
     print("Please select one of the following:")
     print()
     print("Enter a if you want to add a new user")
     print("Enter d if you want to delete a user")
     print("Enter f if you want to find a user")
     print("Enter c if you want to change your password")
     print("Enter u if you want to display a list of users")
     print("Enter q if you want to Quit")
     choice = input("")
     return choice

 while True:
     menu_choice = menu()
     if menu_choice.lower() == "a":
         add_user()
     elif menu_choice.lower() == "d":
         delete_user()
     elif menu_choice.lower() == "f":
         find_user()
     elif menu_choice.lower() == "c":
         change_password()
     elif menu_choice.lower() == 'u':
         display_users()
     elif menu_choice.lower() == "q":
         print("Goodbye")
         with open('users.pickle', 'wb') as f:
             pickle.dump(users, f)
             quit()
     else:
         invalid_entry()
</code>```

It's not working properly though, as the pickle file is being overwritten every time the program runs. I'm guessing the culprit is the users line, but I don't know how to resolve the problem, if that's the case. I tried moving the entire line to the bottom of the try section, aligned with the pickle.dump line, but that just threw an error:

NameError: name 'users' is not defined

Can someone help me please? I've been trying to do this for about 2 weeks now and I'm getting increasingly frustrated. I've looked at so many related tutorials on the web that many of the links I'm seeing are now purple, but I just can't seem to work out how to write the code to create the correct logical flow.

I think the logic should probably be:

1) Does file exist?

If Y - do nothing

If N - create it with sample data

2) Does the user want to create a new login?

If Y - append the login to the file

If N - do nothing

答:
The issue I found is that you arent actually using the loaded pickle data in these lines:

```<code>users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]

 try:
     foo = pickle.load(open("users.pickle", "rb"))
 except (OSError, IOError) as f:
     foo = 3
     pickle.dump(foo, open("users.pickle", "wb"))
</code>```

You load the file into foo but never use it and your exception doesn't make much sense, try changing that block into the following:

```<code> try:
     users = pickle.load(open("users.pickle", "rb"))
 except (OSError, IOError) as f:
     users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]
     pickle.dump(foo, open("users.pickle", "wb"))
</code>```

Now you will try to load the pre-made file, and on failure generate a default

Body:
Here is my code:

 import pickle

 class User:
     def __init__(self, username, password):
         self.username = username
         self.password = password

     def set_password(self):
         self.password = input("Enter NEW password > ")

     def __get_password(self):
         return self.password

     def __get_username(self):
         return self.username

     def change_password(self):
         my_password = input("Enter your CURRENT password > ")
         if my_password == User.__get_password(self):
             self.set_password()
         else:
             print("Please try again")

     def display_details(self):
         print()
         print("Username and password")
         print("---------------------")
         print("username is: ", User.__get_username(self))
         print("password is: ", User.__get_password(self))
         print()

     def __repr__(self):
         return f'username: {self.username}'

 users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]

 try:
     foo = pickle.load(open("users.pickle", "rb"))
 except (OSError, IOError) as f:
     foo = 3
     pickle.dump(foo, open("users.pickle", "wb"))

 # with open('users.pickle', 'wb') as f:
 #     pickle.dump(users, f)

 def find_user(name):
     for user in users:
         if user.username == name:
             return user

 def add_user():
     user = input("Enter NEW user > ")
     password = input(f"Enter password for {user} > ")
     users.append(User(user, password))

 def delete_user():
     delete_user = input("Enter the user you wish to remove > ")
     user = find_user(delete_user)
     if user:
         users.remove(user)
         print('done')
     else:
         print(f'user {delete_user} not found')

 def change_password():
     my_password = input("Enter your CURRENT password > ")
     change_password()

 def display_users():
     for user in users:
         print(user)

 def invalid_entry():  # Response for invalid entries to menu.
     print("Invalid entry, please try again")
     print()

 def menu():  # Display menu, prompt for and accept keyboard choice
     print("Please select one of the following:")
     print()
     print("Enter a if you want to add a new user")
     print("Enter d if you want to delete a user")
     print("Enter f if you want to find a user")
     print("Enter c if you want to change your password")
     print("Enter u if you want to display a list of users")
     print("Enter q if you want to Quit")
     choice = input("")
     return choice

 while True:
     menu_choice = menu()
     if menu_choice.lower() == "a":
         add_user()
     elif menu_choice.lower() == "d":
         delete_user()
     elif menu_choice.lower() == "f":
         find_user()
     elif menu_choice.lower() == "c":
         change_password()
     elif menu_choice.lower() == 'u':
         display_users()
     elif menu_choice.lower() == "q":
         print("Goodbye")
         with open('users.pickle', 'wb') as f:
             pickle.dump(users, f)
             quit()
     else:
         invalid_entry()

It's not working properly though, as the pickle file is being overwritten every time the program runs. I'm guessing the culprit is the users line, but I don't know how to resolve the problem, if that's the case. I tried moving the entire line to the bottom of the try section, aligned with the pickle.dump line, but that just threw an error:

NameError: name 'users' is not defined

Can someone help me please? I've been trying to do this for about 2 weeks now and I'm getting increasingly frustrated. I've looked at so many related tutorials on the web that many of the links I'm seeing are now purple, but I just can't seem to work out how to write the code to create the correct logical flow.

I think the logic should probably be:

1) Does file exist?

If Y - do nothing

If N - create it with sample data

2) Does the user want to create a new login?

If Y - append the login to the file

If N - do nothing

Body:
The issue I found is that you arent actually using the loaded pickle data in these lines:

users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]

 try:
     foo = pickle.load(open("users.pickle", "rb"))
 except (OSError, IOError) as f:
     foo = 3
     pickle.dump(foo, open("users.pickle", "wb"))

You load the file into foo but never use it and your exception doesn't make much sense, try changing that block into the following:

 try:
     users = pickle.load(open("users.pickle", "rb"))
 except (OSError, IOError) as f:
     users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]
     pickle.dump(foo, open("users.pickle", "wb"))

Now you will try to load the pre-made file, and on failure generate a default


问:
Recommended MySQL INDEX for storing domain names
I'm trying to store about 100 Million domain names in a MySQL database, but I can't figure out the right INDEX method to use on the domain names.

The issue being that LIKE queries will also be executed:

```<code>SELECT id FROM domains WHERE domain LIKE '%.example.com'
</code>```

or

```<code>SELECT id FROM domains WHERE domain LIKE 'example.%'
</code>```

If it makes it easier, '%example%' is not a requirement, but at best a nice to have / be able to.

What would be the proper index to use? Left to right (example.%) should be realitivly straight forward, but right to left (%.example.com) is problematic but the most common query.

I'm using MariaDB 10.3 on Linux. DB running on a PCI-e SSD, lookup times longer then 10 seconds should be coincided "unacceptable"

答:
I'm not sure an index would help you here. If you can't change the database, your options seem limited. One thing you could do, is if you're running both a subdomain and domain query back to back, to run the subdomain query first. That should help reduce the number of rows the domain query has to cover.

It would definitely help if you split the URL between subdomains and domains into different columsn in the database. Have indexes for both of them. Then you could query the subdomains only and the domains only. It should speed things up. And if there are a lot of repeating values, you should normalize those fields so to remove repetition and speed up queries even more.

Body:
I'm trying to store about 100 Million domain names in a MySQL database, but I can't figure out the right INDEX method to use on the domain names.

The issue being that LIKE queries will also be executed:

SELECT id FROM domains WHERE domain LIKE '%.example.com'

or

SELECT id FROM domains WHERE domain LIKE 'example.%'

If it makes it easier, '%example%' is not a requirement, but at best a nice to have / be able to.

What would be the proper index to use? Left to right (example.%) should be realitivly straight forward, but right to left (%.example.com) is problematic but the most common query.

I'm using MariaDB 10.3 on Linux. DB running on a PCI-e SSD, lookup times longer then 10 seconds should be coincided "unacceptable"


问:
codeigniter table join
I want to display both the user table and users_profiles table in 1 table :
I want to link them both so that usrpID = usrID,

Before this process I tried displaying only users table using this code and it works great.

Controller:

```<code>$data['query'] = $this->db->query('SELECT * FROM users_profiles');
$this->load->view('users/users_view',$data);
</code>```

View:

```<code><?php foreach($query->result_array() as $row): ?>
        <tr class="even gradeC">
            <td><?php echo $row['usrID']</td>
            <td><?php echo $row['usrName'];?></td>
        </tr>
<? endforeach; ?>
</code>```

but when I try to join two tables, it returns me an error: this is my code

```<code>$this->db->select('users.usrID, users_profiles.usrpID');
$this->db->from('users', 'users_profiles');
$this->db->join('users', 'users.usrID = users_profiles.usrpID');
$result = $this->db->get();
</code>```

users table has fields like username,password, etc. and every user has his own profile in users_profiles table

```users           users_profiles```

EDIT I tried selecting the fields but when I tried this

```<code><td><?php echo $row['usrID'];?></td>
            <td><?php echo $row['usrName'];?></td>
            <td><?php echo $row['usrpFirstName'].' '.$row['usrpLastName'];?></td>
            <td><?php echo $row['usrpBday'];?></td>
            <td><?php echo $row['usrpSex'];?></td>
            <td><?php echo $row['usrpAddress'];?></td>
</code>```

it returns me the first value in users profiles in which it should not

答:
users table was in both from and join functions, so in sum you were joining 3 tables: users, users and users_profiles -> the 2 first have the same name -> error unique/alias table.

Try this (joining [users in from] on [users_profiles in join]):

```<code>$this->db->select('users.usrID, users_profiles.usrpID')
         ->from('users')
         ->join('users_profiles', 'users.usrID = users_profiles.usrpID');
$result = $this->db->get();
</code>```

EDIT:

example:

To get users_profiles userpNick column:

```<code>$this->db->select('users.usrID, users_profiles.userpNick')
         ->from('users')
         ->join('users_profiles', 'users.usrID = users_profiles.usrpID');
$query = $this->db->get();
</code>```

view:

```<code><?php foreach($query->result() as $row): ?>
        <tr class="even gradeC">
            <td><?php echo $row->usrID</td>
            <td><?php echo $row->userpNick;?></td>
        </tr>
<? endforeach; ?>
</code>```

Title: codeigniter table join

Body:
I want to display both the user table and users_profiles table in 1 table :
I want to link them both so that usrpID = usrID,

Before this process I tried displaying only users table using this code and it works great.

Controller:

$data['query'] = $this->db->query('SELECT * FROM users_profiles');
$this->load->view('users/users_view',$data);

View:

<?php foreach($query->result_array() as $row): ?>

            <?php echo $row['usrID']
            <?php echo $row['usrName'];?>

<? endforeach; ?>

but when I try to join two tables, it returns me an error: this is my code

$this->db->select('users.usrID, users_profiles.usrpID');
$this->db->from('users', 'users_profiles');
$this->db->join('users', 'users.usrID = users_profiles.usrpID');
$result = $this->db->get();

users table has fields like username,password, etc. and every user has his own profile in users_profiles table

users           users_profiles

EDIT I tried selecting the fields but when I tried this

<?php echo $row['usrID'];?>
            <?php echo $row['usrName'];?>
            <?php echo $row['usrpFirstName'].' '.$row['usrpLastName'];?>
            <?php echo $row['usrpBday'];?>
            <?php echo $row['usrpSex'];?>
            <?php echo $row['usrpAddress'];?>

it returns me the first value in users profiles in which it should not

Body:
users table was in both from and join functions, so in sum you were joining 3 tables: users, users and users_profiles -> the 2 first have the same name -> error unique/alias table.

Try this (joining [users in from] on [users_profiles in join]):

$this->db->select('users.usrID, users_profiles.usrpID')
         ->from('users')
         ->join('users_profiles', 'users.usrID = users_profiles.usrpID');
$result = $this->db->get();

EDIT:

example:

To get users_profiles userpNick column:

$this->db->select('users.usrID, users_profiles.userpNick')
         ->from('users')
         ->join('users_profiles', 'users.usrID = users_profiles.usrpID');
$query = $this->db->get();

view:

<?php foreach($query->result() as $row): ?>
        <tr class="even gradeC">
            <td><?php echo $row->usrID</td>
            <td><?php echo $row->userpNick;?></td>
        </tr>
<? endforeach; ?>


问:
git plugin for Jenkins fails to clone a repo from local machine. Error code 128
Error:

```<code>Failed to connect to repository : Command "/usr/bin/git ls-remote -h file:///home/myuser/path/to/project HEAD" returned status code 128:
stdout:
stderr: fatal: 'home/myuser/path/to/project' does not appear to be a git repository
fatal: The remote end hung up unexpectedly
</code>```

I have tried the following:

chmod 777 to the repo folder(folder containing .git directory)

chowned to jenkins:jenkins on the repo folder

tried to clone into another folder from this local repo folder: this works!

When I run the above command: /usr/bin/git ls-remote -h file:///home/myuser/path/to/project HEAD on cmd I get the branches.

My questions are:

why is git ls-remote -h ... command called when it should be git clone ...?

How to configure jenkins git plugin to fetch code from local repo

My environment:

RHEL 5.9

Jenkins 1.519 installed as a service(no Web container)

Git plugin

答:
Instead of file:/// you can also use ssh:// as in this answer:

```<code>ssh://YOUR_USER@localhost/PATH_TO_YOUR_PROJECT
</code>```

Note that you need to do the standard ssh setup:

Generate a keypair using ssh-keygen if you don't already have one in ~/.ssh

Paste private key (default ~/.ssh/id_rsa) into Jenkins (project settings, git repo, credentials)

Paste public key into ~/.ssh/authorized_keys

Body:
Error:

Failed to connect to repository : Command "/usr/bin/git ls-remote -h file:///home/myuser/path/to/project HEAD" returned status code 128:
stdout:
stderr: fatal: 'home/myuser/path/to/project' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

I have tried the following:

chmod 777 to the repo folder(folder containing .git directory)

chowned to jenkins:jenkins on the repo folder

tried to clone into another folder from this local repo folder: this works!

When I run the above command: /usr/bin/git ls-remote -h file:///home/myuser/path/to/project HEAD on cmd I get the branches.

My questions are:

why is git ls-remote -h ... command called when it should be git clone ...?

How to configure jenkins git plugin to fetch code from local repo

My environment:

RHEL 5.9

Jenkins 1.519 installed as a service(no Web container)

Git plugin

Body:
Instead of file:/// you can also use ssh:// as in this answer:

ssh://YOUR_USER@localhost/PATH_TO_YOUR_PROJECT

Note that you need to do the standard ssh setup:

Generate a keypair using ssh-keygen if you don't already have one in ~/.ssh

Paste private key (default ~/.ssh/id_rsa) into Jenkins (project settings, git repo, credentials)

Paste public key into ~/.ssh/authorized_keys