text:
Q: Weighted random sampling in Elasticsearch I need to obtain a random sample from an ElasticSearch index, i.e. to issue a query that retrieves some documents from a given index with weighted probability Wj/ΣWi (where Wj is a weight of row j and Wj/ΣWi is a sum of weights of all documents in this query).
Currently, I have the following query:
GET products/_search?pretty=true

{"size":5,
  "query": {
    "function_score": {
      "query": {
        "bool":{
          "must": {
            "term":
              {"category_id": "5df3ab90-6e93-0133-7197-04383561729e"}
          }
        }
      },
      "functions":
        [{"random_score":{}}]
    }
  },
  "sort": [{"_score":{"order":"desc"}}]
}

It returns 5 items from selected category, randomly.
Each item has a field weight. So, I probably have to use
"script_score": {
  "script": "weight = data['weight'].value / SUM; if (_score.doubleValue() > weight) {return 1;} else {return 0;}"
}

as described here.
I have the following issues:

*

*What is the correct way to do this?

*Do I need to enable Dynamic
Scripting?

*How to calculate the total sum of the query?

Thanks a lot for your help!

A: In case it helps anyone, here is how I recently implemented a weighted shuffling.
On this example, we shuffle companies. Each company has a "company_score" between 0 and 100. With this simple weighted shuffling, a company with score 100 is 5 times more likely to appear in first page than a company with score 20.
json_body = {
    "sort": ["_score"],
    "query": {
        "function_score": {
            "query": main_query,  # put your main query here
            "functions": [
                {
                    "random_score": {},
                },
                {
                    "field_value_factor": {
                        "field": "company_score",
                        "modifier": "none",
                        "missing": 0,
                    }
                }
            ],
            # How to combine the result of the two functions 'random_score' and 'field_value_factor'.
            # This way, on average the combined _score of a company having score 100 will be 5 times as much
            # as the combined _score of a company having score 20, and thus will be 5 times more likely
            # to appear on first page.
            "score_mode": "multiply",
            # How to combine the result of function_score with the original _score from the query.
            # We overwrite it as our combined _score (random x company_score) is all we need.
            "boost_mode": "replace",
        }
    }
}

A: In addition to other answers:
You may also consider a case with a non-uniform distribution of the source documents by the features to balance on. For example, you want to retrieve 100 randomly mixed news: 50% on sports and 50% on politics from the index with 10,000 news on sports and 1,000,000 news on politics.
In this case, you may use a custom script_score function to mix with random_score to transform the source distribution to wanted 50/50 distribution in the results:
GET objects/_search
{
  "size": 100,
  "sort": [
    "_score"
  ],
  "query": {
    "function_score": {
      "query": { "match_all": {} },
      "functions": [
        {
          "random_score": {}
        },
        {
          "script_score": {
            "script": {
              "source": """
                double boost = 0.0;
                if (params._source['labels'] != null && params._source['labels']['genres'] != null && params._source['labels']['genres'].contains('politics') && Math.random()*1000000 <= 50) {
                  boost += 1.0;
                }
                if (params._source['labels'] != null && params._source['labels']['genres'] != null && params._source['labels']['genres'].contains('sports') && Math.random()*10000 <= 50) {
                  boost += 1.0;
                }
                return boost;
              """
            }
          }
        }
      ],
      "score_mode": "multiply",
      "boost_mode": "replace"
    }
  }
}

Note, that source documents in the above example are nested like below:
{
  "title": "...",
  "body": "...",
  "labels": {
    "genres": ["news"],
    "topics": ["sports", "celebrities"]
  }
}

but you might have a simpler data model with plain fields; in this case just use doc['topic'].contains('sports') instead of params._source[].

A: I know this question is old, but answering for any future searchers.
The comment before yours in the GitHub thread seems to have the answer. If each of your documents has a relative weight, then you can pick a random score for each document and multiply it by the weight to create your new weighted random score. This has the added bonus of not needing the sum of weights.
e.g. if two documents have weights 1 and 2, then you'd expect the second to have twice the likelihood of selection as the first. Give each document a random score between 0 and 1 (which you're already doing with "random_score"). Multiply the random score by the weight and you'll have the first document with a score between 0 and 1 and the second with a score between 0 and 2, so twice as likely to be selected!


text:
Q: Loading icon on state change with resolve I'm want to display a loading icon in my view, but I doesn't seem to work..
My view renders when my $resource in the resolve is loaded.
.run(['$rootScope', '$state', '$stateParams', function () {
    $rootScope.$on('$stateChangeStart', function () {
        console.log('start');
        $rootScope.spinner = true;
    });
    $rootScope.$on('$stateChangeSuccess', function () {
        console.log('end');
        $rootScope.spinner = false;
    });
}])

Can't set the spinner because my view isn't loaded yet..
How am I supposed to ng-show on my spinner div then..?

A: You can put the spinner to be outside of any view. That way you don't need to include it in any template but you'll still be able to control it with ng-show and watching state changes like you did.

A: I've solved it by putting my loading div outside of the ui-view.
Because it is outside the controller of the ui-view, I can just use the $rootScope.loading here.

