text:
Q: How to reliably update data on a particular RecyclerView Item? The date/time in my RecyclerView Item only updates every other time I change it, not for every change. The current process is:

*

*User updates time via Date/TimePicker

*Change is saved to Room database

*My fragment's "reminders" LiveData observer is triggered, which calls the adapter's overridden submitList function

*For every ~2nd change, submitList thinks the old and new lists are identical, because the old list is somehow already updated to reflect the new changes even though the old list (mRemindersList) is private to the Adapter so I'm not sure how it's getting sneakily updated.

Example:
I changed the time from 15:21 to 21:21. After hitting OK on the below dialog, the RecyclerView Item still shows the old time of 15:21:
Picture of RecyclerView Item whose time is 15:21 while the new time selected is 21:21
Logs from submitList:
2022-05-26 17:57:30.314 6461-6461/com.example.ewmreminders V/ReminderListAdapter:165:submitList: Are the two lists the same? true
2022-05-26 17:57:30.315 6461-6461/com.example.ewmreminders V/ReminderListAdapter:168:submitList: Old list (size: 1): [Reminder(id=51, hour=21, minute=21)]
2022-05-26 17:57:30.315 6461-6461/com.example.ewmreminders V/ReminderListAdapter:169:submitList: New list (size: 1): [Reminder(id=51, hour=21, minute=21)]

If I click on the time again from my RecyclerView Item, the TimePickerDialog correctly defaults the time to 21:21 (so somewhere it knows the time was updated...) If I change the time to 18:21, as soon as I hit OK, the time updates:
Picture of RecyclerView Item whose time was updated correctly to 18:21
Logs from submitList:
2022-05-26 18:03:50.931 6461-6461/com.example.ewmreminders V/ReminderListAdapter:165:submitList: Are the two lists the same? false
2022-05-26 18:03:50.932 6461-6461/com.example.ewmreminders V/ReminderListAdapter:168:submitList: Old list (size: 1): [Reminder(id=51, hour=21, minute=21)]
2022-05-26 18:03:50.932 6461-6461/com.example.ewmreminders V/ReminderListAdapter:169:submitList: New list (size: 1): [Reminder(id=51, hour=18, minute=21)]

Code:
Adapter:
class ReminderListAdapter(private val timeClickListener: ReminderClickListener,
                          private val reminderListViewModel: ReminderListViewModel,
                          val activity: MainActivity,
                          val reminderDatabaseDao: ReminderDatabaseDao):
    ListAdapter<Reminder, ReminderListAdapter.ReminderListViewHolder>(DiffCallback),
    ItemTouchHelperAdapter
{
    private var mRemindersList = mutableListOf<Reminder>()

    override fun submitList(list: List<Reminder>?) {
        Timber.v("Are the two lists the same? ${mRemindersList == list?.toMutableList()}")
        Timber.v("Old list (size: ${mRemindersList.size}): $mRemindersList")
        Timber.v("New list (size: ${list?.size}): $list")

        mRemindersList = list.toMutableList() //DiffUtil needs a new list to compare to
        super.submitList(mRemindersList)
    }
}

Fragment:
class ReminderListFragment : Fragment() {
    private lateinit var reminderListViewModel: ReminderListViewModel
    lateinit var adapter: ReminderListAdapter

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val binding: FragmentReminderListBinding = DataBindingUtil.inflate(
            inflater, R.layout.fragment_reminder_list, container, false)

        val application = requireNotNull(this.activity).application
        val reminderDatabaseDao = ReminderDatabase.getInstance(application).reminderDatabaseDao
        val viewModelFactory = ReminderListViewModelFactory(reminderDatabaseDao, application)
        reminderListViewModel =
            ViewModelProvider(this, viewModelFactory)[ReminderListViewModel::class.java] //.get() and [] are the same thing
        binding.reminderListViewModel = reminderListViewModel
        binding.lifecycleOwner = this
        val manager = LinearLayoutManager(this.context)
        binding.remindersList.layoutManager = manager

        adapter = ReminderListAdapter(
            ReminderClickListener(application) { reminder, position ->
                val defaultReminderTime: LocalTime = LocalTime.of(reminder.hour!!, reminder.minute!!)
                val timeClickListener =
                    TimePickerDialog.OnTimeSetListener { view, hourOfDay, minute ->
                        val selectedTime = LocalTime.of(hourOfDay, minute)
                        reminderListViewModel.setTime(reminder, selectedTime) //updates the database
//                        adapter.notifyItemChanged(position)
                    }
                val tP = TimePickerDialogPlus(context, timeClickListener, defaultReminderTime.hour, defaultReminderTime.minute, true) {
                    Timber.v("User clicked the Clear button")
                    reminderListViewModel.setTime(reminder, null)
                }
                tP.show()
            },
            reminderListViewModel,
            activity as MainActivity,
            reminderDatabaseDao)
        binding.remindersList.adapter = adapter

        reminderListViewModel.reminders.observe(viewLifecycleOwner, Observer {
            it?.let {
                adapter.submitList(it.toMutableList())
            }
        })

        return binding.root
        }
}

View Model:
class ReminderListViewModel(val reminderDatabaseDao: ReminderDatabaseDao, application: Application) : AndroidViewModel(application) {
    fun setTime(reminder: Reminder, selectedTime: LocalTime?) {
        reminder.hour = selectedTime?.hour
        reminder.minute = selectedTime?.minute
        reminder.save(getApplication()) //eventually calls reminderDatabaseDao.update
    }
    var reminders = reminderDatabaseDao.getAllReminders()
}

Dao:
interface ReminderDatabaseDao {
    @Update
    fun update(reminder: Reminder)

    @Query("select * ...etc...")
    fun getAllReminders() : LiveData<List<Reminder>>
}

Thought

*

*I tried calling adapter.notifyItemChanged(position) but that didn't change anything