Loading, please wait...

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get child Count in Header in expandable list view Kotlin enter image description here
How get the child count same as shown in the picture in the header.
API RESPONSE: -
data class ToDoListResponse(
val message: String = "",
val success: Int = 0,
val todays_task_list: MutableList<TodaysTask>,
val todays_task_total: Int = 0,
val tomorows_task_list: MutableList<TodaysTask>,
val tomorrow_task_total: Int = 0,
val upcomming_task_list: MutableList<TodaysTask>,
val upcomming_task_total: Int = 0)
{
data class TodaysTask(
val created_at: String = "",
val description: String = "",
val due_date: String= "",
val is_completed: String= "",
val is_pinned_task: String= "",
val remind_me: String= "",
val task_id: String= "",
var title: String= "",
val updated_at: String= "",
val user_id: String= ""
)

ADPATER: -
package com.coronation.jackpotplus.adapter

import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.content.Context
import android.graphics.Typeface
import android.os.Build
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.annotation.RequiresApi
import com.coronation.jackpotplus.R
import com.coronation.jackpotplus.model.CommonResponse
import com.coronation.jackpotplus.model.ToDoListResponse
import com.coronation.jackpotplus.network.ApiClient
import com.coronation.jackpotplus.network.ApiService
import com.coronation.jackpotplus.view.ToDoListActivity
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.textfield.TextInputEditText
import org.jetbrains.anko.layoutInflater
import retrofit2.Call
import retrofit2.Response
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.*

@Suppress("NAME_SHADOWING", "DEPRECATED_IDENTITY_EQUALS")
class CustomExpandableListAdapter(
        context: Context,
        expandableListTitle: ArrayList<String>,
        expandableListDetail: HashMap<String,
                MutableList<ToDoListResponse.TodaysTask>>)
    : BaseExpandableListAdapter()
{
    private val context: Context
    private val expandableListTitle: ArrayList<String>
    private val expandableListDetail: HashMap<String, MutableList<ToDoListResponse.TodaysTask>>
    private lateinit var edtTitle: TextInputEditText
    private lateinit var edtDes: TextInputEditText
    private lateinit var dueDate: TextView
    private lateinit var txtreminddate: TextView
    private lateinit var createAt: String
    private lateinit var taskId: String
    private var ChildCount: String? = null
    private lateinit var dialog: BottomSheetDialog

    override fun getChild(listPosition: Int, expandedListPosition: Int): Any
    {
        return expandableListDetail[expandableListTitle[listPosition]]?.get(expandedListPosition)!!
    }

    override fun getChildId(listPosition: Int, expandedListPosition: Int): Long
    {
        return expandedListPosition.toLong()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    @SuppressLint("InflateParams", "SimpleDateFormat")
    override fun getChildView(listPosition: Int, expandedListPosition: Int, isLastChild: Boolean, convertView: View?, parent: ViewGroup?): View
    {
        var convertView = convertView
        if (convertView == null)
        {
            val layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            convertView = layoutInflater.inflate(R.layout.list_item, null)
        }
        val expandedListTextView = convertView?.findViewById(R.id.expandedListItem) as TextView
        val expandedItem = convertView.findViewById(R.id.expandedItem) as LinearLayout
        val txtDelete = convertView.findViewById(R.id.delete) as FrameLayout
        val unpin = convertView.findViewById(R.id.unpin) as FrameLayout
        val pin = convertView.findViewById(R.id.pin) as FrameLayout
        val complete = convertView.findViewById(R.id.complete) as FrameLayout
        val mainPin = convertView.findViewById(R.id.mainPin) as ImageView

        val getset = getChild(listPosition, expandedListPosition) as ToDoListResponse.TodaysTask
        expandedListTextView.text = getset.title
        createAt = getset.created_at
        unpin.visibility = View.GONE
        if (getset.is_pinned_task == "1")
        {
            mainPin.visibility = View.VISIBLE
            unpin.visibility = View.VISIBLE
            pin.visibility = View.GONE
        }
        else
        {
            mainPin.visibility = View.GONE
            pin.visibility = View.VISIBLE
        }

        unpin.setOnClickListener {
            pinnedtask(getset.task_id)
        }

        pin.setOnClickListener {
            pinnedtask(getset.task_id)
        }

        complete.setOnClickListener {
            markascomplete(getset.task_id)
        }

        txtDelete.setOnClickListener {
            deleteTask(getset.task_id)
        }

        expandedItem.setOnClickListener {
            openTaskDetails()
            taskId = getset.task_id
            edtTitle.setText(getset.title)
            edtDes.setText(getset.description)
            dueDate.visibility = View.VISIBLE
            txtreminddate.visibility = View.VISIBLE
            val dueDate1 = getset.due_date
            val sdf = SimpleDateFormat("yyyy-MM-dd")
            val date = Date(dueDate1.toLong() * 1000)
            dueDate.text = sdf.format(date)
            val remindDate = getset.remind_me
            val sdf1 = SimpleDateFormat("yyyy-MM-dd")
            val date1 = Date(remindDate.toLong() * 1000)
            txtreminddate.text = sdf1.format(date1)
        }
        return convertView
    }

    private fun pinnedtask(taskId: String)
    {
        val retIn = ApiClient.client!!.create(ApiService::class.java)
        retIn.pintask(taskId).enqueue(object : retrofit2.Callback<CommonResponse> {
            override fun onResponse(call: Call<CommonResponse>, response: Response<CommonResponse>) {
                showToast(response.body()?.message)
                notifyDataSetChanged()
                if (context is ToDoListActivity) {
                    context.tasklistAPI("1")
                }
            }

            override fun onFailure(call: Call<CommonResponse>, t: Throwable) {
                showToast("Shomwthing wents wrong")
            }
        })
    }

    private fun markascomplete(taskId: String)
    {
        val retIn = ApiClient.client!!.create(ApiService::class.java)
        retIn.markcomplete(taskId).enqueue(object : retrofit2.Callback<CommonResponse> {
            override fun onResponse(call: Call<CommonResponse>, response: Response<CommonResponse>) {
                showToast(response.body()?.message)
                notifyDataSetChanged()
                if (context is ToDoListActivity) {
                    context.tasklistAPI("1")
                }
            }

            override fun onFailure(call: Call<CommonResponse>, t: Throwable) {
                showToast("Shomwthing wents wrong")
            }
        })
    }

    private fun deleteTask(taskId: String)
    {
        val retIn = ApiClient.client!!.create(ApiService::class.java)
        retIn.deteletask(taskId).enqueue(object : retrofit2.Callback<CommonResponse> {
            override fun onResponse(call: Call<CommonResponse>, response: Response<CommonResponse>) {
                showToast(response.body()?.message)
                notifyDataSetChanged()
                if (context is ToDoListActivity) {
                    context.tasklistAPI("1")
                }
            }

            override fun onFailure(call: Call<CommonResponse>, t: Throwable) {
                showToast("Shomwthing wents wrong")
            }

        })
    }

    @RequiresApi(Build.VERSION_CODES.O)
    @SuppressLint("InflateParams")
    private fun openTaskDetails()
    {
        try
        {
            val modalbottomsheet = context.layoutInflater.inflate(R.layout.custom_view_todo, null)
            dialog = BottomSheetDialog(context, R.style.DialogStyle)
            dialog.setContentView(modalbottomsheet)
            edtTitle = dialog.findViewById(R.id.edtTitle)!!
            edtDes = dialog.findViewById(R.id.edtDes)!!
            dueDate = dialog.findViewById(R.id.dueDate)!!
            txtreminddate = dialog.findViewById(R.id.txtreminddate)!!
            val imgDatePicker = dialog.findViewById<ImageView>(R.id.imgDatePicker)
            val imgDatePickerReminder = dialog.findViewById<ImageView>(R.id.imgDatePickerReminder)
            val button = dialog.findViewById<Button>(R.id.Button)

            imgDatePicker?.setOnClickListener {
                showDatePicker(context)
            }
            imgDatePickerReminder?.setOnClickListener {
                showDatePickerForRemind(context)
            }
            button?.setOnClickListener {
                updateTaskAPI()
            }
            dialog.show()
        }
        catch (e: Exception)
        {
            e.printStackTrace()
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun updateTaskAPI()
    {
        val l = LocalDate.parse(dueDate.text, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
        val dueDateTimestamp = l.atStartOfDay(ZoneId.systemDefault()).toInstant().epochSecond
        Toast.makeText(context, dueDateTimestamp.toString(), Toast.LENGTH_SHORT).show()

        val l1 = LocalDate.parse(txtreminddate.text, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
        val remindMeTimestamp = l1.atStartOfDay(ZoneId.systemDefault()).toInstant().epochSecond
        Toast.makeText(context, remindMeTimestamp.toString(), Toast.LENGTH_SHORT).show()

        val retIn = ApiClient.client!!.create(ApiService::class.java)
        retIn.taskupdate(
                createAt,
                edtDes.text?.trim().toString(),
                dueDateTimestamp.toString(),
                remindMeTimestamp.toString(),
                taskId, edtTitle.text?.trim().toString(),
                "1").enqueue(object : retrofit2.Callback<CommonResponse>
        {
            override fun onResponse(call: Call<CommonResponse>, response: Response<CommonResponse>)
            {
                if (response.body()!!.success == 1)
                {
                    dialog.dismiss()
                    showToast(response.body()?.message)
                }
            }

            override fun onFailure(call: Call<CommonResponse>, t: Throwable)
            {
                showToast("Something not right, Please try again.")
            }
        }
        )
    }

    @SuppressLint("InflateParams")
    fun showToast(msg: String?)
    {
        try
        {
            val inflater = context.layoutInflater
            val layout = inflater.inflate(R.layout.custom_toast, null)
            val text = layout.findViewById<View>(R.id.text) as TextView
            text.text = msg
            val toast = Toast(context)
            toast.duration = Toast.LENGTH_SHORT
            toast.view = layout
            if (toast.view.isShown)
            {
                toast.cancel()
            }
            else
            {
                toast.show()
            }
        }
        catch (e: Exception)
        {
            e.printStackTrace()
        }
    }

    private fun showDatePickerForRemind(context: Context)
    {
        val cal = Calendar.getInstance()
        val dateSetListener =
                DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
                    cal.set(Calendar.YEAR, year)
                    cal.set(Calendar.MONTH, monthOfYear)
                    cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                    val myFormat = "yyyy-MM-dd" // mention the format you need
                    val sdf = SimpleDateFormat(myFormat, Locale.US)
                    txtreminddate.visibility = View.VISIBLE
                    txtreminddate.text = sdf.format(cal.time)
                }

        var datepicker: DatePickerDialog? = null
        if (txtreminddate.text.isNotBlank())
        {
            try
            {
                val date: String = txtreminddate.text.trim().toString()
                val datearr = date.split("-").toTypedArray()
                val yearint = datearr[2].toInt()
                val monthint = datearr[1].toInt()
                val dateint = datearr[0].toInt()
                datepicker = DatePickerDialog(
                        context,
                        dateSetListener,
                        dateint,
                        monthint - 1,
                        yearint
                )
            }
            catch (e: Exception)
            {
                e.printStackTrace()
            }
        }
        else
        {
            try
            {
                val calendar = Calendar.getInstance()
                val dd = calendar[Calendar.DAY_OF_MONTH]
                val mm = calendar[Calendar.MONTH]
                val yy = calendar[Calendar.YEAR]
                datepicker = DatePickerDialog(context, dateSetListener, dd, mm, yy)
            }
            catch (e: Exception)
            {
                e.printStackTrace()
            }
        }
        datepicker!!.show()
    }

    private fun showDatePicker(context: Context)
    {
        val cal = Calendar.getInstance()
        val dateSetListener =
                DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
                    cal.set(Calendar.YEAR, year)
                    cal.set(Calendar.MONTH, monthOfYear)
                    cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                    val myFormat = "yyyy-MM-dd" // mention the format you need
                    val sdf = SimpleDateFormat(myFormat, Locale.US)
                    dueDate.visibility = View.VISIBLE
                    dueDate.text = sdf.format(cal.time)
                }

        var datepicker: DatePickerDialog? = null
        if (dueDate.text.isNotBlank())
        {
            try
            {
                val date: String = dueDate.text.toString()
                val datearr = date.split("-").toTypedArray()
                val dateint = datearr[0].toInt()
                val monthint = datearr[1].toInt()
                val yearint = datearr[2].toInt()
                datepicker = DatePickerDialog(
                        context,
                        dateSetListener,
                        yearint,
                        monthint - 1,
                        dateint
                )
            }
            catch (e: java.lang.Exception)
            {
                e.printStackTrace()
            }
        }
        else
        {
            try
            {
                val calendar = Calendar.getInstance()
                val yy = calendar[Calendar.YEAR]
                val mm = calendar[Calendar.MONTH]
                val dd = calendar[Calendar.DAY_OF_MONTH]
                datepicker = DatePickerDialog(context, dateSetListener, yy, mm, dd)
            }
            catch (e: java.lang.Exception)
            {
                e.printStackTrace()
            }
        }
        datepicker!!.show()
    }

    override fun getChildrenCount(listPosition: Int): Int
    {
        ChildCount = expandableListDetail[expandableListTitle[listPosition]]?.size.toString()
        Log.e("TAG",ChildCount)
        return expandableListDetail[expandableListTitle[listPosition]]?.size!!
    }

    override fun getGroup(listPosition: Int): Any
    {
        return expandableListTitle[listPosition]
    }

    override fun getGroupCount(): Int
    {
        return expandableListTitle.size
    }

    override fun getGroupId(listPosition: Int): Long
    {
        return listPosition.toLong()
    }

    @SuppressLint("InflateParams")
    override fun getGroupView(listPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup?): View
    {
        var convertView: View? = convertView
        val listTitle = getGroup(listPosition) as String

        if (convertView == null)
        {
            val layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            convertView = layoutInflater.inflate(R.layout.list_group, null)
        }
        val listTitleTextView = convertView?.findViewById(R.id.listTitle) as TextView
        val listCount = convertView.findViewById(R.id.listCount) as TextView
        val arrowicon = convertView.findViewById(R.id.arrowicon) as ImageView
        listTitleTextView.setTypeface(null, Typeface.BOLD)
        listTitleTextView.text = listTitle
        listCount.text = "($ChildCount)"

        if (getChildrenCount(listPosition) === 0)
        {
            arrowicon.visibility = View.INVISIBLE
        }
        else
        {
            arrowicon.visibility = View.VISIBLE
            arrowicon.setImageResource(if (isExpanded) R.drawable.ic_arrow_up else R.drawable.ic_arrow_down)
        }
        return convertView
    }

    override fun hasStableIds(): Boolean
    {
        return false
    }

    override fun isChildSelectable(listPosition: Int, expandedListPosition: Int): Boolean
    {
        return true
    }

    init
    {
        this.context = context
        this.expandableListTitle = expandableListTitle
        this.expandableListDetail = expandableListDetail
    }
}

ACTIVITY: -
  fun tasklistAPI(userId: String)
    {
        if (isOnline())
        {
            llNoInternet.gone()
            llLoading.visible()
            apiService.todotasklist(userId).enqueue(object :
                    Callback<ToDoListResponse>
            {
                override fun onFailure(call: Call<ToDoListResponse>, t: Throwable)
                {
                    llLoading.gone()
                }

                override fun onResponse(call: Call<ToDoListResponse>, response: Response<ToDoListResponse>)
                {
                    if (response.isSuccessful)
                    {
                        if (response.body()!!.success == 1)
                        {
                            try
                            {

                                llLoading.gone()
                                expandableListDetail = HashMap()

                                val todaytask = response.body()!!.todays_task_list

                                expandableListTitle = ArrayList()
                                todaystitle = ArrayList()
                                todayslist = ArrayList()
                                Log.e("<>list", todaystitle.toString())

                                for (i in todaytask.indices)
                                {
                                    todaystitle.add(todaytask[i])
                                }

                                val tommrowtask = response.body()!!.tomorows_task_list
                                val tommorowtitle: MutableList<ToDoListResponse.TodaysTask> = ArrayList()

                                for (i in tommrowtask.indices)
                                {
                                    tommorowtitle.add(tommrowtask[i])
                                }

                                val upcomingtask = response.body()!!.upcomming_task_list
                                val upcomingtitle: MutableList<ToDoListResponse.TodaysTask> = ArrayList()

                                for (i in upcomingtask.indices)
                                {
                                    upcomingtitle.add(upcomingtask[i])
                                }

                                expandableListTitle.add("Today's Task")
                                expandableListTitle.add("Tommorow's Task")
                                expandableListTitle.add("Upcoming Task")
                                expandableListDetail.put(expandableListTitle[0], todaystitle)
                                expandableListDetail.put(expandableListTitle[1], tommrowtask)
                                expandableListDetail.put(expandableListTitle[2], upcomingtask)
                                Log.e("task", expandableListTitle.get(0) + " = " + expandableListDetail.put(expandableListTitle.get(0), todaystitle))
                                Log.e("task", expandableListTitle.get(1) + " = " + expandableListDetail.put(expandableListTitle.get(1), tommrowtask))
                                Log.e("task", expandableListTitle.get(2) + " = " + expandableListDetail.put(expandableListTitle.get(2), upcomingtask))
                                expandableListAdapter = CustomExpandableListAdapter(activity, expandableListTitle, expandableListDetail)
                                expandableListView!!.setAdapter(expandableListAdapter)
                            }
                            catch (e: Exception)
                            {
                                e.printStackTrace()
                            }
                        }
                    }
                    else
                    {
                        llLoading.gone()
                    }
                }
            })
        }
        else
        {
            llNoInternet.visible()
        }
    }

Here is the code that show that how can i add add data into hashmap and the expandable list view.
as u see there is an hashmap for expandable list view and and in the adaoter i put the title from api respose but the header for listview parent is static and the data in the child re dynamic so you can see the diffrance

A: You've added a lot of code but I think this is the only one which is important for your question :-
expandableListTitle.add("Today's Task")
expandableListTitle.add("Tommorow's Task")
expandableListTitle.add("Upcoming Task")
expandableListDetail.put(expandableListTitle[0], todaystitle)
expandableListDetail.put(expandableListTitle[1], tommrowtask)
expandableListDetail.put(expandableListTitle[2], upcomingtask)
Log.e("task", expandableListTitle.get(0) + " = " + expandableListDetail.put(expandableListTitle.get(0), todaystitle))
Log.e("task", expandableListTitle.get(1) + " = " + expandableListDetail.put(expandableListTitle.get(1), tommrowtask))
Log.e("task", expandableListTitle.get(2) + " = " + expandableListDetail.put(expandableListTitle.get(2), upcomingtask))
expandableListAdapter = CustomExpandableListAdapter(activity, expandableListTitle, expandableListDetail)

expandableListView!!.setAdapter(expandableListAdapter)

So As much as I have understood from the image you have added in the link what you need is you need to show the number of elements present in the child in your header right.
What you can do is simply add the total number of elements present in your list like this :-
expandableListTitle.add("Today's Task (${todaystitle.count()})") //.count() gives the total number of elements present in list

It will add title as Today's Task (10) \\ here 10 would be the number of elements present in your list. Now you can simply format in any way you want


text:
Q: Torque : estimate walltime value before running job Is there anybody who know if there is a way to estimate walltime value or "hours of calculation" needed to run a job before running It ?
tank you very much
best regards


text:
Q: Loop each jQuery Issue I have this code:
var arrayInstSaude = new Array();
$("input[name='uniSaudePrj']:checked").each(function(){
    arrayInstSaude[$(this).val()]=$(this).val();
});

For some reason it gives me a messed array.
Exemple:

*

*if I check 1 element value eq 1. It gives me the arrayInstSaude length equal 2.

*if I check 2 elements value eq 2. It gives me the arrayInstSaude length equal 3.

*if I check 3 elements value eq 5. It gives me the arrayInstSaude length equal 6.

*if I check 4 elements value eq 6. It gives me the arrayInstSaude length equal 7.

*if I check 5 elements value eq 7. It gives me the arrayInstSaude length equal 8.

If I do that for 5 elements:
for (var i = 1; i <=arrayInstSaude.length; i++) {
     alert(arrayInstSaude[i]);
}

I will have 1,2,undefined,undefined,5,6,7,undefined, while it was expected to have 1,2,5,6,7.
Someone know what is going on?
Thanks!

A: Arrays are always contiguous.
The length is simply the highest index plus one.
It sounds like you want a regular object that happens to have numeric keys (and no length).

A: Replace
for (var i = 1; i <=arrayInstSaude.length; i++) {
     alert(arrayInstSaude[i]);
}

with
for (var i in arrayInstSaude) {
     alert(arrayInstSaude[i]);
}

Consider reading this discussion by olliej.

A: I think this code is enough for my propouse:
var arrayInstSaude = new Array();
var k=0;
$("input[name='uniSaudePrj']:checked").each(function(){
    arrayInstSaude[k]=$(this).val();
    k++;
});

It was important to observe that the length is the highest index plus one. So, to retrieve the elements we could use
for(k=0;k<arrayInstSaude.length;k++){
    alert(arrayInstSaude[k]);
}

Because we know that the last element is allways empty.


text:
Q: What switches can run a installation program with no human interaction? I am in the process of automating the installation of different programs on a Windows system. I am having a hard time getting programs that end in .EXE to run on their own but I am able to have scripts that end in .MSI run with the appropriate switches.

*

*I am not in a position to download additional software to accomplish this goal.

*In the command Prompt I would enter: "\temp\Notepad++\Current Installer\npp current installer.exe" /(? or h or help) to see what switches were available.

I expect the program to install and that the batch script that contains this process, proceeds to close on its own. Instead the process requires user input and is a manual process rather than automatic.

A: So, this is my code for automation installation, .exe installation doesn't have an silence mode, even if the program show you the command, i try for hours install an skype.exe, with the command /SILENCE, and never works, but with the msiexec command, and the .msi works, nothing apears, install by own and close when finish. Somethings are in my language.  msiexec /i Skype.msi /q --> /q set the silence mode.
title Pacote de Instalacao

cls
@echo off
@echo **************************************************************
@echo ********                                              ********
@echo ********                 Pacote Padrao                ********
@echo ********                                              ********
@echo **************************************************************
pause

:menu
@echo off
@echo Usuario:%username%
@echo Dominio:%userdomain%
@echo Data:%date%
echo **************************************************************
echo ** 1 - Instalar o Skype                                     **
echo ** 2 - Instalar o Adobe Reader                              **
echo ** 3 - Instalar o Firefox                                   **
echo ** 4 - Instalar o Chrome                                    **
echo ** 5 - Instalar o Office16                                  **
echo ** 6 - Instalar o Office16                                  **
echo ** 7 - Pacote Completo                                      **
echo ** 8 - Pacote Sem Firefox                                   **
echo ** 9 - Sair                                                 **
echo **************************************************************

choice /c 1234567890 /m "O que deseja instalar?"

IF errorlevel==9 goto Sair
IF errorlevel==8 goto Completo2
IF errorlevel==7 goto Completo1
IF errorlevel==6 goto Office16
IF errorlevel==5 goto Office10
IF errorlevel==4 goto Chrome
IF errorlevel==3 goto Firefox
IF errorlevel==2 goto Adobe
IF errorlevel==1 goto Skype

:Skype
msiexec /i Skype.msi /q
Cls
goto menu

:AcroRead
msiexec /i AcroRead.msi /q
Cls
goto menu

:Firefox
msiexec /i Firefox.msi /q
Cls
goto menu

:Chrome
msiexec /i Chrome.msi /q
Cls
goto menu

:Completo1
msiexec /i Skype.msi /q
msiexec /i AcroRead.msi /q
msiexec /i Firefox.msi /q
msiexec /i Chrome.msi /q
msiexec /i Trend.msi /q

pause
set /p a=Deseja instalar o Office?(S\N).
IF %a% GEQ "S" (goto S1)
IF %a% GEQ "N" (exit)

:Completo2
msiexec /i Skype.msi /q
msiexec /i AcroRead.msi /q
msiexec /i Chrome.msi /q

pause
set /p a=Deseja instalar o Office?(S\N).
IF %a% GEQ "S" (goto S1)
IF %a% GEQ "N" (exit)

:S1
echo ** 1 - Instalar o Office16
echo ** 2 - Instalar o Office10

choice /c 12 /m "Deseja instalar qual office?"

IF errorlevel==2 goto Office10
IF errorlevel==1 goto Office16

:Office10
start E:\Pasta\Office10\setup.exe
Cls

:Office16
start E:\Pasta\Office16\setup.exe
Cls

:Sair
Exit

pause
@echo Fim do Script


text:
Q: Position header div in the centre of the screen at the top Could anyone tell me how i would get this div to be centred at the top of the screen, with equal distances from the bounds of the page on both the left and the right.
position:relative;
width:800px;
height:70px;
background-color:#0CF;
left: 15%;

Thanks!

A: By specifying automatic margins for left and right edges:
margin:0 auto;

This forces the browser to equalize them within the parent, which has full browser width, so it's centered since you have explicitly set the width.
Sample implementation.

A: Well it depends on the parent element, and why you have it as position:relative;, but generally to center a block level element with a set width, within it's parent, you can just use:
margin:0 auto

A: Since you have a width set, you should use
margin:0 auto;

A: You should try this jsfiddle :
HTML :

This is some DIV

CSS :
div {
    width : 50%;
    margin : auto;
    border : 1px solid black; // To see that it is centered
}

A: Usually when doing this you want to do something like below.  It will stay withing the bounds of it's parent element and wherever you put it on the page but will place it in the middle.
If you want to put it in the code:
    style="
    margin-left:auto;
    margin-right:auto;"
Otherwise just add that to your css for the div.
using this method will not set your upper and lower margin to auto.

A: use margin: 0 auto;
0 - stands for 0px top and bottom sides of the page
auto - means it'll adjust itself according to the available window size and can make it center.


text:
Q: syscacheobjects is cleared randomly Microsoft SQL Server Web Edition (64-bit)
Version 10.50.1600.1
SQL Server 2008 R2
I have noticed that we are getting a lot of execution plan re-complilcations - first executions quite slow, subsequent calls very fast as you would expect.
However, periodically (after around 10 minutes or so), performances returns to that of the first query i.e. execution is slow again, then fast.
I have read many articles on what could cause this; I have changed auto update statistics to off as suggested.
What I have noticed is that syscacheobjects will build up nicely, with usecounts into the 1,000's - then suddenly the table will be empty, causing all the queries to recompile.
Does anyone know why the cache may be getting flushed like this?
Many thanks
Paul

A: A couple of things to check into. These two you could capture with a server-side trace or extended events (though I haven't used the latter for this specific task):

*

*explicit calls to DBCC FREEPROCCACHE or DBCC FREESYSTEMCACHE

*certain explicit calls to RECONFIGURE (or RECONFIGURE WITH OVERRIDE)

If you see these calls happening often, you'll want to figure out where they're coming from and why, because they absolutely flush the procedure cache.
Also check the error log for events containing the text "cachestore flush":
EXEC xp_readerrorlog 0, 1, N'cachestore flush';

If you see these events make sure the database in question does not have the option AUTO_CLOSE on. You may want to make sure this isn't the case anyway, and it is often turned on with Web Edition since this edition is typically used to hold a lot of infrequently-used databases at a web host.


text:
Q: How do I avoid problems arising from accessing static fields before the class is initialized? I have this code:
public abstract class Person {

    public static final class Guy extends Person {

        public static final Guy TOM = new Guy();
        public static final Guy DICK = new Guy();
        public static final Guy HARRY = new Guy();
    }

    public static final List<Guy> GUYS = ImmutableList.of(Guy.TOM, Guy.DICK, Guy.HARRY);
}

I know, it looks like it should be an enum, and it would be, but it needs to inherit from Person, an abstract class.
My problem is: If I try to access the list of Guys, I'm okay.  But it I try to access any one Guy in particular, I have a problem: Guy gets loaded before Person.  However, since Guy inherits Person, Person gets loaded, and tries to access TOM, but since Guy is already being loaded, it can't start to load again, and so we have a null reference.  (And ImmutableList doesn't accept null, so we get an exception.)
So I know why this is happening, but I'm not sure how to avoid it.  I could move the List into the Guy class, but I'll have more than one implementation of Person, and I'd like to have a master list of all Persons in the Person class.
It seems strange to me that it's possible to load a static inner class without loading its containing class, but I guess it makes sense.  Is there any way to solve this problem?

A: You could keep your immutable list in a separate class, like People.GUYS:
public class People {
    public static final List<Guy> GUYS = ImmutableList.of(Guy.TOM, Guy.DICK, Guy.HARRY);
}

This way you can still keep the individual guys in the Guy class:
public abstract class Person {

    public static final class Guy extends Person {

        public static final Guy TOM = new Guy();
        public static final Guy DICK = new Guy();
        public static final Guy HARRY = new Guy();
    }
}

A: A solution for the sake of solution, this seems working (for single thread)
public class Person
{
    static Lazy tom = new Lazy();
    static Lazy cat = new Lazy();

    public static final List<Guy> GUYS = ImmutableList.of(tom.get(), cat.get());

    public static final class Guy extends Person
    {
        public static final Guy TOM = tom.get();
        public static final Guy CAT = cat.get();
    }

    static class Lazy
    {
        Guy v;
        Guy get()
        {
            if(v==null)
            {
                Object x = Guy.TOM; // just to trigger Guy initialization
                if(v==null)
                    v = new Guy();
            }
            return v;
        }
    }

OP's design is inherently recursive. Although Java has a well-defined initialization procedure (which backs off when recursion is detected), the behavior varies depending on which class is initialized first.
The problem is worsened by the requirement that the fields are final, which severely limits how we can assign them. Otherwise, we can try if(null) assign in multiple places to solve the problem.
The solution posted above essentially uses a temporary variable to workaround the final constraint.

A modified version using a Map, suitable for more number of fields:
public class Person
{
    static Map<String,Guy> cache = new HashMap<>();  // remove after both class are initialized
    static Guy get(String name)
    {
        if(!cache.containsKey(name))
        {
            Object x = Guy.TOM; // just to trigger Guy initialization
            if(!cache.containsKey(name))
                cache.put(name, new Guy());
        }
        return cache.get(name);
    }

    public static final List<Guy> GUYS = ImmutableList.of(get("tom"), get("cat"));

    static{ if(Guy.TOM!=null) cache=null; }

    public static final class Guy extends Person
    {
        public static final Guy TOM = get("tom");
        public static final Guy CAT = get("cat");

        static{ if(Person.GUYS!=null) cache=null; }
    }

Multi-Threading
It's possible that one thread starts initializing Person while another thread starts initializing Guy. Deadlock is possible, and it does happen in real world. Therefore this design is inherently flawed.
In general, two classes (not necessarily parent-child) having dependency on each other during static initialization is inherently in danger of deadlock.
Application can get away with doing this kind of thing, by carefully triggering initialization in a predictable way at the application start. Still, this is quite dangerous, and it could send someone into days of debugging hell.

A: Is the requirement to use the Person abstract class absolute (i.e. is it already a part of legacy code)?
If not then as a recommendation, I suggest that you could refactor the design of your data model into a Guy enum class that implements a Person interface.  There are many advantages to this design over the class-based one.
public enum Guy implements Person {

    TOM {
        @Override
        public void personMethod1(...) {...} // constant-specific
            :
            :
    },
    DICK {
        @Override
        public void personMethod1(...) {...} // constant-specific
            :
            :
    };

    @Override
    public int personMethod2(...) {...} // general to the enum class
        :
        :
}

Note that in this case there is no reason to define a List instance with the constant references as the enum API provides the GUY.values() method.
It would solve all your initialization woes while still enabling multiple implementations of Person.  The downside is in code duplication.  The methods in Person will need to be implemented in every enum class (but if there are many methods you can always create a private static helper class and forward method calls to it.)

A: change
public static final List<Guy> GUYS = ImmutableList.of(Guy.TOM, Guy.DICK, Guy.HARRY);

to
public static final List<Guy> GUYS = Collections.unmodifiableList(Arrays.asList(new Guy[] {Guy.TOM, Guy.DICK, Guy.HARRY}));

should work (I tested using JDK 8), but is it still meet your requirement?
public abstract class Person {

    public static final class Guy extends Person {

        public static final Guy TOM = new Guy();
        public static final Guy DICK = new Guy();
        public static final Guy HARRY = new Guy();
    }

    public static final List<Guy> GUYS = Collections.unmodifiableList(Arrays.asList(new Guy[] {Guy.TOM, Guy.DICK, Guy.HARRY}));
}


text:
Q: Integrate javascript in wordpress This is the code

        Mouse over this

This code is for an object(image in my case) to follow mouse pointer. I have put the javascript in the  tags but I want the html to be applied on the whole website instead of one page or post.
How I can do this?

A: Try this:-
//For adding javascript and css
    add_action('wp_enqueue_scripts','wdm_test_script');
    function wdm_test_script(){ ?>

    <?php }
//For adding content to all pages
    add_filter('the_content','wdm_demo_content',1,1);
    function wdm_demo_content($content){
        ob_start();
    ?>

Mouse over this

    <?php
    $contents = ob_get_contents();
    ob_end_clean();
    return $contents.$content;
    }


text:
Q: Table View not showing titles I'm developing my project on swift and create a simple table view with one cell, then i created a label, but it's not showing. What's the problem and how to fix it?

A: If you're transitioning back to the TableView from another ViewController, try updating on the main thread in ViewDidAppear.
Making sure you're dequeuing the correct cell is also another potential fall, as mentioned above.
Hard to help without code though, hope this helps.
override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)
    dispatch_async(dispatch_get_main_queue()) {
        self.tableView.reloadData()
    }
}


text:
Q: Can I change solid into liquid, gas or solute by cutting again and again until it is a molecule particle? If I have small piece of solid, for example, pure iron powder, fine sand , (at room temperature) then I cut it slowly into half again and again. Every times, after I cut it, I wait for temperature back to room temperature again.
Case 1: If I do this in vaccuum, is it change to liquid or gas ?
I think it might be impossible because intermolecular force will make it form solid again. If it is impossible what is the smallest size (approximately) that I can get and is it look like viscous liquid ?
Case 2: If I do this in water or in polar liquid, is it change to solute ?
Case 3: If I do this in carbon tetrachloride or in nonpolar liquid, is it change to solute ?

A: Solid, liquid and gas are properties that belong only to multiple particles, not a single particle.  Those words describe the relationship between different particles, not a single particle.
If you end up with a molecule, all you have is a molecule.
Now if you end up with zillions of molecules all whizzing around more or less at random, you have a gas.
If you end up with a dense bunch (zillions again) of molecules which are very close together but not actually joined by molecular bonds, then it's a liquid.
And if you end up with molecules that are clumped together by strong molecular bonds in a more or less rigid structure, it's a solid.
Whether a substance is soluble in water is, thankfully, the problem of chemists.  A substance can react in many ways to contact with water.
Wikipedia's page on Carbon Tetrachloride also lists it's solubility in water.

A: There is no free lunch. The mechanical breaking of bonds by cutting will take as much energy as melting or boiling and the final temperatures should also be the same. It may seem impossible to get a liquid this way, but assuming a perfectly insulated sample, it will. The act of cutting will generate higher energy molecules that are vibrating or moving linearly. This is the definition of heat, so the answer to doing without heat is no, you can't.


text:
Q: Hibernate can insert but does not delete entry I'm having issues trying to delete an entry in my database table.
The structure of the database is as follows:
User ---< UserET >--- ExitTicket

ExitTicket.java
@Entity
@Table(name = "exit_ticket")
public class ExitTicketEntry implements Serializable {

private static final long serialVersionUID = 1L;

    private long id;
    private String title;
    private String dateET;
    private Set<UserET> userETs= new HashSet<UserET>();

    public ExitTicketEntry() {}

    public ExitTicketEntry(String title,String dateET) {
        this.title = title;
        this.dateET = dateET;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY )
    @Column(name = "ticket_id")
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }

    @OneToMany(mappedBy = "exitTicketEntry", orphanRemoval=true)
    public Set<UserET> getUserETs() {
        return userETs;
    }

    public void setUserETs(Set<UserET> userETs) {
        this.userETs = userETs;
    }

    public void addUserETs(UserET userETs) {
        this.userETs.add(userETs);
    }

    //getters and setters
}

UserET.java
@Entity
@Table(name="userET")
public class UserET implements Serializable {

    //private static final long serialVersionUID = 1L;

    private long answerId;
    private User user;
    private ExitTicketEntry exitTicketEntry;
    private String answer;
    private Date dateAnswer;

    @Id
    @GeneratedValue
    @Column(name="answerId")
    public long getAnswerId() {
        return answerId;
    }
    public void setAnswerId(long answerId) {
        this.answerId = answerId;
    }

    @ManyToOne(cascade = CascadeType.ALL )
    @JoinColumn(name = "user_id")
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "ticket_id")
    public ExitTicketEntry getExitTicketEntry() {
        return exitTicketEntry;
    }
    public void setExitTicketEntry(ExitTicketEntry exitTicketEntry) {
        this.exitTicketEntry = exitTicketEntry;
    }

    @Column(name = "answer")
    public String getAnswer(){
        return answer;
    }
    public void setAnswer(String answer) {
        this.answer = answer;
    }

    @Column(name = "dateAnswer")
    @Temporal(TemporalType.DATE)
    public Date getDateAnswer() {
        return dateAnswer;
    }
    public void setDateAnswer(Date dateAnswer) {
        this.dateAnswer = dateAnswer;
    }

User.java
@Entity
@Table(name="USER")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    private long id;
    private String user_name, user_password, user_type,user_realname;

    private Set<UserET> userETs= new HashSet<UserET>();

    public User() {
    }

    public User(String user_name,String user_password,String user_type,String user_realname) {
        this.user_name = user_name;
        this.user_password = user_password;
        this.user_type = user_type;
        this.user_realname=user_realname;
    }

    public void addExitTicketEntry(UserET group) {
        this.userETs.add(group);
    }

    @Id
    @GeneratedValue
    @Column(name="user_id")
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @OneToMany(mappedBy = "user", orphanRemoval=true)
    public Set<UserET> getUserETs() {
        return userETs;
    }

    public void setUserETs(Set<UserET> userETs) {
        this.userETs = userETs;
    }

    public void addUserETs(UserET userETs) {
        this.userETs.add(userETs);
    } ... + getters and setters

I am able to insert a new Entry of ExitTicket correctly (using ExitTicketService.java), with this function:
public void addEntryET(ExitTicketEntry exitTicketEntry) {
    log.info("adding entry in database");
    try {
        hibernateTemplate.save(exitTicketEntry);
    }
    catch(Exception e) {
        log.info("error adding an entry in the database->"+e.toString());
    }
}

However when I try to delete an entry from the database table, the hibernate delete only does 'select' commands and never gets to do a 'delete'
2018-11-05 09:28:27 INFO  AuthService:72 - entro 1 ------
Hibernate: select exitticket0_.ticket_id as ticket_i1_0_0_, exitticket0_.dateET as dateET2_0_0_, exitticket0_.title as title3_0_0_ from exit_ticket exitticket0_ where exitticket0_.ticket_id=?
Mon Nov 05 09:28:27 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2018-11-05 09:28:27 TRACE BasicBinder:65 - binding parameter [1] as [BIGINT] - [9]
2018-11-05 09:28:27 TRACE BasicExtractor:61 - extracted value ([dateET2_0_0_] : [VARCHAR]) - [2011-05-20]
2018-11-05 09:28:27 TRACE BasicExtractor:61 - extracted value ([title3_0_0_] : [VARCHAR]) - [test1]
2018-11-05 09:28:27 TRACE CollectionType:790 - Created collection wrapper: [com.jcg.spring.hibernate.pojo.ExitTicketEntry.userETs#9]
Hibernate: select userets0_.ticket_id as ticket_i4_2_0_, userets0_.answerId as answerId1_2_0_, userets0_.answerId as answerId1_2_1_, userets0_.answer as answer2_2_1_, userets0_.dateAnswer as dateAnsw3_2_1_, userets0_.ticket_id as ticket_i4_2_1_, userets0_.user_id as user_id5_2_1_, user1_.user_id as user_id1_1_2_, user1_.user_name as user_nam2_1_2_, user1_.user_password as user_pas3_1_2_, user1_.user_realname as user_rea4_1_2_, user1_.user_type as user_typ5_1_2_ from userET userets0_ left outer join USER user1_ on userets0_.user_id=user1_.user_id where userets0_.ticket_id=?
2018-11-05 09:28:27 TRACE BasicBinder:65 - binding parameter [1] as [BIGINT] - [9]
2018-11-05 09:28:27 INFO  AuthService:99 - deleted entry with ID#=9

My delete function in my service class:
public void deleteById(Class<?> type, long id) {
    log.info("entro 1 ------");
    ExitTicketEntry e=(ExitTicketEntry) hibernateTemplate.load(type,id);
    hibernateTemplate.delete(e);
}

I've been reading plenty of forums, but still have the same issue, I can't delete any entries. Am I missing something?


text:
Q: How to open a jquery ui dialog box from an iframe on a click event I am trying to open a jquery ui dialog box from an iframe. When the button is clicked to open the dialog box, the dialog box is suppose to display over the iframe like a bootstrap modal.
The problem I am having is when I click a button to open the dialog box it opens the entire page of the other file inside the dialog box.
myIframeFile.asp:
<iframe id="myiframe" src="myFileToOpenTheDialogBox.asp?a=<%=Request.QueryString("a")%>">

myFileToOpenTheDialogBox.asp:
   <button id="btnOptions">Options</button>

      <form>
        ...
      </form>


text:
Q: Unity lanucher bug - problem with stacked aps I have problem with launcher, i'm not able to switch between running aps if they are piled - lets say i have 2x terminal running, when i click on terminal icon in launcher instead this window manager everything disappear and reappear after few seconds. I'm able to successful change with tab or right click
Kindly ask for any help.

A: I resolve this problem , here is solution for all people who struggle with unity bugs.
sudo su
apt-get update
apt-get autoclean
apt-get install --reinstall ubuntu-dekstop
apt-get install --reinstall unity

If you still have problem you can try reinstall video drivers.
If there will be still problem - well i think only reinstall left.


text:
Q: Android RTP/RTCP Stack I'm looking for a Stack/Library which offers me a full utilizing of all Header-Fields of the RTP- and RTCP-Protocol under Android.
I don't know if this is important, but I want to combine it with the JAIN-SIP Stack which I'm using for SIP and SDP.
Have anyone any experience or any suggestions?
The android.net.rtp is not really what I'm looking for, cause as far as I understood it is not offering me the possibility to read the RTCP reports.
Thanks for your help in advance :-)
Daniel


text:
Q: Divide numbers in 2 multidimensional array I have 2 sets of multidimensional array ($profit & $sales). I want to divide the numbers in 2 multidimensional array to get the % of margin (using this formula: $profit/$sales*100)
$profit= array(
    0 => array(
        "no"=> "1",
        "value"=>"10"
    ),
    1=> array(
        "no"=> "2",
        "value"=>"15"
    )
);

$sales= array(
    0 => array(
        "no"=> "1",
        "value"=>"100"
    ),
    1=> array(
        "no"=> "2",
        "value"=>"200"
    )
);

This is the expected output:
$margin= array(
    0 => array(
        "no"=> "1",
        "value"=>"10"
    ),
    1=> array(
        "no"=> "2",
        "value"=>"7.5"
    )
);

I have done some search with no luck still, below is the function that I'm using, it is not working:
function ArrayDivide($arrayList = [])
{

    $m = [];
    $no_details = [];
    $i = 0;

    foreach ($arrayList as $arrayItem) {
        foreach ($arrayItem as $subArray) {
            if (isset($no_details[$subArray['x']])) {//if no is exist
                $m[$no_details[$subArray['x']]]['y'] =  $m[$no_details[$subArray['x']]]['y'] /$subArray['y']*100;
            } else {
                $no_details[$subArray['x']] = $i;
                $m[$i] = ["x"=>$subArray['x'], "y"=>"0"];
                $i++;
            }
        }
    }
    return $m;

}

How you done similar function before? Where should I fix?
Thanks.

A: Something like this ? If I understood your question correctly.
function getMargin($profit, $sales){

    $margin = [];

    foreach($profit as $key => $val){

        $no = $val['no'];
        $value = $val['value'];

        if(isset($sales[$key]) && $sales[$key]['no'] == $no){

            $res = ($value/$sales[$key]['value'])*100;

            $margin[$key]['no'] = $no;
            $margin[$key]['val'] = $res;

        }

    }

    return $margin;

}

var_dump(getMargin($profit, $sales));

A: Use "Sourcey86" code and replace:
$res = $value / $no;
to
$res = $value/$sales[$key]['value']*100;
(I don't have enough points to add a comment on his post :D )


text:
Q: Do I need a where clause in a conditional UPDATE? We imported a lot of data from another table. Now I'm trying to correct some of them.
UPDATE [x10ddata].[dbo].[ResourceTest]
  SET [Country] = (CASE
      WHEN [Country] IN ('Aezerbaijan', 'AZERBIJAN') THEN 'Azerbaijan'
      WHEN [Country] = 'Belgique'    THEN 'Belgium'
      WHEN [Country] = 'China (RPC)' THEN 'China'
      WHEN [Country] = 'Columbia'    THEN 'Colombia'
     WHEN [Country] = 'Croatia (Local Name: Hrvatska)' THEN 'Croatia'
     .....//...
     WHEN [Country] IN ('U.S.', 'U.S.A', 'U.S.A.', 'US', 'USA',
                         'USA - Maryland', 'USAQ') THEN 'United States'
    END)
  GO

I didn't use ELSE because many rows have valid country. My question is to know whether I need to the WHERE clause to filter the rows that will be affected?
The reason I'm asking this question is that, I've selected into a test table and tried the the script. According to the output, all the rows affected, but when I check closely, not all the rows were affected. It's confusing.
Thanks for helping

A: The case statement will return null if none of the when clauses are met.  You can verify this with this simple sql:
declare @i int
set @i = 2
select case when @i = 1 then 'A' end AS Column1

This will return null since @i is not 1.
To fix this in your case, you can either add the where clause like you said, or the simpler option might be to add ELSE [Country] after all of your WHEN clauses.  This would mean "If I don't need to change the country field, then just use the same value that was there before."

A: You won't need a WHERE clause, but the ELSE clause is needed. Change your statement to:
UPDATE [x10ddata].[dbo].[ResourceTest]
  SET [Country] = (CASE
      WHEN [Country] IN ('Aezerbaijan', 'AZERBIJAN') THEN 'Azerbaijan'
      WHEN [Country] = 'Belgique'    THEN 'Belgium'
      WHEN [Country] = 'China (RPC)' THEN 'China'
      WHEN [Country] = 'Columbia'    THEN 'Colombia'
     WHEN [Country] = 'Croatia (Local Name: Hrvatska)' THEN 'Croatia'
     .....//...
     WHEN [Country] IN ('U.S.', 'U.S.A', 'U.S.A.', 'US', 'USA',
                         'USA - Maryland', 'USAQ') THEN 'United States'
     ELSE [Country]
    END)

A: alternatively,
Make a conversion table,
DECLARE @conversion TABLE
(
    [Before] NVARCHAR(250) NOT NULL,
    [After] NVARCHAR(250) NOT NULL
);

INSERT @conversion
VALUES
('Aezerbaijan', 'Azerbaijan'),
...
('USAQ', 'United States');

Then do,
UPDATE [x10ddata].[dbo].[ResourceTest]
            SET [Country] = [C].[After]
    FROM
            [x10ddata].[dbo].[ResourceTest]
        JOIN
            @conversion [C]
                ON [C].[Before] = [C].[Country];

This has a number of potential performance benefits over the extend CASE approach, among which is only effecting rows that need to change.
Its probably worth using a temporary table instead of a table variable and creating an index on [Before] to optimize the join.

A: No you don't need a where clause because your CASE statements contain your logic.
Note: If a value doesn't match any of your CASE statements then it will return null. So I recommend adding ELSE [Country] at the end. Here's an example that demonstrates what I'm saying
SELECT * INTO #yourTable
FROM
(
    SELECT 1 ID, CAST('OldValue' AS VARCHAR(25)) val
    UNION ALL
    SELECT 2 , 'OldValue'
    UNION ALL
    SELECT 3,'Doesnt need to be updated'
) A

SELECT *
FROM #yourTable;

Results:
ID          val
----------- -------------------------
1           OldValue
2           OldValue
3           Doesnt need to be updated

Now update:
UPDATE #yourTable
SET val =
    CASE
        WHEN ID = 1 THEN 'NewValue1'
        WHEN ID = 2 THEN 'NewValue2'
        --Add this so you leave values alone if they don't match your case statements
        ELSE val
    END
FROM #yourTable

SELECT *
FROM #yourTable

Results:
ID          val
----------- -------------------------
1           NewValue1
2           NewValue2
3           Doesnt need to be updated

A: No, you don't NEED it. Aside from the performance cost that may be incurred through additional (unnecessary) writes to disk and locking (blocking other sessions), the physical outcome would be the same.
One could argue that you SHOULD use a WHERE clause, not only for performance reasons, but to better capture and convey intentions.


text:
Q: Binding  to advice body getting inconsistent binding I was able to get the @AfterThrowing work for my basic needs
@AfterThrowing(pointcut = "within(@custom.SomeAnnotation *) || @annotation(custom.SomeAnnotation) ", throwing = "ex")
public void intercept(Throwable ex) {
    // do stuff
}

But when I try to read a field from the annotation I'm getting  java.lang.IllegalArgumentException: error at ::0 inconsistent binding
I tried several approaches, the last one that I tried was:
@AfterThrowing(pointcut = "within(@custom.SomeAnnotation *) || @annotation(custom.SomeAnnotation) || @annotation(custom.SomeAnnotation(myProperty))", throwing = "ex", argNames = "ex, myProperty")
public void intercept(Throwable ex, String myProperty) {
    // do stuff
}

Am I using the pointcut correctly?
I tried
@AfterThrowing(pointcut = "within(@custom.SomeAnnotation *) || " +
            "@annotation(custom.SomeAnnotation) || " +
            "@annotation(custom.SomeAnnotation) && args(myProperty))",
            throwing = "ex", argNames = "ex, myProperty")

@AfterThrowing(pointcut = "@annotation(theAnnotation)",
throwing = "ex", argNames = "ex, theAnnotation")
public void intercept(Throwable ex, custom.SomeAnnotation theAnnotation)


text:
Q: Laptop memory "on BD"? Whilst browsing for a new laptop, I came across a new memory configuration:

*

*8GB DDR3 1600MHz

*Configuration 4GB x 1 + 4GB on BD

*1 x DIMM slot

It looks like a single RAM slot with 8GB, filled with a 4GB stick, but then with "+ 4GB on BD".
What is this 4GB on BD?


text:
Q: Atribuição de responsabilidades no MVC Estou iniciando o trabalho com MVC, mais especificamente com Laravel e o Eloquent (o ORM embutido no Laravel).
Estudei e continuo estudando o padrão MVC e suas vantagens. No entanto, na prática, fiquei com algumas dúvidas de onde atribuir as devidas responsabilidades. Principalmente pela flexibilidade do framework e das várias dezenas de variações do MVC.
Vamos lá: na minha aplicação utilizarei métodos que trarão por exemplo noticias em destaque. Tal método deve ficar no Model ou no meu Controller? Por quê?

A: Pense que as controllers são apenas um dos pontos de entradas para a sua aplicação, e por isso devem possuir o mínimo de código possível. Digo isso porque pode haver outros pontos de entrada, como comandos, APIs etc.
Em geral a maior parte do código nas minhas aplicações reside nas models (que, pra mim, são representações das entidades da aplicação, que por sua vez são replicadas no banco de dados); nos repositórios (responsáveis por trazer uma instância ou uma coleção de entidades); e nos serviços (que são responsáveis por executar uma tarefa específica na aplicação).
Voltando à sua pergunta, você diz que quer buscar notícias em destaque. Eu faria da seguinte maneira:

*

*Ter um método no controlador mapeado à rota (por exemplo) /noticias/destaques. O método poderia se chamar NoticiasController::destaquesAction.

*Ter uma entidade Noticia, que representa a notícia no seu banco de dados, e uma classe NoticiasRepository, responsável por trazer uma notícia ou uma coleção delas.

*Ter um método NoticiasRepository::getNoticiasEmDestaque que retorna uma coleção de notícias em destaque, ordenadas a seu gosto.

*Por fim, chamar esse método a partir do seu controlador e renderizá-la na view.

Assim é a forma que costumo desenvolver minhas aplicações. Se tiver alguma opinião a respeito, é só falar. :)


text:
Q: PayPal NVP API Error 10413 - The totals of the cart item amounts do not match order amounts I'm having a problem using the classic PayPal NVP API. It's complaining about how the totals don't match up and I really can't spot why that is.
The NVP name-value pairs which are sent to Paypal
array(19) {
  ["METHOD"]=>
  string(18) "SetExpressCheckout"
  ["AMT"]=>
  string(5) "48.00"
  ["MAXAMT"]=>
  string(5) "48.00"
  ["RETURNURL"]=>
  string(40) "http://vikingchallenge/site/payPalReturn"
  ["CANCELURL"]=>
  string(40) "http://vikingchallenge/site/payPalCancel"
  ["REQCONFIRMSHIPPING"]=>
  string(1) "0"
  ["NOSHIPPING"]=>
  string(1) "1"
  ["LOCALECODE"]=>
  string(2) "GB"
  ["PAYMENTREQUEST_0_AMT"]=>
  string(5) "48.00"
  ["PAYMENTREQUEST_0_CURRENCYCODE"]=>
  string(3) "GBP"
  ["PAYMENTREQUEST_0_ITEMAMT"]=>
  string(2) "40"
  ["PAYMENTREQUEST_0_TAXAMT"]=>
  string(4) "8.00"
  ["PAYMENTREQUEST_0_DESC"]=>
  string(6) "Adults"
  ["PAYMENTREQUEST_0_ALLOWEDPAYMENTMETHOD"]=>
  string(18) "InstantPaymentOnly"
  ["L_PAYMENTREQUEST_0_NAME0"]=>
  string(6) "Adults"
  ["L_PAYMENTREQUEST_0_DESC0"]=>
  string(6) "Adults"
  ["L_PAYMENTREQUEST_0_AMT0"]=>
  string(2) "20"
  ["L_PAYMENTREQUEST_0_QTY0"]=>
  string(1) "2"
  ["L_PAYMENTREQUEST_0_TAXAMT0"]=>
  string(4) "8.00"
}

The response from Paypal
array(9) {
  ["TIMESTAMP"]=>
  string(20) "2013-07-15T14:54:32Z"
  ["CORRELATIONID"]=>
  string(13) "f64e080a80db6"
  ["ACK"]=>
  string(7) "Failure"
  ["VERSION"]=>
  string(4) "92.0"
  ["BUILD"]=>
  string(7) "6868861"
  ["L_ERRORCODE0"]=>
  string(5) "10413"
  ["L_SHORTMESSAGE0"]=>
  string(94) "Transaction refused because of an invalid argument. See additional error messages for details."
  ["L_LONGMESSAGE0"]=>
  string(63) "The totals of the cart item amounts do not match order amounts."
  ["L_SEVERITYCODE0"]=>
  string(5) "Error"
}

A: Change L_PAYMENTREQUEST_0_TAXAMT0 to 4.00 since you have qty=2 of this line item.
METHOD=SetExpressCheckout
CANCELURL=http://vikingchallenge/site/payPalCancel
RETURNURL=http://vikingchallenge/site/payPalReturn
MAXAMT=48.00
REQCONFIRMSHIPPING=0
NOSHIPPING=1
LOCALECODE=GB
PAYMENTREQUEST_0_AMT=48.00
PAYMENTREQUEST_0_CURRENCYCODE=GBP
PAYMENTREQUEST_0_PAYMENTACTION=SALE
PAYMENTREQUEST_0_ITEMAMT=40
PAYMENTREQUEST_0_TAXAMT=8.00
PAYMENTREQUEST_0_DESC=Adults
PAYMENTREQUEST_0_ALLOWEDPAYMENTMETHOD=InstantPaymentOnly
L_PAYMENTREQUEST_0_NAME0=Adults
L_PAYMENTREQUEST_0_DESC0=Adults
L_PAYMENTREQUEST_0_AMT0=20
L_PAYMENTREQUEST_0_TAXAMT0=4.00
L_PAYMENTREQUEST_0_QTY0=2


text:
Q: Show that the function is constant Let $S^n$ be an $n$-dimentional unit sphere.
Consider $f: S^n \longrightarrow R_+$ even continuous function.
Denote
$$
F(f):=\int_0^{\infty}\int_{S^n}f(y)g\left(\frac{|xy|}{t}\right)dy\frac{dt}{t^{n+1}},
$$
where $x \in S^n, \, t>0$ and function $g$ is such that
$$
\int_{0}^{\infty}s^jg(s)ds=0, \quad j=0,2,4,\ldots, 2\left[(n-1)/2\right]
$$
$$
\int_1^{\infty}s^{\alpha}|g(s)|ds< \infty, \quad \alpha>n-1.
$$
Show that if Fourier transform $\hat{F}=f$, then $f$ is constant.
Thank you.


text:
Q: Proof of an inequality about $\frac{1}{z} + \sum_{n=1}^{\infty}\frac{2z}{z^2 - n^2}$ I've encountered an inequality pertaining to the following expression:
$\frac{1}{z} + \sum_{n=1}^{\infty}\frac{2z}{z^2 - n^2}$, where $z$ is a complex number.
After writing $z$ as $x + iy$ we have the inequality when $y \gt 1$ and $|x| \le \frac{1}{2} $:
$|\frac{1}{z} + \sum_{n=1}^{\infty}\frac{2z}{z^2 - n^2}|
 \le C + C\sum_{n=1}^{\infty}\frac{y}{y^2+n^2}$
The "proof" of the inequality is given as follows:
  $\frac{1}{z} + \sum_{n=1}^{\infty}\frac{2z}{z^2 - n^2} = \frac{1}{x+iy} +\sum_{n=1}^{\infty}\frac{2(x+iy)}{x^2 - y^2 - n^2 + 2ixy}$
But I fail to see how the inequality follows.

A: As
$$1\leq y\leq|x+iy|\leq{y\over2}+y={3\over2} y$$
we have
$${1\over |x+iy|}\leq 1$$
and
$$|n^2+y^2-x^2-2ixy|\geq |n^2+y^2-x^2|\geq\Bigl(1-{1\over8}\Bigr)(n^2+y^2)\qquad(n\geq1)\ .$$
It follows that
$$\left|{1\over z}+\sum_{n=1}^\infty{2z\over z^2-n^2}\right|\leq 1+\sum_{n=1}^\infty {3y \over{7\over8}(n^2+y^2)}=1+{24\over7}\sum_{n=1}^\infty {y \over n^2+y^2}\ .$$
Therefore the stated inequality is true with $C=4$, say.

A: The following is not the simplest way to solve this question but it may provide additional insight.
The key observation is that both sums have a closed-form representation. To see this, we first need to show that for $w = \sigma + it$
$$ |\pi \cot(\pi w)| \le \pi \coth(\pi t).$$
This is because
$$ |\pi \cot(\pi w)| =
\pi \left|
\frac{e^{i\pi\sigma-\pi t}+e^{-i\pi\sigma+\pi t}}
{e^{i\pi\sigma-\pi t}-e^{-i\pi\sigma+\pi t}}
\right|\le \pi
\frac{e^{\pi t}+e^{-\pi t}}{e^{\pi t}-e^{-\pi t}} = \pi \coth(\pi t)$$
for $t>0.$
Similarly, when $t<0$,
$$ |\pi \cot(\pi w)| =
\pi \left|
\frac{e^{i\pi\sigma-\pi t}+e^{-i\pi\sigma+\pi t}}
{e^{i\pi\sigma-\pi t}-e^{-i\pi\sigma+\pi t}}
\right|\le \pi
\frac{e^{\pi t}+e^{-\pi t}}{e^{-\pi t}-e^{\pi t}} = -\pi \coth(\pi t)$$
Now we use a classic technique to evaluate the two sums, introducing the functions
$$ f_1(w) = \pi \cot(\pi w) \frac{2z}{z^2-w^2} \quad \text{and} \quad
f_2(w) = \pi \cot(\pi w) \frac{z}{z^2+w^2},$$
with the conditions that $z$ not be an integer for $f_1(z)$ and not $i$ times an integer for $f_2(z).$ We choose $\pi \cot(\pi w)$ because it has poles at the integers with residue $1$.
The key operation of this technique is to compute the integrals of $f_1(z)$ and $f_2(z)$ along a circle of radius $R$ in the complex plane, where $R$ goes to infinity. Now by the first inequality we certainly have $|\pi\cot(\pi w)| < 2\pi$ for $R$ large enough. The two terms $\frac{2z}{z^2-w^2}$ and $\frac{z}{z^2+w^2}$ are both $\theta(1/R^2)$ so that the integrals are $\theta(1/R)$ and vanish in the limit. (Here we have used the two bounds on $|\pi \cot(\pi z)|$ that we saw earlier.) This means that the sum of the residues at the poles add up to zero.
Now let
$$ S_1 = \sum_{n=1}^\infty \frac{2z}{z^2-n^2} \quad \text{and} \quad
S_2 = \sum_{n=1}^\infty \frac{y}{y^2+n^2}.$$
By the Cauchy Residue Theorem,
$$ \frac{2}{z} - 2\pi\cot(\pi z) + 2S_1 = 0  \quad \text{and} \quad
 \frac{1}{y} - \pi\coth(\pi y) + 2S_2 = 0.$$
Solving these, we obtain
$$ S_1 = -\frac{1}{z}  + \pi\cot(\pi z)   \quad \text{and} \quad
 S_2 = - \frac{1}{2} \frac{1}{y} + \frac{1}{2} \pi\coth(\pi y).$$
Starting with the left side of the original inequality we finally have
$$\left| \frac{1}{z} + S_1\right| < \pi \coth(\pi y) = 2 S_2 +  \frac{1}{y} .$$
It follows that $C=2$ is an admissible choice.


text:
Q: How to import RequireJS (AMD) module in Angular 4.x (Angular Cli) App? I have a legacy JS file, written in the following RequireJS (AMD) module notation:
define('mymodule', [], function(){

    // ... bla bla bla

    return {
        calculate: function() { return 1 + 1; }
    };
});

I'm importing this file from another (legacy) project that uses RequireJS, therefore - I can't change the module definition used.
I want to import it in an Angular Cli (Angular 4.x) app written in TypeScript.
Since Angular Cli uses Webpack 2 to build projects, which supports AMD, I thought I can import it like this:
import * as MyModule from './mymodule.js';

... but that's not working, it triggers an error that the mymodule.js is not a module.
Any ideas (or workarounds) how can I import this legacy module?

A: I am able to load amd module.
here is TS:
import * as MyModule from './mymodule.js';

console.log('my value is', MyModule.value);

mymodule.js file:
define(["require", "exports"], function(require, exports){
   exports.value = "aaa";
});

and in tsconfig.js
"allowJs": true

UPDATE:
You can use System.import provided by webpack.
 declare var System: any;

 System.import('./mymodule.js')
     .then(MyModule=>console.log(MyModule.value));


text:
Q: Estimating Probability Estimate of low sample data I have a problem pertaining practical real-life situation we encounter quite often.
Lets say I have a e-commerce site selling clothes. There is a particular shirt which was sent N units to the warehouse and let's say few of them were bought online.
SO here are the questions:
1). What would be the estimate of future probability of selling of this shirt and the no. of units we can estimate to be sold in future.
2). If the no. of units are lets say 10 and we sold 10 of them, this is a low sample problem and sample estimate here is like 1.0, but that can't be correctly used to estimate the probability parameter.  How to estimate the future probability of selling of this shirt.
3). How to get an estimate for a completely new product which doesn't have any sales yet.
4). In general if someone buys 5 products. Normally if the items are independent of each other we can estimate the sales by taking the sum of probabilities times the no. of units etc. But in practice items are not bought independently, hence the probability distribution of each of these 5 items is not independent. In this case how can one get an estimate


text:
Q: How do I pass a method with two arguments to a Minitest Spec assertion? With Minitest Spec in Rails I'm trying to check if an ActiveSupport::TimeWithZone is in a certain range. I thought to use the between? method that takes the min and max of the range. Here's how I'm expressing that in Minitest Spec:

_(language_edit.curation_date).must_be :between?, 10.seconds.ago, Time.zone.now

but it gives me this error:

Minitest::UnexpectedError: ArgumentError: wrong number of arguments (1
  for 2)

What am I doing wrong?

A: Looks like must_be is implemented as infect_an_assertion :assert_operator, :must_be
assert_operator
# File lib/minitest/unit.rb, line 299
def assert_operator o1, op, o2, msg = nil
  msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op} #{mu_pp(o2)}" }
  assert o1.__send__(op, o2), msg
end

What if you use assert directly?
Example:
class DateTest < ActiveSupport::TestCase
  test "using assert with between? should work" do
    a = 5.seconds.ago

    assert a.between?(10.seconds.ago, Time.zone.now)
  end
end

A: Thanks to radubogdan for showing me some of the code behind the must_be method. It looks like it's designed to be used with operators like this:
_(language_edit.curation_date).must_be :>, 10.seconds.ago

and a side-effect of this is it works with boolean methods that take one or no arguments, but not with methods that take more than one argument. I think I'm supposed to do this:
_(language_edit.curation_date.between?(10.seconds.ago, Time.zone.now)).must_equal true


text:
Q: Decoupling K3S and containerd I am trying to run k3s on a pre-installed cointainerd on the node.
My goal in general is that when k3s is stopped, containerd will keep running.
It is also preferable that k3s will use the same containerd runtime as mentioned above.

A: There is a flag --container-runtime-endpoint which can be passed with the socket of your pre-installed containerd while initializing the k3s server/agent.
How to: agent-runtime-flags


text:
Q: Decrypting a Vigenere cipher with affine key Consider a cipher where the method of encryption is to perform a Vigenere cipher on a plaintext, with the key word being an affine cipher of the letters a,b,c,...,z.
How strong would this cipher be? Would it be possible to crack under a ciphertext only attack?