A: Yeah see, in your setTime function in the VM, you're passing in a Reminder instance and changing its data, mutating the object itself:
fun setTime(reminder: Reminder, selectedTime: LocalTime?) {
    reminder.hour = selectedTime?.hour
    reminder.minute = selectedTime?.minute

and the Reminder you're passing in is one of the objects in the adapter's internal list:
adapter = ReminderListAdapter(
    ReminderClickListener(application) { reminder, position ->
        ...
        reminderListViewModel.setTime(reminder, selectedTime)

So you're explicitly updating the Reminder in your adapter to 21:21 (which won't visually update because the adapter doesn't know anything about the change yet).

After setTime changes that Reminder object, it uses it to update the DB:
reminder.save(getApplication())

Which updates the record, which pushes a new list to the LiveData you grabbed with getAllReminders(), and that should contain unique Reminder instances. But remember, you already changed the adapter's internal list by updating that Reminder. The list you get from the DB is going to be the same as the old one, just with one of the Reminders' time changed, right?
Since you changed the adapter's internal list in the same way, the data is gonna match - the lists will look the same (I'm assuming your diff treats two Reminders with the same data as "the same", if they're data classes and checked for equality then yep). So the adapter doesn't bother updating the display - as far as it's concerned, nothing has changed.

Your dialog shows the correct time because the time has been set on that Reminder - the adapter just isn't showing it yet. I don't know why it would work every 2nd time with the exact same steps though - you'll probably need to set some breakpoints in useful places (e.g. in setTime, your observer on reminders, inside your dialog) and debug the app, see what's actually going on in there as it's running.

Sorry about the long answer but I wanted to explain why you're seeing that issue - you're effectively updating the adapter's internal list and the one in the DB/View Model at the same time, so they always match. You can probably fix it by not mutating the Reminder you pass in - just make a copy, change the time on it, and save that to the DB. Leave the old one untouched, so it reflects the old state. If you're using a data class, you can just do
reminder.copy(
    hour = selectedTime?.hour,
    minute = selectedTime?.minute
).save(application) // if you make application a val in your VM constructor you can access it here

and that might fix everything!


text:
Q: This word could not be fit on page. It will not be plotted. (Wordcloud) I am trying to print a wordcloud with 10 terms.
My data is:
freq.df$word <- c("toque queda","recorrido habitual","prevencion quedateencasa","mensaje directo","medidas preventivas","medidas prevencion","juntoslogramosmas prevencion","desvio linea","coronavirus

covid19","colectivos desvio")

freq.df$freq <- c(2320,2780,3020,2560,3390,3970,5180,2660,4580,3020)

The code I use is:
pal=brewer.pal(8,"PuBu")

wordcloud(freq.df$word,freq.df$freq,random.order = F, colors=pal)

But it returns the following error of several words:
 Warning in wordcloud(freq.df$word, freq.df$freq, random.order = F, colors = pal) :
  juntoslogramosmas prevencion could not be fit on page. It will not be plotted.
Warning in wordcloud(freq.df$word, freq.df$freq, random.order = F, colors = pal) :
  coronavirus covid19 could not be fit on page. It will not be plotted.
Warning in wordcloud(freq.df$word, freq.df$freq, random.order = F, colors = pal) :
  medidas prevencion could not be fit on page. It will not be plotted.
Warning in wordcloud(freq.df$word, freq.df$freq, random.order = F, colors = pal) :
  medidas preventivas could not be fit on page. It will not be plotted.
Warning in wordcloud(freq.df$word, freq.df$freq, random.order = F, colors = pal) :
  prevencion quedateencasa could not be fit on page. It will not be plotted.

How can I solve that? Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Running C# Program in Command Prompt regardless of the location of the Executable? I would like to integrate my program into the Command Interpreter in Windows 10 (preferably without registry edits). I have done minimal work with Libraries, but I still could write a DLL if that is necessary in any way. I would like to run my program, lets call it "speedtest" for this example. I would like to type the following in the Command Prompt to run it:
speedtest

Much like entering "py" into the Command Prompt with Python installed will open the Shell environment, I would like to do the same thing with my programs. Any way to do this easily?

A: Add your utility's Path to the environment variables list.
To do so, in Windows 10 and Windows 8

*

*In Search, search for "System" and then select: System (Control
Panel) Click the Advanced system settings link.

*Click Environment Variables. In the section System Variables, find
the PATH environment variable and select it. Click Edit. If the PATH
environment variable does not exist, click New.

*In the Edit System Variable (or New System Variable) window, specify
the value of the PATH environment variable. Click OK. Close all
remaining windows by clicking OK.

A: All python and similar programs are doing is adding the location of the executable to the PATH environment variable (while that may or may not be stored in the registry, its not exactly a registry edit, you can do it through the Windows GUI).
You will discover this when the automatic process fails for some reason because you have to add it to PATH yourself.
The command interpreter is very simple, it looks in the current directory for the command you input and then checks PATH. If there isn't a program with the same name as your command in either of those places, it will throw an error.
There just isn't any other way to hack it. Either add your program's location to PATH or write an installer to do it for you.


text:
Q: Android Facebook SDK I am working with Android Facebook SDK and wanted to get a friends list. I have created an "AsyncTask" for doing such a thing. I am pasting my doInBackgroundMethod here.
@Override
    protected String doInBackground(String... url) {
        String jsonResponse;
        try {
            jsonResponse =     Factory.getFacebook().request(Utils.LOGGEDIN_USER_FRIENDS);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return jsonResponse;
    }

Utils Code
public static final String LOGGEDIN_USER_FRIENDS = "me/friends";

The problem I am running in to is that it is returning an empty jsonResponse for the first time the application runs. When I open my app the second time I am getting the JsonResponse. But for the first time however I am getting empty jsonResponse.
Can any one help me out in this regard.

A: Well it was easy... It was messed up by creating a String variable in a Factory. Later on, the same day I saw that, and called the AsyncTask built in method get which provides the result in the same thread.


text:
Q: Bootstrap columns are moving together I have a container which contains two divs ( col-md-4 and col-md-8) and also I made a JQuery animation which gives the left div (col-md-4) a "-65%" amount of marginLeft when I click a toggle button. The problem is the other div (col-md-8) also moves with it to the left side as the first div moves. Is there a way to free the second div(col-md-8) from moving together with the first div (col-md-4) ?
Basically what I want to do is to hide and show the left div as I click the button, but want it to move over the second div rather than they move together in the row. Hope I could explain my request properly.
Thanks
Html code

<button id="button">toggle</button>

Animation
   var $div1 = $('#listhide')
$('#button').click(function() {
  $div1.toggleClass('isOut')
  var isOut = $div1.hasClass('isOut')
  $div1.animate({marginLeft: isOut ? '-35%' : '-65%'}, 300)
})

A: I have solved the problem, I should have used #listhideinner div instead of #listhide div, because it is the parent div, and we only want to child div to move so.
Animation (Updated one)
   var $div1 = $('#listhideinner')
$('#button').click(function() {
  $div1.toggleClass('isOut')
  var isOut = $div1.hasClass('isOut')
  $div1.animate({marginLeft: isOut ? '-35%' : '-65%'}, 300)
})


text:
Q: How to `pause`, and `resume` download work? Usually, downloading a file from the server is something like this:
fp = open(file, 'wb')
req = urllib2.urlopen(url)
for line in req:
    fp.write(line)
fp.close()

During downloading, the download process just has to be finished. If the process is stopped or interrupted, the download process needs to start again. So, I would like to enable my program to pause and resume the download, how do I implement such? Thanks.

A: In python, you can do:
import urllib, os

class myURLOpener(urllib.FancyURLopener):
    """Create sub-class in order to overide error 206.  This error means a
       partial file is being sent,
       which is ok in this case.  Do nothing with this error.
    """
    def http_error_206(self, url, fp, errcode, errmsg, headers, data=None):
        pass

loop = 1
dlFile = "2.6Distrib.zip"
existSize = 0
myUrlclass = myURLOpener()
if os.path.exists(dlFile):
    outputFile = open(dlFile,"ab")
    existSize = os.path.getsize(dlFile)
    #If the file exists, then only download the remainder
    myUrlclass.addheader("Range","bytes=%s-" % (existSize))
else:
    outputFile = open(dlFile,"wb")

webPage = myUrlclass.open("http://localhost/%s" % dlFile)

#If the file exists, but we already have the whole thing, don't download again
if int(webPage.headers['Content-Length']) == existSize:
    loop = 0
    print "File already downloaded"

numBytes = 0
while loop:
    data = webPage.read(8192)
    if not data:
        break
    outputFile.write(data)
    numBytes = numBytes + len(data)

webPage.close()
outputFile.close()

for k,v in webPage.headers.items():
    print k, "=", v
print "copied", numBytes, "bytes from", webPage.url

You can find the source: http://code.activestate.com/recipes/83208-resuming-download-of-a-file/
It only works for http dls

A: The web server must support Range request header to allow pause/resume download:
Range: <unit>=<range-start>-<range-end>

Then the client can make a request with the Range header if he/she wants to retrieve the specified bytes, for example:
Range: bytes=0-1024

In this case the server can respond with a 200 OK indicating that it doesn't support Range requests,
Or it can respond with 206 Partial Content like this:
HTTP/1.1 206 Partial Content
Accept-Ranges: bytes
Content-Length: 1024
Content-Range: bytes 64-512/1024

Response body.... till 512th byte of the file

See:

*

*Range request header

*Content-Range response header

*Accept-Ranges response header

*206 Partial Content

*HTTP 1.1 specification


text:
Q: Im trying to have a button do one action at once in two cells, getting error I'm currently working on an excel doc for work, and on it has two cells that have the same value in two different spots so it lines up in our system. This is what I currently have.
Sub CheckDuplicateVALUE()

'Declaring variables
Dim Cell As Variant
Dim Source As Range

'Initializing source range
Set Source = Range("O4:O200,C4:C200")

'Removing any previous formatting from the source
Source.Interior.Color = RGB(255, 255, 255)

'Looping through each cell in the source range
For Each Cell In Source

    'Checking whether value in cell already exist in the source range
    If Application.WorksheetFunction.CountIf(Source, Cell) > 1 Then

        'Highlighting duplicate values in red color
        Cell.Interior.Color = RGB(255, 0, 0)

    End If
Next

End Sub

What do I need to change in order to have it work in cells O4:O200 and C4:C200. I did not make this code I found it online as I just need help creating some things.

A: The main issue is that WorksheetFunction.CountIf doesn't work with a multi-area range as the first argument.

I'm comparing duplicates in the entire cell range like C4 = foo and C5 = foo. So when I run it it would highlight it and I can change it.

In that case, refactor to something like the following, calling HighlightDupes twice, once on each range.
Private Sub HighlightDupes(ByVal source As Range)
    source.Interior.Color = vbWhite

    Dim cell As Range
    For Each cell In source
        If Application.WorksheetFunction.CountIf(source, cell.Value) > 1 Then
            cell.Interior.Color = vbRed
        End If
    Next
End Sub

Sub CheckDuplicateVALUE()
    HighlightDupes Range("O4:O400")
    HighlightDupes Range("C4:C400")
End Sub

A: Could you just use conditional formatting on each range? It has a duplicate values function. I just recorded a macro and threw it into a simple loop in case you want to automate it. The code is ugly, but it should work fine for your circumstances.
Sub check_duplicates()

    Dim form_rng As Range
    Dim ws As Worksheet
    Dim i As Integer

    Set ws = Workbooks("your workbook").Sheets("your sheet")
    Set ws = ActiveSheet

    For i = 1 To 2
        If i = 1 Then
            Set form_rng = ws.Range("C4:C400")
        Else
            Set form_rng = ws.Range("O4:O400")
        End If
        form_rng.Select
        Selection.FormatConditions.AddUniqueValues
        Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
        Selection.FormatConditions(1).DupeUnique = xlDuplicate
        With Selection.FormatConditions(1).Font
            .Color = -16383844
            .TintAndShade = 0
        End With
        With Selection.FormatConditions(1).Interior
            .PatternColorIndex = xlAutomatic
            .Color = 13551615
            .TintAndShade = 0
        End With
        Selection.FormatConditions(1).StopIfTrue = False
    Next i

End Sub


text:
Q: Setting the names in `...` for an R function Suppose arguments of function foo are arbitrary defined as ....
If names of the arguments are a = c("ESL", "prof"), and their values are a1.vales = 1:8 and a2.vales = 0:7:
how can I make: foo(a[1] = a1.vales, a[2] = a2.vales) to work just like: foo("ESL" = a1.vales, "prof" = a2.vales)?
P.S. can setNames help here?
foo <- function(n = 2:9, ...){

  data.frame(n = n, ...)
}

## Function argument names and values:
a = c("ESL", "prof")
a1.vales = 1:8
a2.vales = 0:7

## Example of use:
foo(a[1] = a1.vales, a[2] = a2.vales)    # Fails?
foo("ESL" = a1.vales, "prof" = a2.vales) # Works

A: To solve your current problem there exists a workaround:
foo <- function(n = 2:9, ...){
  args <- list(...)
  setNames(data.frame(c(list(n), args[-1])), c("n", args[[1]]))
}

foo(n = 2:9, a, a1.vales, a2.vales)

  n ESL prof
1 2   1    0
2 3   2    1
3 4   3    2
4 5   4    3
5 6   5    4
6 7   6    5
7 8   7    6
8 9   8    7


text:
Q: Processing 3 : using background subtraction, video not playing I am trying to run simple processing program in eclipse to play video. this is the code:
import processing.core.*; import processing.video.*;

public class BackgroundSubtraction extends PApplet {

Movie video;

public void setup(){
size(720,480);
 video = new Movie(this,"/home/gurinderbeer/Desktop/new/Gurbinder/data/mv2_002.avi");
video.loop();
video.play();
}

public void draw() {
image(video, 0, 0);
}

   public void movieEvent(Movie m) {
  m.read();
}
}

when I run the program, it gives no error. Applet pops-up but video is not playing in applet. I can hear the audio when i run the program, but no visuals on applet. Can anyone please help...! Thanks

A: I had a similar issue while running on Ubuntu 14.04 64 bit. The error seems to be due to missing FFmeg plugin for GStreamer 0.10. This plugin is not available in the official Ubuntu 14.04 repositories.
Look at this issue. Assuming it's 14.04 64 bit, try installing the FFmeg plugin as try the code again.
sudo apt-add-repository ppa:mc3man/trusty-media

sudo apt-get update

sudo apt-get install ffmpeg gstreamer0.10-ffmpeg gstreamer0.10-fluendo-mp3 gstreamer0.10-gnonlin gstreamer0.10-plugins-bad-multiverse gstreamer0.10-plugins-bad gstreamer0.10-plugins-ugly totem-plugins-extra gstreamer-tools ubuntu-restricted-extras libxine1-ffmpeg gxine mencoder mpeg2dec vorbis-tools id3v2 mpg321 mpg123 libflac++6 totem-mozilla icedax tagtool easytag id3tool lame nautilus-script-audio-convert libmad0 libjpeg-progs flac faac faad sox ffmpeg2theora libmpeg2-4 uudeview flac libmpeg3-1 mpeg3-utils mpegdemux liba52-0.7.4-dev libquicktime2


text:
Q: Loading Mask orientation I have posted the similar question in :
sencha touch forum
But no answer yet :(
I'm facing orientation problem in the loading mask when I rotate my device to landscape (from portrait). It doesn't recalculate its position to fullscreen. I'm using Galaxy Tab for running my application.
Here is the screenshot :

I don't know whether it is some kind of sencha bug or not..
Could someone help me out of this case?
Thanks in advance

A: I have not tested this, but I hope this will help.
Either
listeners : {
    orientationchange : function(context, orientation, width,height) {
        mask.hide();
        mask.show();
    }
}

Or
listeners : {
    orientationchange : function(context, orientation, width,height) {
        panel.docomponentlayout();
    }
}


text:
Q: Linear Algebra - change of basis matrix - quick method In the class, the instructor supplied the following exercise:
Given the following vectors:
$$
\begin{align}
\psi_1(x) &= \frac{1}{\sqrt 2} \\
\psi_2(x) &= \sqrt{\frac{3}{2}} \cdot x \\
\varphi_1(x) &= \frac{\sqrt 3}{2} \cdot x + \frac{1}{2} \\
\varphi_2(x) &= \frac{\sqrt 3}{2} \cdot x - \frac{1}{2}
\end{align}
$$
Then $(\psi_1, \psi_2)$ and $(\varphi_1, \varphi_2)$ form a basis.
Find a matrix which converts a vector $\begin{pmatrix} c_1 \\ c_2 \end{pmatrix}_{\psi}$ in base $\psi$ to a vector $\begin{pmatrix} d_1 \\ d_2 \end{pmatrix}_{\varphi}$ in base $\varphi$.

The solution according to the instructor:
The instructor guessed the following:
$$
\begin{align}
\varphi_1(x) &= \frac{1}{\sqrt 2} \cdot \big(\; \psi_1(x) + \psi_2(x) \;\big) \\
\varphi_1(x) &= \frac{1}{\sqrt 2} \cdot \big( -\psi_1(x) + \psi_2(x) \;\big)
\end{align}
$$
So the required matrix $P$ is:
$$
P = \begin{pmatrix}
1 & 1\\
-1 & 1\\
\end{pmatrix} \cdot \frac{1}{\sqrt 2}
$$
and the conversion is done as follows: $\vec d = P \cdot \vec c$.
Or, when elaborating:
$$
\begin{pmatrix} d_1 \\ d_2 \end{pmatrix} =
\begin{pmatrix}
\frac{1}{\sqrt 2} & \frac{1}{\sqrt 2}\\
-\frac{1}{\sqrt 2} & \frac{1}{\sqrt 2}\\
\end{pmatrix}
\cdot
\begin{pmatrix} c_1 \\ c_2 \end{pmatrix}
$$
Now, this guess seems easy. But I'm having difficulties with:

*

*How did he know that he needs to find $\varphi_i$ as a linear combination of $\psi_i$ in order to find the matrix in question?

*What should I do if guessing isn't as easy as in the example?
Solve it using the standard method of $P = M_\varphi^E M_E^\psi $ ? ($E$ is standard basis ; $E = (1, x)$)
It takes precious time. Isn't there a quicker method?

Edit:
I solved it as follows:
$$
P = M_\varphi^E \cdot M_E^\psi \equiv P_\varphi^\psi
$$
when:

*

*The basis in the subscript is the range, and the basis in the superscript is the domain

*Matrix M is a also a change of basis matrix (identity map $Id$)

*E is standard basis

Therefore, according to the definition of change-of-basis matrix:
$$
P_\varphi^\psi = \begin{pmatrix}
 | & | \\
 [\psi_1]_\varphi & [\psi_2]_\varphi \\
 | & | \\
\end{pmatrix} = \begin{pmatrix}
\lambda_1 & \lambda_3 \\
\lambda_2 & \lambda_4 \\
\end{pmatrix}
$$
Now, according to the definition of coordinate vector:
$$
\begin{align*}
& [\psi_1]_\varphi =
\begin{pmatrix} \lambda_1 \\ \lambda_2 \end{pmatrix} =
\lambda_1 \cdot \varphi_1 + \lambda_2 \cdot \varphi_2 \\
&
[\psi_2]_\varphi =
\begin{pmatrix} \lambda_3 \\ \lambda_4 \end{pmatrix} =
\lambda_3 \cdot \varphi_1 + \lambda_4 \cdot \varphi_2
\\
\end{align*}
$$
According to all the actions that I did until now - we know that we need to find $\psi$ as a function of $\phi$ - which is the opposite of what the instructor did.
Let's solve the above equations:
$$
\begin{align*}
 \left[ \frac{1}{\sqrt 2} \right]_\varphi &=  \frac{1}{\sqrt 2} \cdot (\varphi_1 - \varphi_2) \\
 \left[ \sqrt{\frac{3}{2}} \cdot x \right]_\varphi &=  \frac{1}{\sqrt 2} \cdot (\varphi_1 + \varphi_2)
\end{align*}
$$
$$
\Longrightarrow P_\varphi^\psi = \begin{pmatrix}
 1 & 1 \\
 -1 & 1 \\
\end{pmatrix} \cdot \frac{1}{\sqrt 2}
$$
Which is exactly the same matrix that the instructor received. He told me that there's symmetry because that the matrix is a Unitary operator. When I showed this (my solution) to the instructor, he said that I mixed the positions of the bases vectors, so I got a wrong result. But again I don't understand what's wrong - everything is done that same as I did in Linear Algebra course.

A: For your first question, it looks like the instructor worked this problem "backwards," but got off easy because of the properties of the resulting transformation. He found $[\phi_1]_\psi$ and $[\phi_2]_\psi$ (whether by experience, guesswork, or having done this example dozens of times before) instead of $[\psi_1]_\phi$ and $[\psi_2]_\phi$ as one might have expected. The matrix $P_\psi^\phi=\left[[\phi_1]_\psi\;[\phi_2]_\psi\right]$ needs to be inverted to get the required change-of-basis matrix, but because $P_\psi^\phi$ is both unitary and conformal, $P_\phi^\psi=(P_\psi^\phi)^{-1}=(P_\psi^\phi)^T$, so he could simply write $[\phi_1]_\psi$ and $[\phi_2]_\psi$ as the rows of the change-of basis matrix.
As for your second question, I have to echo Bye_World's comment. Sometimes, you can just eyeball a solution, sometimes there are other shortcuts you can take, but sometimes you just have to grind through the algebra. Experience in working through such problems will let you develop your own shortcuts.
It shouldn't be all that time-consuming for problems like this, though. You're simply solving the system $$\begin{align}
\psi_1 &= a_{11}\phi_1+a_{21}\phi_2 \\
\psi_2 &= a_{11}\phi_1+a_{22}\phi_2
\end{align}$$ whatever those two bases might be. For that matter, using the "standard method" here doesn't require all that much work and pretty much no thought: plug in the vectors, invert one of matrices, then multiply them together.

A: Using the "standard method:" $$
M_E^\psi=\pmatrix{\frac1{\sqrt2} & 0 \\ 0 & \sqrt\frac32} \\
M_\varphi^E=\pmatrix{\frac12 & -\frac12 \\ \frac{\sqrt3}2 & \frac{\sqrt3}2}^{-1}=\pmatrix{1 & \frac1{\sqrt3} \\ -1 & \frac1{\sqrt3}} \\
M_\varphi^E M_E^\psi = \pmatrix{1 & \frac1{\sqrt3} \\ -1 & \frac1{\sqrt3}}\pmatrix{\frac1{\sqrt2} & 0 \\ 0 & \sqrt\frac32}=\pmatrix{\frac1{\sqrt2} & \frac1{\sqrt2} \\ -\frac1{\sqrt2} & \frac1{\sqrt2}}.
$$


text:
Q: Is there any package in pandas to calculate mean of selected part of values of column based on other columns I am trying to calculate mean of dataframe column based on other columns , for example i have column a ,c d and column e contains value for mean. if column 'a' 6 rows have value then calculate mean of 6 rows in column e and only give one value.next check column c if have value then calculate mean corresponding value and then check column c and do same.
i tried this piece of code but its not giving my desired results
df['mean']=df['e'].rolling(window=6, min_periods=6).mean()

original dataframe:

desired output:

Sample:
df = pd.DataFrame({
         'a':[0] * 6 + [np.nan] * 13,
         'c':[np.nan] * 6 + [400] * 7+ [np.nan] * 6,
         'd':[np.nan] * 13 + [300] * 6,
         'e':[3,4,5,6,8,10,
              3,4,5,6,8,5,5
              ,4,5,6,8,10,11]
})
print (df)
      a      c      d   e
0   0.0    NaN    NaN   3
1   0.0    NaN    NaN   4
2   0.0    NaN    NaN   5
3   0.0    NaN    NaN   6
4   0.0    NaN    NaN   8
5   0.0    NaN    NaN  10
6   NaN  400.0    NaN  3
7   NaN  400.0    NaN  4
8   NaN  400.0    NaN  5
9   NaN  400.0    NaN  6
10  NaN  400.0    NaN  8
11  NaN  400.0    NaN  5
12  NaN  400.0    NaN  5
13  NaN    NaN  300.0   4
14  NaN    NaN  300.0   5
15  NaN    NaN  300.0   6
16  NaN    NaN  300.0   8
17  NaN    NaN  300.0  10
18  NaN    NaN  300.0  11

please you check first group and second group mean is same ,so in output your code will give mean of group first for second replace with NAn , but i also want mean of second group even its same

A: Use:
df = pd.DataFrame({
         'a':[np.nan] * 2 + [0]*4 + [np.nan] * 13,
         'c':[np.nan] * 6 + [400] * 7+ [np.nan] * 6,
         'd':[np.nan] * 13 + [300] * 6,
         'e':[3,4,5,6,8,10,
              11,54,56,46,95,89,45
              ,4,5,6,8,10,11]
})
#print (df)

df1 = df[['a','c','d']]
s = df1.ffill(axis=1).iloc[:, -1].fillna(-1)
#create groups by consecutive values
m = s.ne(s.shift()).cumsum()

#get means per groups with transform and set only last value of group to new column
df['mean_e'] = np.where(~m.duplicated(keep='last') & ~df1.isnull().all(axis=1),
                        df['e'].groupby(m).transform('mean'),
                        np.nan)

print (df)
      a      c      d   e     mean_e
0   NaN    NaN    NaN   3        NaN
1   NaN    NaN    NaN   4        NaN
2   0.0    NaN    NaN   5        NaN
3   0.0    NaN    NaN   6        NaN
4   0.0    NaN    NaN   8        NaN
5   0.0    NaN    NaN  10   7.250000
6   NaN  400.0    NaN  11        NaN
7   NaN  400.0    NaN  54        NaN
8   NaN  400.0    NaN  56        NaN
9   NaN  400.0    NaN  46        NaN
10  NaN  400.0    NaN  95        NaN
11  NaN  400.0    NaN  89        NaN
12  NaN  400.0    NaN  45  56.571429
13  NaN    NaN  300.0   4        NaN
14  NaN    NaN  300.0   5        NaN
15  NaN    NaN  300.0   6        NaN
16  NaN    NaN  300.0   8        NaN
17  NaN    NaN  300.0  10        NaN
18  NaN    NaN  300.0  11   7.333333


text:
Q: recover partition after reinstall windows XP My OS was infected by trojan or virus and system files are corrupted. After tried to reinstall XP several time and failed, I took out the hard drive and prepare to back up files for a clean reinstall. Then found my data partition (D:) was empty except only a pagefile.sys, but looking into property, still can see 80% of disk space used (80GB).
It seems the index or something was corrupted during rebooting "chkdsk" when doing recovery installation. I found the disk label has been changed and chkdsk was reindexing that partition. But it hang somewhere so I forced reboot the machine. Could anyone help me out how to fix this?
PS: below is message from chkdsk:
Stage(2 of 3)
Correcting error in index $0 for files 25.
Index verification completed.
Error found. CHKDFK cannot continue in read-only mode.

A: http://www.piriform.com/recuva Is a free tool made by the makers of CCleaner.
It's worth a shot and certainly doesn't cost any money.
ddrescue is another very powerful option but it's more gear toward linux professionals. It works wonders.

A: WinHex or the 'lite' variant Davory would be my tool of choice, state-of-the-art forensic utilities.
you can run Davory over the drive and see if it is able to find your files. however, you will have to purchase a license in order to recover the files.
Note: When you select the drive to scan (F9), choose the physical disk rather than the logical drive.


text:
Q: Return country name from a city one? Guys is there a way on page load grab a city name from URL and then some how return the country it belongs to?
Lets say here is my URL: site.com/sevilla_r
How can I return España on page load and show it in the page content?
P.S
If it's a country then do nothing!

A: You can use Google geocade API
Read here
For e.g. https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY
This will return Country name, postal code, lat lng etc
--EDIT--
This is how i implemented it
$url = 'https://maps.googleapis.com/maps/api/geocode/json?address=shimla&key=';

$json = file_get_contents($url);
print_r($json);


text:
Q: Create a "normal" class from class with all `static` methods Once upon a time I wrote a Singleton class. The implementation is a class consisting only of static methods - I added an exception on __init__ for illustration purposes only, I do not even have an __init__, but will need one later:
class A:
    x = 3
    def __init__(self): raise Exception('Oh no you did not!')
    @staticmethod
    def m1():
        print(A.x)
    @staticmethod
    def m2(n):
        A.y=8

Fast forward some years, and now I need to create instances of the Singleton  - please no judgement :). The requirements:

*

*I cannot forego the Singleton version. I used it too many times, so I cannot just rewrite it.

*The new class should access an object variable where the original accessed a class one

*All staticmethod decorators need to be removed

*All methods need an additional self argument.

*Need to define an __init__ method

*I do not want to copy paste and fix the paste - the class is long, and will be subject to future changes that should always apply to both versions, holding to the above requirements. As such construction of the new version should be dynamic, and rely on the original version (I already screwed myself once not thinking ahead).

Solutions may be implemented in the original class, but I think it might be impossible, so a function taking the original class and spewing out a new one would probably be the way to go:
class A:
    x = 3 #No need to touch class variable definitions.
    def __init__(self): pass #Maybe the init method will be an argument

    def m1(self):
       print(self.x)

    def m2(self,n):
       self.y = n

Any solution (hacky or not) that dynamically creates stuff is fine. I am currently looking at building this using inspect, though I am not sure it will pan out.

A: I'm not sure this is sufficient, but I think the following modification can be used both as your original singleton and as a normal class. There's a fair amount of boilerplate, but it's isolated to the class, not the code that uses the class.
class A:

    def __init__(self):
        pass

    def m1(*args):
        # A.m1() means args will be empty
        if args and isinstance(args[0], A):
            self = args[0]
        else:
            self = A

        print(self.x)

    def m2(*args):
        if isinstance(args[0], A):
            self, n = args
        else:
            self = A
            n = args[0]

        self.y = n

Essentially, you'll do the following to each method:

*

*Strip the staticmethod decorator

*Replace each method's argument list with *args

*Manually identify if the first argument (if any) is an instance of A. If it is not, set self = A, otherwise, self = args[0].

*Manually create local variables for each of the old parameters, using the appropriate element of *args based on what you find in step 3.

For example, A.m1() results in print(A.x), while a = A(); a.mi() results in print(a.x). Likewise, A.m2(8) is A.y = 8 while a.m2(8) is a.y = 8.
I would be hesitant to try to automate this further; you'll probably spend more time identifying and trying to work around corner cases than you would by updating each method manually.

A: It will be hard to convert a static singleton class where all side effects can only affect the class itself to a normal class where side effects would only affect the instance objects. But it is possible to do the opposite: convert a normal class to a singleton static class simply by making the static class own a unique instance of the normal class and delegates all its methods call and attribute accesses to it.
A metaclass could do the job. This one creates a special attribute _own to hold an instance of its model class, explicitely creates methods for it with the appropriate signature (it also keeps docstrings if any) just delegating calls to _own, and also delegates all attribute accesses to _own
import inspect

class Singletoner(type):
    def __getattr__(self, attr):           # delegates attribute accesses
        return getattr(self._own, attr)
    def __new__(cls, name, bases, namespace, **kwds):
        obj = type.__new__(cls, name, bases, namespace)
        X = kwds['model']           # the model class is expected with the model keyword
        obj._own = X()
        for name, func in inspect.getmembers(X, inspect.isfunction):
            if name != '__init__':
                _trans(name, func, obj)   # tranfers all methods other than __init__
        return obj

def _trans(name, func, clazz):
    def f(*args,**kwargs):
            return func(clazz._own, *args, **kwargs)
    sig = inspect.signature(func)   # copy signature just removing the initial param
    parameters = sig.parameters
    params = [t[1] for t in list(sig.parameters.items())[1:]]
    f.__signature__ = sig.replace(parameters = params)
    f.__doc__ = func.__doc__
    setattr(clazz, name, f)

With your example, the non singleton class would b:
class A:
    x = 3
    def __init__(self): pass
    def m1(self):
        print(self.x)
    def m2(self, n):
        self.y=n

Its singleton delegator could be declared as:
class B(metaclass=Singletoner, model=A):
    pass

You can they use it simply:
>>> B.m1()
3
>>> B.m2(6)
>>> B.x
3
>>> B.y
6
>>> import inspect
>>> print(inspect.signature(B.m2))
(n)
>>> print(inspect.signature(B.m1))
()

A: To me it seems the biggest problem is having the method call self.x instead of A.x This is gonna be a silly idea, but you said hacky fixes are okay, so could we just backup all the values for class attributes, change them to match the instance attributes, then call the staticmethod, then restore all the values? If you would allow that, something like this might work:
import types

class A:
    x=3

    def __init__(self):
        pass

    @staticmethod
    def m1():
        print(A.x)
    @staticmethod
    def m2(n):
        A.y = n

    def __getattribute__(self, name):
        Aattr = getattr(type(self),name)            # get the class attribute of the same name to see if it is a function
        if isinstance(Aattr,types.FunctionType):
            def hackyfunction(self,*args,**kwargs):
                ... # copy all previous values of A attributes, replace them with instance attributes
                returnvalue = Aattr(*args, **kwargs)
                ... # change everything back
                return returnvalue
            method = types.MethodType(hackyfunction, self)
            return method
        # now it can't be a function, so just return normally. self.name will default to A.name if there is no instance attribute
        return object.__getattribute__(self,name)

A: Thank you all for your great ideas, they helped me implement what I wanted, before I hit a duh moment:
I renamed the original class, fixed it to work normally, and created an instance of it with the same old name.
All code that imported the file used the same name as is, with no modification whatsoever. I really should have thought of this before. Seriously.

In case someone really wants the fruit of everyone's work, this is what I did using all the ideas (somewhat tested)
import inspect
import re
def method_remove_static(m,cls_name):
    source = inspect.getsourcelines(m)[0]
    for i in range(len(source)):
        if 'staticmethod' in source[i]:
            del source[i]
            break
    for j in range(i,len(source)):
        if ' def ' in source[i]:
            source[i] = source[i].replace('(','(self,',1).lstrip()
            break

    return re.sub(r'(?<!\w)%s\.'%cls_name,'self.',''.join(source))

def class_remove_indentation(cls):
    source = inspect.getsourcelines(cls)[0]
    for i in range(len(source)):
        if ' class ' in source[i]:
            source[i] = source[i].lstrip()
            break
    return ''.join(source)

def regular_var(x):
    return (not inspect.ismethod(x) and
            not inspect.isbuiltin(x) and
            not inspect.ismethoddescriptor(x) and
            not inspect.isclass(x) and
            not inspect.isfunction(x))

#MAIN FUNCTION
def class_remove_static(cls,init = None,context = {}):
    class newCls:
        if init is not None:
            __init__ = init

    #Inner classes
    for name,incls in inspect.getmembers(cls,predicate=lambda x: inspect.isclass(x)):
        if name == "__class__": continue
        exec(class_remove_indentation(incls),context)
        setattr(newCls,name,context[name])

    __init__ = init
    #static methods are listed as functions
    for name,method in inspect.getmembers(cls,predicate=inspect.isfunction):
        if name == "__init__": continue
        exec(method_remove_static(method,cls.__name__),context)
        setattr(newCls,name,context[name])

    #Class variables defined at time of call (almost)
    for name,var in inspect.getmembers(cls,predicate=regular_var):
        if (name == '__doc__'     or name == '__module__' or
            name == '__weakref__' or name =='__dict__'): continue
        setattr(newCls,name,var)

    return newCls

This literally re-compiles the source code. I am sure the regular expression sub can break some use-cases, but it worked for me. Provide your locals() as context if your class is based on variables in the module you are using this, and an optional init function that must accept at least one parameter (colloquially named self).
The is a simple search and replace, with the very un-loved exec. Use at your own discretion if you really need it.


text:
Q: Cookie length should be less then or equal to 4096 characters Chrome dev tools has started warning me that "Cookie length should be less then or equal to 4096 characters" (spelling mistake and all).
Trouble is, my cookie is only ~1100 characters.
However, and I think this may be the cause, the cookie is being set 7 times over the lifetime of the request.
So browser bug or should I hack Codeigniter to not set it 7 times?
Below is a portion of my response header (actual values replaced with random strings) :-
Set-Cookie:cms_session=B7O7MbSL5CiqAuQBFscYlVv0Pq0WIahPzJp0kYslMX4wJTK8CSNnfKMNxXGP0ItNohXwZJaFLqPYU1PgtMM4DHX0ozGvhRV4bq8BIbdj7K8E3fNz5uI5s1KZ2QINFlBVM0c4dTKC9X2rxxTIC12Zc3RytVjxOtiXgvzz2K7qcEkC0C5JUB5ATrrmYJUz5WGLmb92WjKhbXBQEd6FmVh3bzI3xaQZHW4xBDcwN7k2q5zFQKgYTA6M6mp12T6WJALnlrI6lsX4i47ALp2cWE9ING9icmC9aJ9aOdx97PlDPZ8KyGn1hfUvqJcSpUcggLf2qPUzz3ZfxYrY9E5bG35U2DwvoFNYJrtAOC1DD0BpBfIopd46sqVFdJ7kSwv5pliiDx5DixSrEyeMf6J0rv17jzIaJrljEGSJufjzuKEdnGksfa3ZK9UM82v4bP6wemcTnKOzJ2aeLfRMMwmaztmV54K7W7ZZOEHxRRkdX0ZTCVbuojFE3BJfLEJ0y761bBxNIX98ELJktvc07OaTr2HvUok6ZNSMDi6bgvIKTWxiJvmlxJRNDYY348eLcZnLeF31ZAtGcBD5lQYwvqGXV3VxkRWRLXSCx3PvWmPJcC4Riek4jyFaKIpodFx9RpcIS7ud0ZhRVsDazF0hyCgvU3b6dbR5s3JGWuwIwAx41zMdpfti8SsbwlIDQQA2C2ViDut3t1wznO5yd3mV270ESetl6w1OftI5nV2Q6GapEJkInroXzSnOYeDYYwXHvNb17OhPDw8H2lDbEsWzYymGydTISPp3kLdzqL86wGTpADK71eM2fVXiBmHpQ0bvADNlYaoWCTts65JlQorv3LpA8M7FZ6iXt0auOGpMIYFKlqf8PTisPOXW9j9TOrfZSI06MfHLoVFoa7DLZCZZHUVqckxE5MmnOUNvK5WO3IFdnJvdnLNNAE4FHSRUlJ3RmVSY2It91QZTWUUIh1Ql8otSniodLBEigv89qTMfOu4ZyLUCqvWFep0eipDMbmwz02QOwe9A8mcRrlT1p8HKHk9YJVmajDfJaYbZozZ09NM7ebtKXm9YJVvNwWQ3tJnrNNlqQH9QShyzWokfkovg3eWlupSB9l2C37HY5EIpkqHVxRPgKoQgSmM14STN; expires=Fri, 07-Apr-2017 20:20:36 GMT; Max-Age=28800; path=/
Set-Cookie:cms_session=j2LC4jd9Aklt4XXSCYFQVNNrGgKGlQb3GnoTaJQSb9b7ZIXM9nvyHFGNdsib7AcZQOnOaop7JEfHMJ15Iho9pPPFd151hMX90PI5GAQO8iWlZ5BvkHklbHyEmcV9dnRXOz3ElfD2f81esTkGBq1JHbL8JEtYctAroBrz59T6JoQPtWiTVbpMwsWqdfh065Ez5gM05BHpAurKqrnW666F6angRLpkCyjz52J8I1BcYqkCBzm7sU8NxGCKA67fGTXywNlWgiLziM7WTmhanp3NnjKsuvQDjheUJaWM6yx7HPfsqZ2INkT4tvLUBGw4hLHqHqF21TVM7RhDiCX0IBG9UiHwkYucjcfXEpyqT57YbwsOYINH3gryhxRHV8ODnWKRWguNdbZJbeh39vtL8O72uEbUW32BwUqR2DYWt5gnhoScmsOeXxO8tK58xaBxeoEdO0nvNglFFapX6DQHRQcMBSjQZoOUCAdlZCPQPtDbDX1b1COXvJU4Oju1TxEzAE2SVkxapP48qO4KUKXe2396NPqTnNUsqbbxayXjp7sMqD6idYdGTx6goV6WivGkdberAN0sYJtuBeOPazkarfV8ZlK75SLWJPFucqLsuobwjNIZPKWqwnQNEi2647nXegasuMRhk8jeLjI4HRaNgbhq8OdrdrIwW7GvJhb6qhKdpoNjrV57KDxNxTOwj4oBkn1HxU79Co0U6K6gEYVUS1lZljGtodPtdDjCIrA8N1C02wyE1V91nKJqa7jniEmT40TbS1p2Y1jiW7eyWORXEsbTFIepobeKX3JIUknhUMiCucEgRgZpdnGEfXXPlpS2goAf4eu7BTKPbNhw14jidtxbcbjJVaPXgCpYvQgAQWhEyZ8cVFDb5Ppl7cmTKqO2IwJIX2Q1CfaQoBLCocZjcMKStCcAznkJw0qE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rxWQdnaC2sX93vA8iYljNvjsiS4WLjEsWmTbhWQBcS5RuYorWLA0aJk6yXL5ADTKeoivb43Wcx2lwtdnrj7bjOvxBbI4Oxwmt7h2MNx4yylzMRHAUkDWrnfiimfvur8XobNU2AzXwm27PBLuMoR7hjh2gjsKxN6ncm45lWPQegTTnOgplVwgjgSjgcURtmKt92igb5zpJcvp54T83ZkNQbUUYNZWR6aSVkDulSP181qdEw5eskf8OfEm6Wx3sdWEt2wwzvszRdMf6DLPbNHKJTtMD1IxBcuh7kAE0fecUorAUu2BpAwVrDFN90MsKlNAtCqZOi7ebFXOKpOuh7ZHKThzv25GFyvI4DUXR5AtA9dFzMuwwlUTZjudrEsWRgI9kI2k57R8BWcbiIvR30g3uLp5DIHVRfC51sntQ6mmFqJcZXWbxFXbaQ4gmUHBRySJoGF2dObqAVD8fBkSGeOMYQ7ObuAlZY87lzh2O04wg; expires=Fri, 07-Apr-2017 20:20:36 GMT; Max-Age=28800; path=/

A: I didn't feel like hacking CI2 so I used the DB method for session handling so that it would only set the cookie once.


text:
Q: Difference between remotes/origin and origin I am working on a new repository on GitLab, however when I list the branches it shows: remotes/origin/branch1.
The times I worked with git it would show only: origin/branch1.
If I create a branch like: git checkout -b myBranch would it show like: remotes/origin/myBranch or do I have to make some kind of config before.
Sorry if it's a stupid question, I am new in this.

A: This guy is Harcourt Fenton Mudd.  Is he also Harry Mudd?
(Hint: Yes.  Yes he is.  Well, modulo whether you're into Star Trek, anyway.  Okay, that wasn't a hint.)

origin/branch1 [vs] remotes/origin/branch1

Both of these are actually abbreviations: the full spelling of this name is refs/remotes/origin/branch1.  Git lops off the refs/remotes/ part, except when—for no apparent reason1—it only lops off the refs/ part.
The full name begins with refs/.  According to the gitglossary, that makes it a ref or reference.  This is a generalization of branch names, tag names, and other such names, so that one piece of code inside Git—the reference handling code—can deal with all the different kinds of refs.  It also means that if someone hands you a full reference, you can tell what kind it is:

*

*refs/heads/name is the branch name name;

*refs/tags/name is the tag name name; and

*refs/remotes/remote/name is a two-part remote-tracking name.2
Confusingly, these two part names are made up of:

*

*a remote name, which is not a remote-tracking name; plus

*your Git's copy of some other Git's branch name, as of the last time that your Git saw their Git's branch name (and corresponding commit hash ID).

The remote in this case is origin.  A remote is a short name under which your Git can store some facts.  The primary fact stored under a remote is a URL: your Git will use this URL to contact the other Git, when you run git fetch or git push.3
What this all boils down to is that when you see refs/remotes/origin/branch1, that tells you that:

*

*your Git has, or had, a remote named origin;

*at some point, your Git called up some other Git using that name;

*at that point, their Git had a branch name, refs/heads/branch1, or branch1 for short; and

*your Git copied that branch name into your own repository, renaming it to origin/branch1 (for short) to keep it away from your branch names.  Your branch names are yours.  They are not to be messed with just because some other Git has some branch names!  The other guy using that other Git can mess with his branch names all he wants; your Git won't mess with yours just because he messed with his.

If you want to create your own branch name branch1 (full name refs/heads/branch1), you're free to do that.  If you'd like it to associate, in some way, with their branch1 (your origin/branch1), you can do that too, by setting your origin/branch1 as the upstream of your branch1.

1The command-line command that is squirrelly here is git branch: git branch lists (local) branch names and lops off refs/heads/ from each, and git branch -r lists remote-tracking names and lops off refs/remotes/ from each; but git branch -a lists both, lopping off refs/heads/ from the branch names while lopping off only refs/ from the remote-tracking names.  I have never seen anything that says why it does this.  There are probably hysterical raisins involved.
2Git documentation calls these remote-tracking branch names, but they don't act like branch names, and I find the word branch in this phrase just muddies the waters.  Calling them remote-tracking names is not much of an improvement, but it seems better.
3You can store more than one URL, if for some reason you want to git fetch from one URL and git push to a different one.  You can also store some configuration items under the remote name.  The command that manipulates remote names and their stored URLs and other data is git remote.

Summary
You've learned these technical terms:

*

*remote: a short name for a URL.  There are relatively few restrictions on these names, and they don't have a long spelling and a short one.

*branch name: a name (that keeps track of a commit ID—we didn't go into this much detail) that your own Git maintains for you, once you have your Git create it.  A branch name has a fully spelled out long form, which you can use when it's in trouble,4 the way "Harry Mudd" becomes "Harcourt Fenton Mudd" when Stella Mudd is angry with him.

*remote-tracking name: a name (that keeps track of a commit ID) that your Git copies, rather slavishly, from some other Git, but changes it around during the copying, so that it won't ever conflict with any of your branch names.

*upstream: a way to link a branch name to some other name—usually a remote-tracking name, but you can use a branch name here too—to make some things more convenient.  (We haven't gone into detail about what this makes convenient.)

4You might wonder when a branch name could possibly be in trouble.  The answer is: when it's also a tag name, or some other name.  What if you accidentally make v1 as both a tag and a branch?  There are some rules that Git uses, but they're pretty weird: the tag name often wins, but not always, and it gets confusing.  But you can just write out the full name—refs/heads/v1 or refs/tags/v1—to get around that, or use an abbreviated name, but one less abbreviated: heads/v1 or tags/v1.
(The git describe command sometimes prints out heads/name, to warn you that it's a branch name instead of a tag name.)

A: @torek has explained deeply on this. Credits to him.
If you write a command git checkout -b mybranch then it will create a new branch named mybranch in your local and it will switch to that new branch from the default branch so that you can work on that branch. Tip: The default branch is master or main branch depending upon version control application you are working on.
Now if you do git branch. It will show your local branches that comes from ref/heads reference like master and *mybranch. * indicates that your Head is pointed to that branch.
$ git branch
  *mybranch
  master

If you do git branch -r. It will show remote branches from ref/remotes.
$ git branch -r
  origin/master

For displaying the list of both local and remote branches which comes from ref/heads and ref/ reference, you need to use git branch -a.
$ git branch -a
  *mybranch
  master
  remote/origin/master

If you want to push the newly created branch into the remote repo.
git push origin mybranch

If you working alone then you need to first check out to master branch then merge it with the newly created branch to the master branch by
git checkout master
git merge mybranch

If you are working in a team then you need to do the pull request so that everyone in your team knows that you have pushed your new branch and requires the approval of the team member to merge the branch to the master branch.


text:
Q: Algorithm to find maximum coverage of non-overlapping sequences. (I.e., the Weighted Interval Scheduling Prob.) I have a question that is very similar to algorithm to find longest non-overlapping sequences.
The only difference to the linked question is that instead of finding the set of non-overlapping tuples that represent the longest sequence, I need to find the set of non-overlapping tuples that represent the maximum coverage, by which I mean the sum of the tuple lengths is maximum (a tuple length being last - first + 1 given the definition of tuple in the next sentence).
I represent my tuples differently than the linked problem.  Instead of (starting index, length), I represent my tuples as (first, last); for example, the tuple (3,7) represents the set of numbers [3, 4, 5, 6, 7].  (A tuple overlaps another tuple even if the end-points match; i.e., (2,6) and (6,8) overlap and therefore cannot both appear in the solution.)
As an example, consider the following set of tuples, sorted by first:
[(0,100), (2,50), (30,150), (60,95), (110,190), (120,150), (191,200)]
The maximal set here would be [(0,100), (110,190), (191,200)] with a coverage of 101 + 81 + 10 = 192.  (Note that the tuples in this solution are non-overlapping.)
What is an example of the least complex algorithm to solve this, and what is the complexity of that algorithm?  (It would be just great if this could be solved in O(N), but I don't know at the moment if it can be.)
ADDENDUM: In retrospect, it turns out that the question I am asking here is equivalent to the weighted interval scheduling problem.  This is a special case of the interval scheduling problem.
@j_random_hacker's answer, below, is, in fact, the known solution to the weighted interval scheduling problem, with a complexity in time of O(N log(N)).

A: Here is an O(nlog n)-time, O(n)-space algorithm.  First, sort the array of tuples by their starting position if they are not already in this order.  I'll assume zero-based array indices.
Let's call the beginning position of tuple i b(i) and the ending position e(i), so that its total length is e(i) - b(i) + 1.  Also let's define a function next(i) that returns the position within the tuple list of the first tuple that can appear to the right-hand side of tuple i.  Notice that next(i) can be calculated in O(log n) time with a binary search: just keep all the tuple beginning positions b(i) in an array b[], and search for the first j in the subarray b[i+1 .. n-1] having b[j] > e(i).
Let's define f(i) to be the maximum coverage of any nonoverlapping set of tuples that begins at or after tuple i.  Since tuple i itself is either in this optimal set or not, we have:
f(i) = max(e(i) - b(i) + 1 + f(next(i)), f(i+1)) for 0 <= i < n

We also have the boundary condition f(n) = 0.
Clearly the largest possible coverage is given by f(0).  This is easily calculated.  In pseudo-C++:
int b[] = /* Tuple beginning positions, in nondecreasing order */;
int e[] = /* Tuple end positions */;
int n = /* Number of tuples */;

// Find the array position of the leftmost tuple that begins to the right of
// where tuple i ends.
int next(int i) {
    return upper_bound(b + i + 1, b + n, e[i]);
}

int maxCov[n + 1];    // In practice you should dynamically allocate this

// After running this, maxCov[i] will contain the maximum coverage of any
// nonoverlapping subset of the set of n - i tuples whose beginning positions
// are given by b[i .. n-1] and whose ending points are given by e[i .. n-1].
// In particular, maxCov[0] will be the maximum coverage of the entire set.
void calc() {
    maxCov[n] = 0;
    for (int i = n - 1; i >= 0; --i) {
        maxCov[i] = max(e[i] - b[i] + 1 + maxCov[next(i)], maxCov[i + 1]);
    }
}

The loop in calc() runs n times, and each iteration makes one O(log n) call to the binary search function upper_bound().
We can reconstruct an actual set of this size by calculating both the inputs to max() for f(0), seeing which one actually produced the maximum, recording whether it implies the presence or absence of tuple 0, and then recursing to handle the remainder (corresponding to either f(next(0)) or f(1)).  (If both inputs are equal then there are multiple optimal solutions and we can follow either one.)

A: The algorithm below works by recursively retrieving the largest non-overlapping set that each element is the leftmost member of and then returning the one with the largest coverage. See comments in the code.
Implemented in PHP. You can test it here http://viper-7.com/xowTRF
I think this algorithm's complexity is O(2^N) or O(N^2) with caching, feel free to leave a comment if you disagree.
$set = [[0,100], [2,50], [30,150], [60,95], [110,190], [120,150], [191,200]];
$GLOBALS['cache'] = array(); //cache for overlapping sub problems

function maximumSet($set) {

    if(count($set) === 1) {
        return $set;
    }

    $cache_key = [];

    foreach($set as $k) {
        $cache_key[] = implode($k,'.');
    }

    $cache_key = implode('_',$cache_key);

    if(isset($GLOBALS['cache'][$cache_key])) {
        return $GLOBALS['cache'][$cache_key];
    }

    $maximumResult = null;

    //for each element in the set,
    //get the largest non-overlapping set that the element is a member of
    //once all N sets have been computed, return the largest one
    foreach($set as $k => $element) {

        unset($set[$k]);

        //create a new set $copy, which contains the remaining elements that
        //do not overlap with $element
        $copy = $set;

        foreach($set as $k2 => $element2) {
            if($element2[0] <= $element[1]) {
                //element is considered non overlapping if its start
                //is less than or equal to current element's end
                unset($copy[$k2]);
            }
            else break; //because the list is sorted we can break the 1st time
            //see a non-overlapping element
        }

        if(!empty($copy)) {
            //if there is at least one non-overlapping element
            //recursively get the maximum set
            $maximumSubset = maximumSet($copy);
            //prepend the current element to it
            array_unshift($maximumSubset,$element);
        }
        else {
            //otherwise the maximum non-overlapping set which contains this element
            //is the element itself
            $maximumSubset = [$element];
        }

        //store the set in the results by coverage
        $coverage = getCoverage($maximumSubset);
        if(is_null($maximumResult) || $maximumResult['coverage'] < $coverage) {
            $maximumResult = [
                'coverage' => $coverage,
                'set' => $maximumSubset
            ];
        }
    }

    $GLOBALS['cache'][$cache_key] = $maximumResult['set'];
    return $maximumResult['set'];
}

function getCoverage($set) {
    $range = 0;
    foreach($set as $v) {
        $range += ($v[1] - $v[0]);
    }
    return $range;
}

$x = maximumSet($set);
print "<pre>";
print_r($x);
print "</pre>";


text:
Q: How to send out of turn messages and replies in bot builder framework 4.0 I am (on external events) posting messages to my microsoft team channel.
var activity = new Activity("message", text: $"", attachments: new List<Microsoft.Bot.Schema.Attachment>
    {
        new Microsoft.Bot.Schema.Attachment{ ContentType = "application/vnd.microsoft.card.adaptive" , Content= new JRaw(json)}
    });
var a = await connector.Conversations.SendToConversationAsync("hardcoded channel string, cant find it anywhere",
    activity);

Which works, the adaptive card is shown in my channel.
I now want to follow up with an reply to this activity later.
 var b = await connector.Conversations.ReplyToActivityAsync("same channel id hardcoded", a.Id, new Activity("message", text: "user disconected",replyToId : a.Id));

but the message is not shown as a reply but instead just a new message in the channel.
The id returned from response of SendToConversationAsync, do not look like an activity id, so how do i get the activity id such i can reply to it properly.
The connectorClient is created like:
var connector = new ConnectorClient(new Uri("https://smba.trafficmanager.net/emea/"), appCredentials);

A: Have a look at this sample to see how to send proactive messages in BotBuilder V4: https://github.com/Microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/16.proactive-messages
Of particular interest should be the CompleteJobAsync method:
// Sends a proactive message to the user.
private async Task CompleteJobAsync(
    BotAdapter adapter,
    string botId,
    JobLog.JobData jobInfo,
    CancellationToken cancellationToken = default(CancellationToken))
{
    await adapter.ContinueConversationAsync(botId, jobInfo.Conversation, CreateCallback(jobInfo), cancellationToken);
}

From this we can see that the trick is to use BotAdapter.ContinueConversationAsync
I've tested this in Teams and found that it will live up to its name by continuing the conversation rather than starting a new one.

EDIT: I now understand that you meant to ask something more like this question: Microsoft Bot Connector - get activity id from response after sending message
That is to say, you understand that in a Microsoft Teams team channel, all activities will share the same "root" conversation ID that looks like this: 19:ad2f5f5a246241718826833354894656@thread.skype
And each "thread" will have its own conversation ID that consists of the root ID plus the message ID that started the thread: 19:ad2f5f5a246241718826833354894656@thread.skype;messageid=1545970892795
So if you want to start a new thread then you can send a message to the root conversation ID and if you want to reply to a thread then you can send a message to the thread's conversation ID. In this regard, there's no difference between SendToConversationAsync and ReplyToActivityAsync because, despite appearances, Teams doesn't "nest" messages under other messages. Instead, each message chain is identified by its own conversation ID.
So in order to send a message to a thread, you've discovered that you need to know the ID of the message that started the thread. Unfortunately, the ID returned by SendToConversationAsync and ReplyToActivityAsync is in a different form from the one you need. After extensive testing I've discovered that Teams seems to have two forms of message ID:

*

*Epoch timestamps (1545970800530)

*

*Used as the activity ID in messages sent to the bot

*Used as part of a conversation ID to define a thread (19:ad2f5f5a246241718826833354894656@thread.skype;messageid=1545970892795)

*Alphanumeric codes (1:1zDTpbvf1DFFLC5cL0n72d-wPdIIV2L6L5LZ5H_nzqhs)

*

*Returned as HTTP content from calls to the REST API

*Used for updating and presumably for deleting activities

So are you out of luck? Not at all! It turns out that if you create the thread with CreateConversationAsync then it will return the thread's conversation ID which you can use for your replies. Here is an extension class to make it easy for you:
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Connector.Teams.Models;
using Microsoft.Bot.Schema;

namespace Microsoft.Bot.Connector.Teams
{
    public static class TeamsExtensions
    {
        public static async Task<ConversationResourceResponse> CreateTeamsThreadAsync(
            this ITurnContext turnContext,
            Activity activity,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var connectorClient = turnContext.TurnState.Get<IConnectorClient>() as ConnectorClient;
            activity.ChannelData = turnContext.Activity.ChannelData;

            return await connectorClient.Conversations.CreateTeamsThreadAsync(turnContext.Activity.Conversation.Id, activity, cancellationToken);
        }

        public static async Task<ConversationResourceResponse> CreateTeamsThreadAsync(
            this IConversations conversations,
            string conversationId,
            Activity activity,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var channelData = activity.GetChannelData<TeamsChannelData>();

            var parameters = new ConversationParameters
            {
                ChannelData = new TeamsChannelData
                {
                    Channel = channelData.Channel,
                    Team = channelData.Team,
                    Tenant = channelData.Tenant,
                },
                Activity = activity,
            };

            return await conversations.CreateConversationAsync(parameters, cancellationToken);
        }
    }
}

Since I saw that you already have a ConnectorClient and a conversation ID I made a method that uses those. You can also call the method that extends ITurnContext if you're want to create a thread in response to a message from a user. All you have to do is save the Id value of the ConversationResourceResponse that the method returns so you can use it for your proactive messages.


text:
Q: Calculating standard deviation on data stored in a cell array of cell arrays I have a cell array A Mx3 in size where each entry contains a further cell-array Nx1 in size, for example when M=9 and N=5:

All data contained within in any given cell array is in vector format and of equal length. For example, A{1,1} contains 5 vectors 1x93 in size whilst A{1,2} contains 5 vectors 1x100 in size:

I wish to carry out this procedure on each of the 27 cells:
B = transpose(cell2mat(A{1,1}));
B = sort(B);
C = std(B,0,2);  %Calculate standard deviation

Ultimately, the desired outcome would be, for the above example, 27 columns (9x3) containing the standard deviation results (padded with 0 or NaNs to handle differing lengths) printed in the order A{1,1}, A{1,2}, A{1,3}, A{2,1}, A{2,2}, A{2,3} and so forth.
I can do this by wrapping the above code into a loop to iterate over each one of the 27 cells in the correct order however, I was wondering if there was a clever cellfun or more succinct method to accomplish this particularly without the use of a loop?

A: You should probably realize that cellfun is essentially a glorified for loop over cells.  There's simply extra error checking and all that to ensure that the whole thing works.  In any case, yes it's possible to do what you're asking in a single cellfun call.  Note that I am simply going to apply the same logic as you would have in a for loop with cellfun.  Also note that because you're using cell arrays, you have no choice but to iterate over the entire master cell array.  However, what you'll want to do is pad each resulting column vector in each output in the final cell array so that they all share the same length.  We can do that with another two cellfun calls - one to determine the largest vector length and another to perform the padding operation.
Something like this could work:
% Step #1 - Sort the vectors in each cell array, then find row-wise std
B = cellfun(@(x) std(sort(cell2mat(x).'), 0, 2), A, 'un', 0);

% Step #2 - Determine the largest length vector and pad
sizes = cellfun(@numel, B);
B = cellfun(@(x) [x; nan(max(sizes(:)) - numel(x), 1)], B, 'un', 0);

The first line of code takes each element in A, converts each cell element into a N x 5 column matrix (i.e. cell2mat(x).'), we then sort each column individually with sort, then take the standard deviation row-wise.  Because the output is ultimately a vector, we must make sure that the 'UniformOutput' flag is 0, or 'un=0'.  Once we complete the standard deviation calculation, we determine the total number of elements for each resulting column vector for all cell elements, determine the largest size then use another cellfun call to pad these vectors so they all match the same size.
To finally get your desired output, you need to transpose the cell array, then unroll the elements in column major order.  Remember that MATLAB accesses things in column major, so a common trick to get things in row-major (what you want) as opposed to column major is to first transpose, then unroll in column-major fashion to perform a row-major readout.  Doing this in one line is tricky, so you'll need to not only transpose the cell array, you must use reshape to ensure that the elements are read out in row major format, but then ensuring that the result is placed in a row of cells, then call cell2mat so you can piece these vectors together. The final result should be a 27 column matrix where we have pieced all of these vectors together in a single row-wise fashion:
C = cell2mat(reshape(B.', 1, []));


text:
Q: Jira API with python returns error 401 on valid credentials I am trying to use the Jira python library to do some quite basic things.
Even before doing anything, the constructor fails.
address = 'https://myaddress.atlassian.net'
options = {'server': address}
un = 'my@user.com'
#un = 'my' #also doesn't work
pw = 'the_pasSword!'
cookie = (un, pw)

j = JIRA(options, basic_auth=cookie)

This is ALL the code.
The last line fails with

WARNING:root:Got recoverable error from GET
https://myaddress.atlassian.net/rest/api/2/serverInfo, will retry [1/3]
in 13.906688704524315s. Err: 401
WARNING:root:Got recoverable error
from GET https://myaddress.atlassian.net/rest/api/2/serverInfo, will
retry [2/3] in 4.071181495745648s. Err: 401
WARNING:root:Got
recoverable error from GET
https://myaddress.atlassian.net/rest/api/2/serverInfo, will retry [3/3]
in 6.266303262421157s. Err: 401

Trying the credentials manually on atlassian do work, and I am able to log in.
Any idea why this very straightforward attempt to connect wouldn't work?

A: They have been discussing deprecating passwords in basic auth. Try generating an API token and using that in replacement of your password.
https://developer.atlassian.com/cloud/jira/platform/deprecation-notice-basic-auth-and-cookie-based-auth/
address = 'https://myaddress.atlassian.net'
options = {'server': address}
un = 'my@user.com'
#un = 'my' #also doesn't work
token = 'the_tokEn'
cookie = (un, token)

j = JIRA(options, basic_auth=cookie)

A: Please try this code:
from jira.client import JIRA
import logging
import getpass
import datetime
import os

# Clearing the screen
os.system('cls||clear')
# Getting user authentication data
print 'Please enter your authentication data'
USER = raw_input('Username: ')
PASSWORD = getpass.getpass('Password: ')
print
JIRA_URL = "YOUR_JIRA_URL"
i = datetime.datetime.now()
TODAY = ("%s/%s/%s" % (i.day, i.month, i.year) )

def connect_jira(log, jira_server, jira_user, jira_password):
    '''
    Connects to JIRA

    Returns None on error
    '''
    try:
        log.info("Connecting to JIRA: %s" % jira_server)
        jira_options = {'server': jira_server}
        jira = JIRA(options=jira_options, basic_auth=(jira_user, jira_password))
                                        # ^--- Note the tuple
        return jira
    except Exception,e:
        log.error("Failed to connect to JIRA: %s" % e)
        return e

# Creating logger
log = logging.getLogger(__name__)
# Creating a Jira connection object, jc
jc = connect_jira(log, JIRA_URL, USER, PASSWORD)


text:
Q: How to catch when a selector is passed to jQuery() that does not exist in document, to stop further possible errors or omissions? Given

$(function() {
  $(".planChoice").on("click", function() {
    console.log(123)
  });

  console.log($(".planChoice").length)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

jQuery happilly allows chaining .on() to jQuery() call where selector passed to jQuery() does not exist in document. Where .addEventListener() throws a TypeError

Cannot read property 'addEventListenet' of null

$(function() {
  document.querySelector(".planChoice")
  .addEventListener("click", function() {
    console.log(123)
  });

  console.log(document.querySelector(".planChoice").length)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

How can we adjust (improve) jQuery() to throw the same TypeError when the selector or element does not exist in document at the time jQuery() is called and, or a jQuery method is chained to the jQuery() call which returns a jQuery object - though no underlying element exists matching the selector string within document at the time of the call?

A: If you really want to throw an error, you can edit jQuery() / $

$ = function (selector, context) {
    var el = new jQuery.fn.init(selector, context);
    if (el.length === 0) throw new Error('fail : "' + selector + '" Not Found');
    return el;
}

$('body'); // okay, returns element

$('nosuchthing'); // fail, throws error
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Another way would be to just return null or undefined instead of an empty collection, and let the next function chained on throw the error

$ = function (selector, context) {
  var el = new jQuery.fn.init(selector, context);
    if (el.length === 0) return null;
    return el;
}

$('body').on('click', function() {}) // hunkydory
$('nosuchthing').on('click', function() {}) // can't read property "on" of "null"

A: If you do want the error to be thrown, just use the vanilla javascript instead of the jquery function.


text:
Q: How to get the contents between nested tags in java html parser? Eg. Consider the html
<html>
<body>
<p> Hello <b> world </b> </p>
</body>
</html>
how can i get the content "Hello" while parsing?
Please help me. I need it in java. I'm aware of few html parsers like jehrico.

A: The method handleText() will give you that.


text:
Q: How to reading an XML by its element id's? This is my current XML file it gives me the dialogue for different characters, or at least it should. I want it to work so that I can specify the entity id and the option/quest id and get the output. So what should I do? Any help is appreciated, thank you very much.
<?xml version="1.0"?>
<dialoge>
<entity id="1"> <!-- questgiver -->
    <quest id="1">
        <option id="1">
            <precondition>player has not started quest</precondition>
            <output>hello there, can you kill 2 enemies for me?</output>
        </option>
        <option id="2">
            <precondition>player has completed quest and player has not...</precondition>
            <output>thankyou, have a sword for your troubles.</output>
        </option>
        <option id="3">
            <precondition>player has not finished quest</precondition>
            <output>you haven't finished yet.</output>
        </option>
        <option id="4">
            <outpur>thank you.</outpur>
        </option>
    </quest>
</entity>
<entity id="2"> <!-- villager -->
    <option id="1">
        <precondition>village is being destroyed</precondition>
        <output>our village is being destroyed, please help us!</output>
    </option>
    <option id="2">
        <precondition>village has been saved or destroyed</precondition>
        <output>we will never forget this.</output>
    </option>
    <option id="3">
        <output>hello.</output>
    </option>
</entity>
</dialoge>

This is what I currently have, but it does not work. I know this is probably a stupid question, but I couldn't find an answer anywhere on the web. Thanks.
public static void read() {
    try {
        File file = new File("text.xml");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(file);
        doc.getDocumentElement().normalize();

        System.out.println("root of xml file " + doc.getDocumentElement().getNodeName());
        NodeList nodes = doc.getElementsByTagName("entity");
        System.out.println("==========================");

        for(int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if(node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                        if(element.getElementsByTagName("entity").item(0).getTextContent().equals("output")) {

                }
                System.out.println("" + getValue("output", element));
            }
        }
    }catch(Exception e) {
        e.printStackTrace();
    }
}

private static String getValue(String tag, Element element) {
    NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
    Node node = (Node) nodes.item(0);
    return node.getNodeValue();
}

A: Simplest method might be to use XPath...
try {
    File file = new File("text.xml");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();

    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression xExpress = xpath.compile("//*[@id='1']");
    NodeList nl = (NodeList) xExpress.evaluate(doc, XPathConstants.NODESET);
    System.out.println("Found " + nl.getLength() + " matches");
} catch (Exception e) {
    e.printStackTrace();
}

The xpath query //*[@id='1'] will find all nodes in the document which have the attribute id with a value of 1
Have a look at WC3 XPath Tutorial and How XPath works for more details about XPath

A: In general, DOM is easier to use but has an overhead of parsing the entire XML before you can start using it where as SAX parser is parsing the XML, and encounters a tag starting (e.g. <something>), then it triggers the startElement event (actual name of event might differ). read more..
See Java Tutorial on Parsing an XML File Using SAX
Here is the sample code:
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class GetElementAttributesInSAXXMLParsing extends DefaultHandler {

    public static void main(String[] args) throws Exception {
        DefaultHandler handler = new GetElementAttributesInSAXXMLParsing();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(false);
        SAXParser parser = factory.newSAXParser();
        parser.parse(new File("text.xml"), handler);
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes)
            throws SAXException {

        System.out.println("Tag Name:"+qName);
        // get the number of attributes in the list
        int length = attributes.getLength();

        // process each attribute
        for (int i = 0; i < length; i++) {

            // get qualified (prefixed) name by index
            String name = attributes.getQName(i);
            System.out.println("Attribute Name:" + name);

            // get attribute's value by index.
            String value = attributes.getValue(i);
            System.out.println("Attribute Value:" + value);
        }
    }
}


text:
Q: How to check if column added in SELECT is null, if yes -> don't print this I am trying to print BMI values of players who are overweight or underweight. If a player doesn't have any problems then I don't want to print this row. I set null to column "Problems_with_weight" if a player is OK.
I have already tried to declare new column as PROBLEMS_WITH_WEIGHT, and then check in WHERE statement: WHERE PROBLEMS_WITH_WEIGHT IS NOT NULL, but it says, it doesn't know what PROBLEMS_WITH_WEIGHT are
SELECT p.name, p.surename, p.weight * 10000.00 / (p.height*p.height)  as BMI,
CASE
    WHEN p.weight * 10000.00 / (p.height*p.height) <= 18.5 **THEN** 'OVERWEIGHT'
    WHEN p.weight * 10000.00 / (p.height*p.height) >= 25 **THEN** 'UNDERWEIGHT'
    ELSE NULL
END AS PROBLEMS_WITH_WEIGHT
FROM PLAYERS p
ORDER BY BMI DESC

A: You can use a WHERE clause to filter out players that do not have BMI problems.
Also, the BMI calculation could be moved to a subquery, to avoid repeating the computation.
Finally the « ELSE NULL » branch in the case is superfluous, since CASE returns NULL  by default when no branch matches (which will not happen in this query anyway because of the newly added WHERE clause).
Query :
SELECT
    p.*,
    CASE
        WHEN p.bmi <= 18.5 THEN 'OVERWEIGHT'
        WHEN p.bmi >= 25 THEN 'UNDERWEIGHT'
    END AS PROBLEMS_WITH_WEIGHT
FROM (
    SELECT
        name,
        surname,
        weight * 10000.00 / (height*height) bmi
    FROM players
) p
WHERE p.bmi <= 18.5 OR p.bmi >= 25
ORDER BY p.bmi DESC

A: You may use auto-computed columns. Also it would make sense to calculate BMI value only once and do not recalculate it again and again (3 times per every rows in your query).

*

*https://firebirdsql.org/refdocs/langrefupd25-intfunc-decode.html

*https://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl-tbl.html#fblangref25-ddl-tbl-alter

*https://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl-tbl.html#fblangref25-ddl-tbl-computedby

*https://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl-trgr.html

*https://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl-idx.html
So, step by step:
alter PROBLEMS_WITH_WEIGHT add BMI float

Then
create trigger materialize_BMI
active before update or insert on PROBLEMS_WITH_WEIGHT
as begin
  NEW.BMI = NEW.weight * 10000.00 / (NEW.height*NEW.height) ;
end

Now for every new or modified row you would have BMI calculated and stored. You can initialize the column by pretending a table-wide update: UPDATE PROBLEMS_WITH_WEIGHT set BMI = BMI
Then
alter PROBLEMS_WITH_WEIGHT add BMI_STATUS computed by
  ( DECODE( BMI <= 18.5, 'UNDERWEIGHT' ,
            BMI >= 25,   'OVERWEIGHT'  )
  )

Then you would have two options.
Lazy one - full table scan:
Select * from PROBLEMS_WITH_WEIGHT where BMI_STATUS is not NULL

Verbose (thus, prone to typos) but potentially faster one:
Create index IDX_BMI_PROBLEMS on PROBLEMS_WITH_WEIGHT(BMI);

Then
Select * from PROBLEMS_WITH_WEIGHT where BMI <= 18.5
  UNION ALL
Select * from PROBLEMS_WITH_WEIGHT where BMI > 25


text:
Q: REST: Resource in wrong state -- Which HTTP status should I return? Assume my server exposes resources wich have a state (Not approved, Approved, Auto-approved). If a resource is in state Not approved it should not be accesible to clients, i.e. clients are allowed to know about the existence of the resource (they do anyway) but should be denied access until the resource is in the correct state.
The HTTP status code should express something along the lines: "Yes, the resource you are trying to access exists, but you will have to wait until it's approved by someone. Please try again later."
What HTTP status code should be returned in this case? Returning 404 (Not found) doesn't seem right, because the resource is in fact existing. Status code 412 (Precondition failed) sounds about right, but the RFC talks a lot about HTTP headers...

The 412 (Precondition Failed) status code indicates that one or more
conditions given in the request header fields evaluated to false when
tested on the server.  This response code allows the client to place
preconditions on the current resource state (its current
representations and metadata) and, thus, prevent the request method
from being applied if the target resource is in an unexpected state.

A: The conditions mentioned in the descriptions refer to HTTP headers like If-Match, If-Modified-Since, If-None-Match, If-Range or If-Unmodified-Since so the use of 412 would not be appropriate in your case.
I think it's up to your interpretation if Not approved resources are simply unavailable 404, restricted to certain users 403 or locked 423.
I'd say in your case 423 (Locked) (until approval) would be the correct response.


text:
Q: How to render clickable urls using react-json-to-table? i'm new to coding and i'm building a web app using reactjs. i need to render a widget that contains a table to display data that comes from the back-end in json format. The table will change dynamically over time and will always be different.
I found a library that could work for me :
https://github.com/thehyve/react-json-to-table
It works like wonders, but i can't render clickable urls in the tables.
Someone can help me archieve this?
i have some data like this:
{
    "Loaded by": "Jills",
    "Load id": 34,
    "git id": "xxqaygqertqsg98qhpughqer",
    "Analysis Id": "7asdlnagsd98gfaqsgf",
    "Load Date": "July 12, 2018",
    "Data Source": "Study XY123-456",
    "Jira Ticket": "Foo-1",
    "Confluence URL": "http://myserver/wxyz"
  }

the my component looks like this:
export default class TableWidget  extends BaseWidget {

constructor(props) {
    super(props);
    const { data } = this.props;
    const data2 = data;

    this.state = {
      data: this.getData(data2)
    };

    this.handleResize = this.handleResize.bind(this);
}

componentWillMount() {
    super.componentWillMount();
    this.props.socket.on(`widget:update:${this.props.jobName}:${this.props.name}`, datas => {
      logger('info', `updating widget: ${this.props.jobName}:${this.props.name}`, datas);
      this.setState({
        data: this.getData(datas.value),
      });
    });
}

getData(data) {

  const demoJson = {
    "Loaded by": "Jills",
    "Load id": 34,
    "git id": "xxqaygqertqsg98qhpughqer",
    "Analysis Id": "7asdlnagsd98gfaqsgf",
    "Load Date": "July 12, 2018",
    "Data Source": "Study XY123-456",
    "Jira Ticket": "Foo-1",
    "Confluence URL": "http://myserver/wxyz"
  };

  if (data == null )
    return demoJson;
  else
    return data;
}

  static get layout() {
return {
  x: 0,
  y: 0,
  w: 4,
  h: 3,
  minH: 3,
  maxH: 40,
  minW: 4,
  maxW: 10,
};
  }

  static get className() {
    return 'TableWidget';
}

  handleResize() {
this.chart.reflow();
  }

render() {

    const classList = classNames(...this.classList, 'widget', 'widget__table',);
    return (

{this.props.title}

        <JsonToTable json={this.state.data} />

    );
}

}

 TableWidget.propTypes = {
title: PropTypes.string.isRequired,
  };

the table renders fine but i want to be albe to clikc on the "conference url". how can i archieve this?
maybe I could use one of these two libraries?
https://github.com/arqex/react-json-table
or
https://github.com/agracio/ts-react-json-table
thanks for the help and sorry if i made some English or code abominations.


text:
Q: Caracter ' dentro de una cadena de caracteres estoy armando un CASE en oracle pero no logro dar con el resultado correcto.
Ejemplo:
CASE
WHEN COLLECTION_ZONE = 'Rancagua' THEN 'REGION DE O'HIGGINS'
ELSE NULL
END AS REGION

En la parte de REGION DE O'HIGGINS ese ' corta la cadena hasta O' y HIGGINS no lo considera...

A: Se usan dos single quote para que se entienda como single quote en un string, por lo que veo en internet
WHEN COLLECTION_ZONE = 'Rancagua' THEN 'REGION DE O''HIGGINS'
ELSE NULL
END AS REGION

https://stackoverflow.com/questions/11315340/pl-sql-how-to-escape-single-quote-in-a-string/11315369


text:
Q: EXCEL VLOOKUP - Extracting multiple columns from one formula I'm trying to use a VLOOKUP array formula to extract and display multiple columns using one formula.
Excel Formula:
=VLOOKUP(A15,A1:G9,{3,4,5},FALSE)
  1                      2             3          4        5          6
Transaction ID      Payment Date    Product    Quantity   Cost       Sales
MVLN195             1/3/2014        Trash Can   1         $14.00     $14.00
XFYR246             1/4/2014        Lawnmower   1         $599.00    $599.00
DWDF167             1/4/2014        Diapers     1         $29.00     $29.00
YNBM339             1/5/2014        Sweater     3         $59.00     $177.00
WTKQ758             1/7/2014        Bike        1         $599.00    $599.00
SFKS527             1/7/2014        Radio       1         $25.00     $25.00
OGWT288             1/8/2014        Bike        1         $599.00    $599.00
TCQN516             1/9/2014        Calender    5         $3.00      $15.00

  1        2         3         4
ID       Product   Quantity   Cost
OGWT288  Bike      #N/A       #N/A

I've tried using the array vlookup formula, but only column 3 comes up. I've tried to press ctrl shift enter as well but still only data from column is pulled not for the other two.
If anyone could be of any assistance would be very helpful.
Thank You

A: Put this in the first cell and drag over:
=VLOOKUP($A$15,$A$1:$G$9,COLUMN(C:C),FALSE)

If you really want to array enter then you can use your formula:

*

*Select B15:D15 with B15 active.

*Enter the formula in the formula bar.

*Hit Ctrl-Shift-Enter to array enter the formula into all three cells at same time.

A: First of all your formula is correct.
Put it in the first column, in your scenario it's A16.
And then select that cell and drag it upto the next 3 cells.
Move your mouse cursor to the top formula bar and click over, and press ctrl+shift+enter
It should work.
Thanks