A: Yes, it could be broken using a ciphertext only attack given enough ciphertext.
Breaking vigenere ciphertext typically involves brute forcing the length of the key, then running statistical analysis. In this case, we already know the length of the key (26 characters), so we can go right to statistical analysis. With enough ciphertext this would be easy.
Obviously this is assuming knowledge of the plaintext language. In practice, that isn't too strong of an assumption, however.


text:
Q: How do I get and use the Apache Ivy.jar file from inside my project, without having it in my .ant folder? At the moment I have this configuration:
build.xml:
<!-- Ivy settings start-->

    <condition property="ivy.home" value="${env.IVY_HOME}">
        <isset property="env.IVY_HOME" />
    </condition>

    <target name="download-ivy" unless="offline" description="Download Ivy">
        <mkdir dir="${ivy.jar.dir}"/>
            <!-- download Ivy from web site so that it can be used even without any special installation -->
        <get src="http://repo2.maven.org/maven2/org/apache/ivy/ivy/${ivy.install.version}/ivy-${ivy.install.version}.jar"
            dest="${ivy.jar.file}" usetimestamp="true"/>
    </target>

    <target name="init-ivy" depends="download-ivy" description="Initialize Ivy">
        <!-- try to load ivy here from ivy home, in case the user has not already dropped
        it into ant's lib dir (note that the latter copy will always take precedence).
        We will not fail as long as local lib dir exists (it may be empty) and
        ivy is in at least one of ant's lib dir or the local lib dir. -->
        <path id="ivy.lib.path">
            <fileset dir="${ivy.jar.dir}" includes="*.jar"/>
        </path>
        <taskdef resource="org/apache/ivy/ant/antlib.xml"
        uri="antlib:org.apache.ivy.ant" classpathref="ivy.lib.path"/>
    </target>

    <target name="update" depends="init-ivy" description="Download project dependencies">
        <!-- edited for brevity -->

        <ivy:retrieve pattern="war/WEB-INF/lib/[artifact]-[revision].[ext]" />
        <!-- edited for brevity -->
    </target>

    <target name="clean-all" depends="clean" description="Purge ivy cache">
        <ivy:cleancache/>
    </target>

<!-- Ivy settings end-->

build.properties:
ivy.install.version=2.2.0
ivy.home=${user.home}/.ant
ivy.jar.dir=${ivy.home}/lib
ivy.jar.file=${ivy.jar.dir}/ivy-${ivy.install.version}.jar

ivy.xml:
<ivy-module version="2.0">
    <info organisation="org.apache" module="hello-ivy"/>
    <dependencies>
        <dependency org="commons-lang" name="commons-lang" rev="2.1" conf="default->master"/>

    </dependencies>
</ivy-module>

This means that Ivy will be downloaded to my ${user.home}/.ant/lib and will be used from there.
How can I download it to my project library(for example war/WEB-INF/lib) and use it from there, so all my files are together and not scattered around my computer?

A: Ivy is a plug-in to ANT.
Using an alternative directory is possible, however, you'd have to run ANT as follows, in order for ANT to pick up the ivy jar from it's alternative download location.
ant -lib $APP_DIR/lib .....

See the ANT manual for details on how ANT manages plugin libraries.
Additional note:
Ivy stores a cache of downloaded files under the following directory $HOME/.ivy2/cache. Alternative locations for this directory can be specified using the caches directive in your ivy settings file.


text:
Q: How to update static list from a dynamic list in a different sheet? I have two sheets, source (Staff) and destination (PatternToApply). In source I have dynamic list of people (it's getting updated automatically from another spreadsheet) and in destination I have static list of people.
I am trying to workout a script which automatically compare the list from both sheets and...

*

*if there is a new name in source sheet copy to destination sheet and insert a row below

*if in source sheet name is missing but it is in the destination sheet delete row from destination sheet
I'm still learning and don't know what I'm doing wrong. Please, any help will be much appreciated.

Here's the test spreadsheet
https://docs.google.com/spreadsheets/d/1mxmnsLeQFlorHj-N8MJX-Tue0v6zTKw4fUDhjZ1bGqs/edit?usp=sharing
Thank you!
Here's what I have so far
function UpdateAgList() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh1 = ss.getSheetByName('Staff');
  var sh2 = ss.getSheetByName('PatternToApply');
  var data1 = sh1.getRange(1,1,sh1.getLastRow(),1).getValues();
  var data2 = sh2.getRange(1,1,sh1.getLastRow(),1).getValues();

  for(i = 1; i<data1.length; i++){
    if(data1[i] == data2[i]){

      }
      else if(data1[i] != data2[i] && data2[i] == null){
        var numColumns = data1.getLastColumn();
        var rows = data1.getRow();
        var rowt = data2.getRow();
        var target = sh2.getRange(rowt, 1);
        data1.getRange(rows, 1, 1, numColumns).copyTo(target);
        sh2.insertRowAfter();
      }
      else if(data1[i] != data2[i] && data1[i] == null){
        target.clearContent();
      }
  }
}

A: Modification points:

*

*I thought that sh1.getLastRow() of var data2 = sh2.getRange(1,1,sh1.getLastRow(),1).getValues(); should be sh2.getLastRow().

*In your script, copyTo, getRange, and clearContent are used in a loop. In this case, the process cost will become high.

When these points are reflected in your script, how about the following modification?
Modified script:
function UpdateAgList() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh1 = ss.getSheetByName('Staff');
  var sh2 = ss.getSheetByName('PatternToApply');
  var data1 = sh1.getRange(1, 1, sh1.getLastRow(), 1).getValues();
  var targetRange = sh2.getRange(1, 1, sh2.getLastRow(), 1);
  var data2 = targetRange.getValues();
  var srcAr = data1.map(([a]) => a);
  var dstAr = data2.map(([a]) => a);
  var values = [
    ...dstAr.map(a => [a.toString() == "" ? a : (!srcAr.includes(a) ? "" : a)]),
    ...srcAr.reduce((ar, a) => (!dstAr.includes(a) && ar.push([a]), ar), []),
  ];
  targetRange.clearContent();
  sh2.getRange(1, 1, values.length).setValues(values);
}

*

*When this script is run, your goal is achieved while the empty rows are kept at the destination sheet.

*If you want to remove the empty rows at the destination sheet, please modify the above script as follows.

*

*From
  var values = [
    ...dstAr.map(a => [a.toString() == "" ? a : (!srcAr.includes(a) ? "" : a)]),
    ...srcAr.reduce((ar, a) => (!dstAr.includes(a) && ar.push([a]), ar), []),
  ];

*To
  var values = [
    ...dstAr.map(a => [a.toString() == "" ? a : (!srcAr.includes(a) ? "" : a)]),
    ...srcAr.reduce((ar, a) => (!dstAr.includes(a) && ar.push([a]), ar), []),
  ].filter(String);

References:

*

*map()

*reduce()


text:
Q: Masking Name with Regex in Javascript I wanna mask a name with the provisions that if there are more than 4 letters it will form the following masking :
Jason Mamoa ---> Ja**n Ma**a

I have tried this :
var name ="Jason Mamoa";
var regex =/\b[^\W]{2}([^\W]{2,})[^\W]\b/g;
console.log(nama.replace(regex,"**$1*"));

but the opposite happened, like this :
Jason Mamoa --> **so* **mo*

A: You need to go the other way around - capture the first two letters, and the last letter, and replace with them separated by **:

var name ="Jason Mamoa";
var regex =/\b(\w{2})\w+(\w)\b/g;
console.log(name.replace(regex, '$1**$2'));

If you want the resulting string to be the same length as the original, use a replacer function:

var name ="Jason Mammmmoa";
var regex =/\b(\w{2})(\w+)(\w)\b/g;
console.log(name.replace(
  regex,
  (_, first, middle, last) => `${first}${'*'.repeat(middle.length)}${last}`
));

Note that [^\W] is equivalent to \w.
To also mask the last 2 characters of 3 and 4 character names, capture up to 2 leading characters, and have the last be optional:

var name ="Eli Mose";
var regex =/\b(\w{1,2})(\w{2,}?)(\w?)\b/g;
console.log(name.replace(
  regex,
  (_, first, middle, last) => `${first}${'*'.repeat(middle.length)}${last}`
));


text:
Q: Serious XSRF bug in the new mobile theme Here's a serious bug with the new mobile theme that was rolled out.
http://meta.stackoverflow.com/mobile/on and http://meta.stackoverflow.com/mobile/off can be forced upon someone because they use GET rather than POST.

A: This has been fixed.
More annoying than serious, but still a bug.

A: I don't think it's dangerous, those actions just alter your session.
edit: I had attempted to trigger rep recalc, but that requires a POST apparently.  The OP mentioned actions work with a GET request.


text:
Q: How to change div width based on value from an sql table? I have a table that stores data. It has ratings for something that go 1-20. If something is a 1 then the page will load a bar with 5% width. Currently I have it so that the div uses style= and I just put the math in there.
<div class="bar" style="width:<?php $row["RATING"]*5 ?>%;">1/20

That seems really messy but its the simplest way I could think of. Is there a cleaner more practical method?

A: I think what you used is the better. If you define a class for each rating, then you have to create 20 classes. Keep things simple and focus on the idea of your application.

A: It could work if you used class names to define the width. You could use the value as part of the class name.
<div class="bar width_<?php $row["RATING"] ?">1/20

And define the used width in a CSS file. This will make it easier for changes in the future as well.


text:
Q: time.time() not working to run while loop for predetermined time in Cython I had a Python module which included a while loop which was supposed to run for a fixed amount of time. I did this by adding a constant to the output of time.time() and running until time.time() was greater than that variable. This did not present any issues, but the same thing is not working for me in Cython. Now I'm getting wildly off timings.
Just for a minimal example demonstrating this:
import time

cdef float wait_time = 3

def slow():
    cdef float end_time = time.time() + wait_time

    while time.time() < end_time:
        pass
    print("Done")

%timeit -r1 -n1 slow()
Done
44.2 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

%timeit -r1 -n1 slow()
Done
35.5 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

%timeit -r1 -n1 slow()
Done
35.5 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

%timeit -r1 -n1 slow()
Done
19.5 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

%timeit -r1 -n1 slow()
Done
35.5 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

%timeit -r1 -n1 slow()
Done
20.6 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

%timeit -r1 -n1 slow()
Done
20 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

%timeit -r1 -n1 slow()
Done
56 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

%timeit -r1 -n1 slow()
Done
1min 3s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

%timeit -r1 -n1 slow()
Done
32.9 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

%timeit -r1 -n1 slow()
Done
1min 5s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

The general behavior this tends to follow is that there will be essentially no wait, except for after pausing for a while before running the function, in which case there is an excessive wait.

A: Python's float is C's double.  C's float usually has only 24 significand bits (one of them implicit), giving it a precision of 128 seconds (since 2004).  When your addition changes from rounding down to rounding up, it moves from one minute in the past to a value one minute in the future.


text:
Q: Anonymous inner classes JAXB serialization I tried to use anonymous inner classes with initializers syntax to serialize JAXB generated objects, and noticed that it works on endpoints but not with RestTemplate. I am wondering why is it working in one case and not the other?
To give example, this is sample endpoint in Spring which returns JAXB generated Profile instance:
@PayloadRoot(namespace = NAMESPACE_URI, localPart = SERVICE_NAME)
@ResponsePayload
public Profile getProfile(@RequestPayload  GetProfile request) {

    // do stuff with service that returns Profile
    return service.doStuff(request);

}

Now, when i have service returning the anonymous instance of Profile, there are no serialization issues:
return new Profile() {

    {
        setBirthday(user.getBirthday());
        setEmailAddress(user.getEmailAddress());
        setFirstname(user.getFirstname());
        setGender(user.getGen());
        // and so on
    }
};

However, when i try to use anonymous inner classes as argument to RestTemplate, then i get JAXB error regarding the not supported anonymous classes.
"a non-static inner class, and JAXB can't handle those.
    this problem is related to the following location..."
    private UpdateProfile createUpdateProfileRequest(final UpdateProfile request) {

    return new UpdateProfile() {

        {
            setProfileV2(getProfile(request));
        }
    };

}

private ProfileV2 getProfile(UpdateProfile request) {

    ProfileV2 profile = new ProfileV2();

    ProfileUpdate profileUpdate = request.getProfileUpdate();

    profile.setBirthday(profileUpdate.getBirthday());
    profile.setFirstname(profileUpdate.getFirstname());

    return profile;

}

I have read this post:
What is Double Brace initialization in Java?
And i generally don't have use case where these objects could turn into container managed singletons - memory leaks.
There is a mention of serialization issues, but no details and i would like to understand this.
Since i am using JAXB for serialization on endpoints too, why it is possible for JAXB to serialize such objects as outgoing data on endpoints but not within RestTemplate.postForObject(...).


text:
Q: How do I open a Facebook link in the Facebook app? Consider:
dataTextView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        Intent facebookIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/app_scoped_user_id/1149231332XXXX/"));
        startActivity(facebookIntent);
    }
});

But it always open this URL in the browser instead of the app.

A: Check out https://graph.facebook.com/ (https://graph.facebook.com/fsintents for instance).
public static Intent openInFBApp(Context context) {
    try {
        context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
        return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/<id_here>"));
    } catch (Exception e) {
        return new Intent(Intent.ACTION_VIEW,Uri.parse("https://www.facebook.com/<user_name_here>"));
    }
}


text:
Q: Alias variable in MapBasic I'm having a bit of trouble with the Alias variable in MapBasic.
In short, I have a table where I was to group by a specific column.
Then I want to run through each unique value from the grouped table
through the original one and combine each one.
So I have a table of cities with a column of which country each city is in.
My program gives the user to choose a table and a column within that table to gorup by.
Then it basically goes like this:
Dim aSelection, aGrouped as Alias

Selection = selectedTable & "." & selectedColumn

Select * from selectedTable into Temp_GroupedTable Group By selectedColumn

aGrouped = Temp_GroupedTable & "." & selectedColumn

So a) is this code correct? b) How can I fetch the data from each row in the
Temp_GroupedTable so that I can compare it with the values in the original table?
I currently have this general setup within a loop:
Fetch rec i from Temp_GroupedTable

Select * from selectedTable into New_Temp_TAB Where aSelection = aGrouped

Objects Combine

I know there is something wrong... But I don't know how to fix it.
Any ideas?

A: Try this:
Dim aSelection, aGrouped as Alias
Dim sGrouped As String

aSelection = selectedTable & "." & selectedColumn
Select * from selectedTable
   into Temp_GroupedTable
   Group By aSelection

aGrouped = "Temp_GroupedTable." & selectedColumn

Fetch First from Temp_GroupedTable
Do Until EOT(Temp_GroupedTable)
   aGrouped = sGrouped
   Select * from selectedTable
      into New_Temp_TAB
      Where aSelection = sGrouped

'**  Objects Combine ...

   Fetch First from Temp_GroupedTable
Loop

I changed your first selection a bit and also the assignment of the aGrouped alias variable.
And then I made some changes to your loop. I'm not entirely sure what more you want to do within the loop.
I'm not entirely sure about this line: Where aSelection = aGrouped
You might need to read the value into a string or numeric value first.
But give it a go and let us know

A: Thanks for the help @Peter! I ended up using the following code which did what I needed:
Sub Process

Dim aGrouped as Alias

Print "Object Combiner Loaded!"

Select * from selectedTable into Temp_GroupedTable Group By selectedColumn
Print "Grouping Successful"

'*** Groups by user selected column
aSelection = selectedTable & "." & selectedColumn
Select * from selectedTable
    into Temp_GroupedTable
    Group By aSelection

aGrouped = "Temp_GroupedTable." & selectedColumn

Fetch First from Temp_GroupedTable  '*** Fetchs first row from grouped table
'*** Runs through table to combine objects by each individual value
Do Until EOT(Temp_GroupedTable)
    sGrouped = aGrouped
    Select * from selectedTable
        Where aSelection = sGrouped
    Objects Combine Data selectedColumn = sGrouped 'Retains value of
                                                   'selected column
    Fetch Next from Temp_GroupedTable
Loop

End Sub