text:
Q: Ubuntu Updates: How Scared Should I Be? I had an install of Ubuntu 14.04 LTS on a different machine, with Nvidia drivers manually installed. I "accepted" an automatic update and it hosed my computer, I still haven't been able to get it back working.
But no worries, I installed 14.04 on a different machine and it's (currently) working fine. But 48 hours after the install I get an auto update notice. How worried should I be? The first laptop was a 2010 build, the latest one is a 2013 build. If that matters.

A: You shouldn't be that worried if you have not installed the nvidia driver on the newer computer in the same way that you did on the first one. There are a few things you should be aware of.
First:
the nvidia drivers will use dkms if it is installed when you manually install the driver. Before installing the nvidia driver, run the following command:
sudo apt-get install dkms

Then, you may install or reinstall the nvidia driver and should not have any issues updating to new kernels and will not have to reinstall the drivers after updating kernels.
Next:
you should be able to log in from grub using the old kernel. Select "Advanced Options" and then select the older kernel from the next menu. This will give you a way to use the machine until you install dkms and reinstall the driver (on the older computer).
Finally:
You can manually apply updates on any machine using the command-line and doing so will offer two options. Run the following commands in an open terminal.
Option one:
sudo apt-get update
sudo apt-get upgrade

Using the above option is safe and should not perform any updates that will break the system. This way, you can perform security updates and other bug fixes without disrupting the system. This is for when you are working on a project or using the machine for production and need to maintain function.
Option two:
sudo apt-get update
sudo apt-get dist-upgrade

This option will perform all updates including kernel upgrades and other updates that  make changes to the system and could affect the overall function. Use this when you are not in the middle of a project and have some time to fix any problems that may arise. Problems are not likely but are possible as you have found out. Also, problems are not typical. Installing dkms before manually installing nvidia should prevent future issues.


text:
Q: How to deal with Microsoft and Google agressive spam policies? Introduction:   I have run my own mail server for more than 10 years, and I never had any problem with Gmail, so far. But I needed to complain regularly (like every year) to Hotmail, because they were sending me directly to their Junk folder. So I used to fill in an online form they provided, and they removed me from their mysterious blacklist for a while (they didn't give reasons, they didn't even answer, actually).

But recently:
  A few months ago, the nightmare really began!
  I'm now going directly on SPAM/Junk folder both on Hotmail and Gmail, with
  all my domains.
  The processes to get out of this are murky.

Microsoft way:
Microsoft changed his process, the form doesn't exist any more, and you now have to apply to a SDNS/JMRP program, which doesn't really help.
I've tried to use an Hotmail account to apply to this program and guess what?
Yes, mails from snds-authorization@outlook.com landed directly in the Junk folder.
How can they help me if they reject themselves?
Google way:
Similarly, Gmail is asking you to subscribe to Postmaster Tools, which doesn't help at all because it needs you to reach a certain volume of mail I'm far from, in order to be effective.
So it's easier to avoid being rejected if you are mass-sending???
I can only access those empty interfaces, and I feel like I'm in front of a big wall.
As many already reported elsewhere, declaring the mail as "non-spam" doesn't solve the issue and the next mail still end up in junk folder (for both Microsoft and Google). Plus this is not a solution anyway.
My situation:
I always have respected every standards (SPF / SenderID, DKIM, DMARC, reverse DNS / PTR).
I DON'T use this server for mailing in batch or marketing, this is my personal mailbox and I only send (very) few messages to my legit contacts (family, friends & customers). Those contacts always expect my mails, and recently they have to check the spam folder, just for NO REASON, even when I simply answer back to mails then sent to me.
I don't send message looking like spams, I don't attach quircky PDF or such things. I don't make use of my broken English since I use my mother tong in most of those e-mails.
I'm not blacklisted anywhere, I've checked many blacklists list on the web.
I'm not a backscatter.
I'm declared OK by SenderScore.
I get 10/10 at mail-tester.
I even subscribe, few years ago to dnswl.org.
Finally, I must add I'm NOT an open relay and my server have not been hacked.
Conclusion:
I'm desperate to understand why this struggle.
I mean I understand SPAM is a big deal, but after having accumulated knowledge for years (managing Postfix can be tricky) and applied to all standards, I feel like I'm punished for not being one of the giant out there.
Am I missing something obvious?
Or do Microsoft and Google just decided to kill personal mail servers?
Please help!
BEFORE ANSWERING THIS:
I know some of you will quickly deal with that question by tagging it as duplicate. I already read about it on this very site:

*

*Mail is marked as spam although SPF and DKIM pass

*Mail marked as spam (Gmail/Hotmail): IP not on blacklist, DKIM Valid, SPF Valid and DMARC valid

*Hotmail and Gmail mark emails as spam

*Gmail and other private servers mark legitimate email as SPAM

*Mail classified as spam, but passes SPF and DKIM

*Can't deliver emails to microsoft

*How to send emails without ending up in Junk/Spam folder

*Is it becoming impossible to be a small mail provider?
All this questions ended-up unanswered or not fit with my case.
So maybe we can try to do something different here and discuss about new ideas or other places where we can actually find an effective answer.
If the answer is contact them to ask why they rejected you then it fails greatly. Because as mentioned, there isn't anywhere to get such contact.
When dealing with those giants, they don't provide a contact. They only provide their useless postmaster tools.
They even warn you they will not give reasons about why you are rejected, when you can find some other useless form to fill in the endless loop of their documentation.
So not a good answer unless one can provide a real contact entry.
Maybe someone heard about an association or some initiative to try to deal with this annoying issue or a community who is trying to force them to provide an actual way to be recognized as legit, without to pay for being whitelisted.

A: I suspect @HBruijn is right and you have some unruly neighbours, which you can't fix.  Here are some suggestions for moving forward.
Sign up to the mailop mailing list (yes, I know the cert is expired; the mailing list still works).  This is a list for mail server operators which includes representatives from the big email senders and receivers.
Lurk for a month or so, and read a few months' worth of the list archives - there are usually several threads on deliverability problems each month.  Implement the suggestions you see discussed (if you've implemented them already, double-check your configuration carefully instead), and if you don't get better results after a few weeks of running them, ask a well-researched question to the list.  Don't do this without signing up to both the Microsoft and Google sender programs, reading through all their help material, and implementing their suggestions.
For me, the answers were:

*

*implementing DMARC

*keeping the volume low and not sending large batches of email at once

If you haven't done so already, it's worth signing up to a service like dmarcian and configuring your domain to send RUA/RUF emails to them so that you can view the statistics and configuration suggestions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: kotlin string concatenation no side effect Why is string concatenation kept without side-effects?
fun main() {
    var s1 = "abc"
    val s2 = "def"
    s1.plus(s2)
    println(s1)
    // s1 = s1.plus(s2)
    // println(s1)
}

I expected abcdef, but got just abc. The commented code works fine, but seems awkward.

A: The plus() method (or the + operator, which is basically the same thing in kotlin) is returning the  concatenated string. So by calling
s1.plus(s2)
//or
s1 + s2

you concatenate these strings but you throw away the result.

A: As this answer shows. Your plus operation returns the concatenated string independent from the given strings. This is because strings are immutable in Kotlin. An alternative is to use CharLists or buffers.
Note that immutability has some serious benefits. With immutablility it is no problem to give away your references to immutable objects because nobody can change the object. You need to change the reference in your model to hold a new value. This way it helps a lot to guarantee consistency and integrity in your model. Also note that immutable objects are threadsafe for that reason.


text:
Q: Can I reduce the CPU speed of my MacBook when on battery? I've got a MacBook with a Core 2 Duo CPU. I've got CoreDuoTemp installed which can show the current speed of the CPU. It appears to always show:
Mini : 1.0 GHz
Maxi : 2.0 GHz
Current : 2.0 GHz
I believe my laptop would run longer on battery if it were to run at a maximum of 1 GHz. Is there a way to configure this, or is the CPU speed adjustment completely automatic?

A: You could try the pmset command for power-management settings:
pmset -b reduce 1

-b       for battery mode only
reduce   reduce processor speed (value = 0/1)

But I'm not sure it will have the desired effect.

A: You cannot manually limit the CPU speed to 1 GHz.
You can optimize for battery life.
Go into your System Preferences, and pick the Energy Saving Settings (the light bulb). Set the first dropdown to Battery, and the second to optimize for saving energy (my Mac is set to Dutch so I don't know the exact wording for this option in English. That should optimize your CPU settings.

A: It's not the frequency that "wastes" battery life, but the voltage. Normally higher frequencies need higher voltages - more heat is released, the fans have to work and so on.
CPUs are not the same when they come out of the factory - they all receive voltage that 99% of them work with. A percentage of them will work well with lower voltage.
Some of them are sold as ULV (Ultra Low Voltage CPUs) that are expensive to buy because they have better performance for less wattage and less impact on battery life. You have to check your particular processor.
One application that was nice for Mac OS X is CoolBook. It easily undervolts your CPU if you want the frequency.
Undervolting is safe. It's not the same with overclocking or overvolting. When you try to run with lower voltage at 2 GHz for example, you will get to a point where your computer will shut down.
So the ideal voltage will be a little higher than that point.
To give you an idea: my CPU with a nominal frequency of 2 GHz normally runs at 1.2625 V. But it actually runs well at 2 GHz with just 1.0750 V. This difference has a huge impact on battery life and heat, resulting in a lot more battery life without losing performance.
As technology evolves, the factory sweet point for the majority of CPUs is more personalized. But you can still optimize a lot!

A: Short answer: No.
The processor will automatically adjust its speed according to usage. The only way to limit the CPU speed is to remove your battery (at least on older Macbooks that works) and rely on the Magsafe, although that does defeat the purpose of what you are trying to do.

A: Even if you could, I really doubt this will help with your battery life usefully..
The CPU will throttle itself automatically, I would guess CoreDuoTemp is simply reporting the current (throttled) speed incorrectly..

A: In windows Vista/Seven you can do this. You can set minimum/maximum CPU % usage for every power scheme, plus you can set passive/active cooling method.

A: Unfortunately, on Windows 8.1 when you set up max CPU usage to 99%, the Turboboost is completely turned off on my MBA mid-2011. (And the Max frequency ends up with 1.7Ghz instead of 2.7Ghz turbo frequency).
I'd like to have 2.2Ghz or 2.0Ghz max instead of 1.7Ghz.
However, this'll reduce a lot the maximum fan speed.
Yesterday i replaced the stock thermal paste with Artic MX-4, the temps are still the same, but the fan speed was decreased. And now the thermal throttle is more difficult to get it activated.


text:
Q: Is it possible to list all branches contained in a tagged release? I need an easy way to track all branches that were part of a release back to their Jira tickets.
Our git process:

*

*Create feature branch from develop

*Create pull request to merge back into develop

*When ready for release, create release branch from develop

*Create pull request with this branch for final review to merge into master

*After merge of pull request, tag master with the release number and publish tag

Possible to get a list of all branch names that were merged between to tags?
UPDATE

This gets me the hash for each commit, but I need the branch name:
git log --pretty=oneline v2.0.0-alpha.46...v2.0.0-alpha.45

A: *

*See the local branches list that contains the tag.
$ git branch --contains <tag-name>

*See the list of branches merged with master branch.
$ git checkout master
$ git pull origin master

$ git branch --merged


text:
Q: Powershell ArrayList remove item with special characters I do this
[System.Collections.ArrayList]$packageList = (Get-ChildItem "\\path-to-files" -Filter *.zip )
Write-Host $packageList
$packageList.Remove("ABC_Export-Cars.zip")
Write-Host $packageList

Remove doesn't work with this kind of item nevertheless it's in the array.  With a simple array e.g. containing "A","B","C" it works. Are "_" or "-" characters which need a special processing?

A: The problem is that your ArrayList contains a collection of FileInfo objects returned by Get-ChildItem. So none of those items match the string you're trying to remove. Obviously when you use a collection of strings (a,b,c) then you can match a string for removal.
You probably just want the names of the files in your ArrayList, in which case do this:
[System.Collections.ArrayList]$packageList = (Get-ChildItem "\\path-to-files" -Filter *.zip).name

The .Remove operation then should work for a specified file name.

A: Mark Wragg's helpful answer explains the problem with your attempt well and offers an effective alternative based on names only.
If you had indeed wanted to collect the [System.IO.FileInfo] instances that Get-ChildItem outputs in $packageList (rather than just their .Name property values), your .Remove()-based approach couldn't have worked, because you would have had to pass the very same [System.IO.FileInfo] instance that is already a part of the array list in order to successfully remove it.
The reason is that the .Remove() method uses reference equality to find list elements that are instances of .NET reference types (the only exception being strings, which are treated like value types in this context).
That is, the argument passsed to .Remove() must be the very same object in order to be found in the list (not another object that happens to represent the same thing).
Therefore, it would have been easier to exclude the file named ABC_Export-Cars.zip file at the source:
$packageList = Get-ChildItem "\\path-to-files\*.zip" -Exclude ABC_Export-Cars.zip

Using the -Exclude parameter allows you to exclude the specific file name as part of the Get-ChildItem call; do note that the *.zip wildcard had to be made part of the (implied) -Path argument to make this work.
If excluding at the source is not an option, the alternative is to use a - slow - loop to remove the file-info object of interest:
$packageList = foreach ($file in $packageList) {
  if ($file.Name -ne 'ABC_Export-Cars.zip') {
     $_ # pass the object through
  }
}

Note that $packageList receives a newly created array ([object[]]) as a result, and that there's therefore no good reason to type $packageList as [System.Collections.ArrayList] to begin with.
A more concise - and slightly faster - alternative is to use the PSv4+ .Where() collection-filtering method:
$packageList = $packageList.Where({ $_.Name -ne 'ABC_Export-Cars.zip' })

In this case the output collection type is [System.Collections.ObjectModel.Collection[psobject]], though in most contexts it will behave like a regular array (or array list).

A: Mark Wragg has already answered your question. Just in case if you want to use Remove method, you can use the index of the required file to remove it. For example -
$packageList.Remove($packageList[n])

where n = Index of the file you want to remove


text:
Q: How to configure nginx log to file and standard output at the same time in Kubernetes Ingress? I use nginx ingress controller in Kubernetes. In this nginx ingress controller, we create soft link to /var/log/nginx/access.log and error.log for stdout and stderr. In the nginx.conf, we config the log as follow:
    access_log /var/log/nginx/access.log
    error_log /var/log/nginx/error.log

With this configuration, the log can be viewed by "kubectl logs [pod name]". Now I want to get this log to be stored as a real file not only the standard output. How to achieve that?


text:
Q: How to move table in one column in IEEE format I have this code for table. I want to put this table in one column in ieee format.
the code is given
  \documentclass{IEEEtran}

    \usepackage[margin=1in]{geometry}
    \usepackage{booktabs}
    \usepackage{makecell}% <--- added

    \begin{document}
    \begin{table*}
    \centering
    \caption{Solution with \texttt{tabular}}
    \begin{tabular}{@{} ll *{6}{c} @{}}
    \toprule
    Heading 1 & State of Health
      &\multicolumn{3}{c}{Fasting Value}
      &\multicolumn{3}{c}{After Eating}\\
    \cmidrule(lr){3-5} \cmidrule(l){6-8}
     & & \makecell{Maxxxxxxx\\xxxxxxxxxxxxxxx\\xxxxxxxxxxxxxxxxxx} & Maxxxxxxxxxxxx & lllllllllllllllllLow & 2hrs & 3hrs & 4hrs\\
    \midrule
    add & Healthy  &70 &100 &a  &$< 140$ & &\\
    \addlinespace %\midrule
    del & Pre-Diabetes &101  &126  &a & 140--200 & &\\
    \addlinespace %\midrule
    mult & Diabetes &$>126$ &N/A  &a & $>200$ & &\\
    \bottomrule
    \end{tabular}
    \end{table*}

    \end{document}

A:
\documentclass{IEEEtran}
\usepackage{tabularx,ragged2e,booktabs}
\usepackage{kantlipsum}% dummy text

\newcolumntype{C}{>{\Centering\arraybackslash}X} %
\frenchspacing
\begin{document}
1.  \kant[1]

\begin{table}[h]

\setlength{\tabcolsep}{2pt} % a bit more whitespace
\begin{tabularx}{\columnwidth}{@{} ll *{6}{C} @{}}
    \toprule
     Heading 1
        & State of Health
            &\multicolumn{3}{c}{Fasting Value}
                &\multicolumn{3}{c}{After Eating}\\
    \cmidrule(lr){3-5} \cmidrule(l){6-8}
        &
            & A
                & B
                    & C
                        & 2hrs
                            & 3hrs
                                & 4hrs\\
    \midrule
        add
            & Healthy
                &70
                    &100
                        &a
                            &$< 140$
                                & &\\
    \addlinespace %\midrule
        del
            & Pre-Diabetes
                &101
                    &126
                        &a
                            & 140--200
                                & &\\
    \addlinespace %\midrule
        mult
            & Diabetes
                &$>126$
                    &N/A
                        &a
                            & $>200$
                                & &\\
    \bottomrule
\end{tabularx}

\smallskip
A is Maxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

B is Maxxxxxxxxxxxx

C is lllllllllllllllllLow

\caption{Precision results of diabetes for various feature subsets.}
\label{table:new}
\end{table}

3.  \kant[9-10]

4.  \kant[9]

\end{document}

A: As recommended by IEEEtran, you can use the stfloats package to send the table to the top or bottom of a double column page.
TOP

BOTTOM

% !TeX TS-program = pdflatex
\documentclass{IEEEtran}

\usepackage[margin=1in]{geometry}
\usepackage{booktabs}
\usepackage{makecell}% <--- added

\usepackage{kantlipsum}% dummy text

\usepackage{stfloats}% added <<<<<<<<<<<<<<<

\begin{document}
1.  \kant[1]

2.  \kant[11]

    \begin{table*}[b] % bottom
        \centering
        \caption{Solution with \texttt{tabular}}
        \begin{tabular}{@{} ll *{6}{c} @{}}
            \toprule
            Heading 1 & State of Health
            &\multicolumn{3}{c}{Fasting Value}
            &\multicolumn{3}{c}{After Eating}\\
            \cmidrule(lr){3-5} \cmidrule(l){6-8}
            & & \makecell{Maxxxxxxx\\xxxxxxxxxxxxxxx\\xxxxxxxxxxxxxxxxxx} & Maxxxxxxxxxxxx & lllllllllllllllllLow & 2hrs & 3hrs & 4hrs\\
            \midrule
            add & Healthy  &70 &100 &a  &$< 140$ & &\\
            \addlinespace %\midrule
            del & Pre-Diabetes &101  &126  &a & 140--200 & &\\
            \addlinespace %\midrule
            mult & Diabetes &$>126$ &N/A  &a & $>200$ & &\\
            \bottomrule
        \end{tabular}
    \end{table*}
3.  \kant[9-10]

4.  \kant[9]

5.  \kant[12]
\end{document}


text:
Q: get all duplicate data on one date in one my sql I have a table  that have date and status column. multiple values of status insert on one date. I want that how many duplicate value are insert on one date.
For example:
            -------------------
            |date     | status|
            -------------------
            |2014-2-14|   1   |
            -------------------
            |2014-2-14|   1   |
            -------------------
            |2014-2-15|   0   |
            -------------------
            |2014-2-13|   2   |
            -------------------

I want flowing output
            -------------------
            |date     | total status|
            -------------------
            |2014-2-14|   2   |
            -------------------
            |2014-2-14|   1   |
            -------------------
            |2014-2-15|   1   |

A: You're expected result is weird, because there is no 2014-2-13 at all, but I guess it's just a type.
Anyway, looks like you need GROUP BY clause:
SELECT Date, COUNT(DISTINCT Status)
FROM MyTable
GROUP BY Date

It will give you number of distinct statuses added for each day. If you want to count all statuses and you don't care if they were distinct, just skip DISTINCT:
SELECT Date, COUNT(Status)
FROM MyTable
GROUP BY Date


text:
Q: vb.net retrieve items from Listview on SelectedIndexChanged I am trying to get the value from a listview in vb.net, but keep getting an error of:
'SelectedItem' is not a member of 'System.Windows.Forms.ListView'.
I think I need to change eventargs to some other event type, but am struggling with this. Could someone please point out my error. Thanks
Sub filllistview()
        Try
            'creatconn()
            cn.Open()
            Dim cmd As OleDbCommand = New OleDbCommand("Select * from Customers", cn)
            dr = cmd.ExecuteReader()
            While dr.Read()
                ListView1.Items.Add(dr(0).ToString())
                ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr(1))

            End While

        Catch ex As Exception
            System.Windows.Forms.MessageBox.Show(ex.Message)
        Finally
            dr.Close()
            cn.Close()
        End Try
    End Sub

Need to catch here
Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As EventArgs) Handles ListView1.SelectedIndexChanged
        Try
            showcontectsinlistview()
            str = ListView1.SelectedItem **<--- ERROR**

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

A: This is true beacuse it doesn't exist a "SelectedItem" property.
The ListView object has a property "SelectedItems", that is a collection. So you could use something like: listView1.SelectedItems[0].
With this you will have the first of the selected items in the collection given by the "SelectedItems" property. To navigate through all the selected items, you can loop between them in this way:
For Each itm As ListViewItem In ListView1.SelectedItems
If itm.Selected Then
    For i As Integer = 0 To itm.SubItems.Count - 1
        str += itm.SubItems(i).Text
    Next
End If
Next

In this way you build a string with all the values of all the selected items. If you have only 1 selected item in the listview, you will have only that value.

A: Look at this example
 Private Sub lstDirectoryInfo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstDirectoryInfo.SelectedIndexChanged
    Dim str As String = String.Empty

    For Each itm As ListViewItem In lstDirectoryInfo.SelectedItems
        If itm.Selected Then
            For i As Integer = 0 To itm.SubItems.Count - 1
                str = itm.SubItems(i).Text
            Next
        End If
    Next
    MessageBox.Show(str)
End Sub


text:
Q: Using GPS library in Python 3 I want to use GPS library in Python 3. I came across this on https://github.com/tpoche/gps-python3
How do I 'install' these files? Should I simple copy them to my folder? Or is there any way of installing them?

A: That project is a warts and all port of the python-gps package to Python 3.
The python-gps files live at /usr/lib/python2.7/dist-packages/gps/
You can put gps-python3 files in your Python 3 path by creating and placing them in an analogous directory, e.g., /usr/local/lib/python3.4/dist-packages/gps/   The module will then be available as it would in Python2.  There is no installer
Another option is use gps3.py.  It's still alpha, but is a fresh python client for the gpsd.  It works with any Python from 2.7 to 3.4.  It can be either placed in a directory such as /usr/local/lib/python3.4/dist-packages/gps/, placed in the directory of your python script, or executed directly via python3 /path/to/gps3.py
Your python script is easy to adapt as it uses the same name(s) as the json stream from the gpsd.
from gps3 import gps3
the_connection = gps3.GPSDSocket()
the_fix = gps3.Fix()
try:
    for new_data in the_connection:
        if new_data:
            the_fix.refresh(new_data)
        if not isinstance(the_fix.TPV['lat'], str): # lat as determinate of when data is 'valid'
            speed = the_fix.TPV['speed']
            latitude = the_fix.TPV['lat']
            longitude = the_fix.TPV['lon']
            altitude  = the_fix.TPV['alt']
            # etc....


text:
Q: Not able to center content using the Box component in MaterialUI and React I am using the Box component from MaterialUI in react and want to be able to center the child component within the page. However, I am unable to do so. I have tried all possible parameters including alignItems justifyContent etc.
This is how I export the component
export const FeaturesScroll = () => {

  return (
    <Box alignItems="center" justifyContent="center" sx={{ bgcolor: 'background.paper', maxWidth: 1200, justifyContent:'center'}}>
        <Typography variant="subtitle1">
          Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        </Typography>
    </Box>
  );
}

I am not sure what I am doing wrong. This component is being called within a div component as shown below
export const Home = () => {
  return(
    <div>
      <HeroSection/>
      <BodySection1/>
      <BodySection2/>
      <FeaturesScroll/>
    </div>
  );
};

A: you should use display:flex property for alignItems and justifyContent to work

A: Use sx={{ display: 'flex' ,justifyContent:'center',alignItems:'center'}}
you can not use alignItems and justifyContent as a prop
   <Box sx={{ display: 'flex' ,justifyContent:'center',alignItems:'center'}}>
            <Typography variant="subtitle1" style={{backgroundColor:'red'}}>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit.
            </Typography>
        </Box>


text:
Q: Unable to start/stop service from BroadcastReceiver I have an activity which starts a service. Now, i want to start/stop the service in a BroadcastReceiver which listens to screen off/on. I used:
public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        Log.d("Screen:", "In Method:  ACTION_SCREEN_OFF");
        context.stopService(new Intent(context, ScreenReceiver.class));
    }
    else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
        Log.d("Screen:", "In Method:  ACTION_USER_PRESENT");
        context.startService(new Intent(context, ScreenReceiver.class));
    }
}
}

I have added the required permissions and have registered/unregistered the BroadcastReceiver in the service. I am able to see the Log messages in Logcat when i run the code, but the service doesn't seem to stop. How should i fix it? Thanks in advance.

A: You are trying to restart your BroadcastReceiver. Use you service class instead.
context.startService(new Intent(context, ScreenReceiver.class));

should be
context.startService(new Intent(context, YourService.class));

and in your manifest file:
<service android:name=".YourService"></service>


text:
Q: xquery- how to put a 'range' condition on some nodes' immediately previous and next sibling nodes Kindly take a look at the sample below--

      First list
      Name #1
      Name #2
      Second list
      Name #2_1
      Name #2_2

Now, I want to extract the links after the 'b' element that has text "First List"-- however, I dont want the links after the 'b' element that has text "Second list"-- and the number of links after "First List" is not known to me.
What I thought of, is something like this--
....XQuery code defining the document as variable named "doc"
let $list:= $doc/div[ @class="patent_bibdata"]/b[. = 'First list']/following-sibling::text() -- but this should get everything after 'First list'-- including 'Second List' and 'Name #2_1' and 'Name #2_2'

Now, only the text in the 2 'b' tags-- (i.e. 'Name #1' and 'Name #2' in our example) are known to me-- so I think I have to somehow put conditions and retrieve the links (that I need), putting conditions on the immediate-predecessor-sibling and immediate-successor-sibling of those links--- what are the commands to put those conditions(if I am right so far)? And if I am not right, then how do I go about getting that set of links?

A: This works:
$doc/div[ @class="patent_bibdata"]/b[. = ' First list']/following-sibling::a[not(preceding-sibling::b[. = ' Second list'])]

Considering the amount of rather basic questions you asked today about XQuery it might be advisable to get a fundamental understanding about XQuery first. There are some very good books out there, I especially like the one from Priscilla Walmsley.


text:
Q: Compute sequential max value in Pandas using vectorized operations I have a dataframe that looks like this
value
 10
 20
 30
 20
 40
 35
 60
 100
 50
 45
 135

and I want to compute a column with the max value until the respective row. The final dataframe should look like this:
value   max_value
 10        10
 20        20
 30        30
 20        30
 40        40
 35        40
 60        60
 100       100
 50        100
 45        100
 135       135

I can achieve this with this iterrows loop:
max_value = df['value'].iloc[0]
for index, row_data in df.iterrows():
    if row_data['value'] > max_value:
        max_value = row_data['value']
    df.at[index, 'max_value'] = max_value

but I'm looking for an efficient way of computing this using just vectorized operations, ideally without having to compute the max for all the previous rows again, since max_value will either be the previous max_value or the value of the respective row.

A: Use DataFrame.cummax()
df['max_value'] = df['value'].cummax()

print(df)

    value  max_value
0      10         10
1      20         20
2      30         30
3      20         30
4      40         40
5      35         40
6      60         60
7     100        100
8      50        100
9      45        100
10    135        135


text:
Q: find function from graph I am asked to find an expression from the following graph
I would say the graph only has zeroes at 5 so when ${f(x) = 0, x = - 5}$
or ${k(0 -5) = -5}$
=> ${-5k = -5}$
=> ${k = 1}$
So the factors are ${x - 5}$
The text book gives the answer ${{-1\over 5} + 2x - 5}$
I have absolutely no clue where this answer came from.

A: Since the parabola  has a double zero for $x=5$, its equation has the form $y=a(x-5)^2$ .
Now we can find $a$ substituting the coordinates of the given point $(0,-5)$ that gives
$$
-5=a\times 5^2 \Rightarrow a=-\frac{1}{5}
$$
and the equation is $t=-\frac{1}{5}(x-5)^2$


text:
Q: Critical points of a function and discontinuity I just wanted to ask, why does the following function:
$$f(x)=x^{1/3}(x+3)^{2/3}$$
Have 3 crtical points $0,-1,-3$, because its first derivative is:
$$f'(x)=\frac{x+1}{x^{2/3}(x+3)^{1/3}}$$
$$f'(x)=\frac{x+1}{x^{2/3}(x+3)^{1/3}}=0$$
Then $x=-1$ is the critical point as its undefined on $-3$, and $0$, so why is $-3$, and $0$ also considered a critical point$?$

A: A critical point $c$ is where $f(c)$ defined, and $f'(c)$ either zero or undefined.

A: Hint critical points any limit points where the function may be prolongated by continuity or where the derivative is not defined.
or
a critical point or stationary point of a differentiable function of a real or complex variable is any value in its domain where its derivative is 0.


text:
Q: Android WebView setEmbeddedTitleBar problem I'm trying to add a titlebar on WebView so the titlebar to be scrolled with WebView.
I used this code.
private void setEmbeddedTitleBar(WebView web, View titlebar) {
    try {
        Method m = WebView.class.getMethod("setEmbeddedTitleBar", new Class[] { View.class });
        m.invoke(web, titlebar);
    }
    catch(Exception e) {
        Log.d("TEST", "Err: "+e.toString());
    }
}

I called the method above and the titlebar seemed to be added to the corresponding webview but the titlebar doesn't show up and just white space( height of titlebar ) is upside the webview content.
My classes are 'CTitleBar' , 'CTab' and 'CWebView'.
CTab includes CWebView as a member( for one WebView per a Tab ).
And CTitleBar includes CTabs array as a member.
Prorgam operates like below.
By clicking 'add tab' button, user add a tab.
Then CTab is created with CWebView in it.
The tab is added to CTab array in CTitleBar.
( ** IMPORTANT ** ) And the CTitleBar view is added as tab.webView's titlebar.
This means.. the titlebar is referenced by it's member's member( titlebar.tab.webview ).
It seems to be a cross reference I think.
I don't know if this causes the 'white space' problem.
Or am I just using the method invocation with worng way?
How can I solve it?
Somebody help me.


text: Q: html text selection caret disappears When html element has contenteditable="true", caret is being displayed correctly but if I select any text, then caret disappears. Any idea how to display the caret right before or after the selected text.


text:
Q: Cypress use local api server maybe somebody use cypress for testing e2e flows together with backend API calls without some mocks.
I have a trouble right now, I want to use my local API from simple Laravel server like
http://127.0.0.1:8000, but all my XHR request aborted when I run tests. After some investigations I understood that if I change request baseUrl to https://example.com then requests works fine.
Example of XHR aborting
I already set chromeWebSecurity to false.
Cypress version: 4.0.2
cypress.json
{
  "viewportWidth": 1920,
  "viewportHeight": 1000,
  "baseUrl": "http://localhost:4200",
  "watchForFileChanges": false,
  "integrationFolder": "cypress/build/cypress/integration",
  "chromeWebSecurity": false,
  "blacklistHosts": [],
  "env": {
    "host": "http://localhost:4200",
    "baseUrl": "http://127.0.0.1:8000/api"
  }
}


text:
Q: Bridging entity from subtype entity ERD design I have two ERD examples involving subtypes. I cannot seem to find any definitive information online or in textbooks on connecting other entities to subtypes and how far you can inherit keys from subtypes, if at all. Those with good eyes may notice that I recently asked a similar question regarding subtypes, but it was for a different scenario and so far I only received a referral to another question that only explains the basics of subtypes which I do not need - I feel this is a more advanced topic to solve.
My specific issue is I need to know whether the Bridging entity called ENROLMENT is allowed to inherit the PK/FK from STUDENT entity, a Subtype of PATRON. If so, is PatronNumber and/or StudentNumber attributes allowed.
The two ERD examples are slightly different. Version 1 uses PatronNumber from the Subtype Student. Version 2 includes another PK called StudentNumber. Is this ok to add as a PK and can ENROLMENT reference from this? Which is better, if any?

Cheers!

A: The first version is to be preferred, for the reason that with a single value, PatronNumber, you can obtain all the information about the student with a single join, while in the second case you need to perform two joins.
Imagine, for instance, that you need to know the name of all the students that are enrolled to the course number 3: you can simply perform a join between Enrollment and Patron, while in the second case you need a join between Enrollment and Student and then between Student and Patron.
If your application requires explicitly a StudentNumber different from PatronNumber, you can simply add the attribute to the Student, and declare it unique.


text:
Q: heroku deployment issue - error: failed to push some refs to this was perfectly fine until i added a server to my cleint that was running with buildpacks mars/...
I made sure to remove all buildpacks with buildpacks:remove mars/...
I also tried heroku buildpacks:set heroku/nodejs
I also tried the git push heroku main:main
I am not sure but i think it maybe something with permissions but i may be wrong since i am new to heroku.
git push heroku main
Enumerating objects: 74, done.
Counting objects: 100% (74/74), done.
Delta compression using up to 12 threads
Compressing objects: 100% (53/53), done.
Writing objects: 100% (68/68), 290.70 KiB | 58.14 MiB/s, done.
Total 68 (delta 15), reused 62 (delta 13), pack-reused 0
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Building on the Heroku-20 stack
remote: -----> Determining which buildpack to use for this app
remote: -----> Node.js app detected
remote:
remote: -----> Creating runtime environment
remote:
remote: NPM_CONFIG_LOGLEVEL=error
remote: NODE_VERBOSE=false
remote: NODE_ENV=production
remote: NODE_MODULES_CACHE=true
remote:
remote: -----> Installing binaries
remote: engines.node (package.json): 12.16.2
remote: engines.npm (package.json): 6.14.6
remote:
remote: Resolving node version 12.16.2...
remote: Downloading and installing node 12.16.2...
remote: Bootstrapping npm 6.14.6 (replacing 6.14.4)...
remote: npm 6.14.6 installed
remote:
remote: -----> Restoring cache
remote: Cached directories were not restored due to a change in version of node, npm, yarn or stack
remote: Module installation may take longer for this build
remote:
remote: -----> Installing dependencies
remote: Installing node modules
remote:
remote: > fsevents@1.2.13 install /tmp/build_ff6289e7/node_modules/fsevents
remote: > node install.js
remote:
remote:
remote: Skipping 'fsevents' build as platform linux is not supported
remote:
remote: > nodemon@1.19.4 postinstall /tmp/build_ff6289e7/node_modules/nodemon
remote: > node bin/postinstall || exit 0
remote:
remote: Love nodemon? You can now support the project via the open collective:
remote: > https://opencollective.com/nodemon/donate
remote:
remote: added 375 packages in 6.258s
remote:
remote: -----> Build
remote: Detected both "build" and "heroku-postbuild" scripts
remote: Running heroku-postbuild
remote:
remote: > everestminds-task@1.0.0 heroku-postbuild /tmp/build_ff6289e7
remote: > cd client && npm install && npm install --only=dev --no-shrinkwrap && npm run build
remote:
remote:
remote: > node-sass@6.0.1 install /tmp/build_ff6289e7/client/node_modules/node-sass
remote: > node scripts/install.js
remote:
remote: Downloading binary from https://github.com/sass/node-sass/releases/download/v6.0.1/linux-x64-72_binding.node
remote: Download complete
remote: Binary saved to /tmp/build_ff6289e7/client/node_modules/node-sass/vendor/linux-x64-72/binding.node
remote: Caching binary to /tmp/npmcache.vnweW/node-sass/6.0.1/linux-x64-72_binding.node
remote:
remote: > core-js@3.6.5 postinstall /tmp/build_ff6289e7/client/node_modules/@firebase/polyfill/node_modules/core-js
remote: > node -e "try{require('./postinstall')}catch(e){}"
remote:
remote:
remote: > core-js@2.6.12 postinstall /tmp/build_ff6289e7/client/node_modules/babel-runtime/node_modules/core-js
remote: > node -e "try{require('./postinstall')}catch(e){}"
remote:
remote:
remote: > core-js@3.14.0 postinstall /tmp/build_ff6289e7/client/node_modules/core-js
remote: > node -e "try{require('./postinstall')}catch(e){}"
remote:
remote:
remote: > core-js-pure@3.14.0 postinstall /tmp/build_ff6289e7/client/node_modules/core-js-pure
remote: > node -e "try{require('./postinstall')}catch(e){}"
remote:
remote:
remote: > ejs@2.7.4 postinstall /tmp/build_ff6289e7/client/node_modules/ejs
remote: > node ./postinstall.js
remote:
remote:
remote: > protobufjs@6.11.2 postinstall /tmp/build_ff6289e7/client/node_modules/protobufjs
remote: > node scripts/postinstall
remote:
remote:
remote: > node-sass@6.0.1 postinstall /tmp/build_ff6289e7/client/node_modules/node-sass
remote: > node scripts/build.js
remote:
remote: Binary found at /tmp/build_ff6289e7/client/node_modules/node-sass/vendor/linux-x64-72/binding.node
remote: Testing binary
remote: Binary is fine
remote: added 2146 packages from 876 contributors and audited 2150 packages in 55.156s
remote:
remote: 151 packages are looking for funding
remote: run npm fund for details
remote:
remote: found 7 vulnerabilities (3 moderate, 4 high)
remote: run npm audit fix to fix them, or npm audit for details
remote: audited 2150 packages in 14.59s
remote:
remote: 151 packages are looking for funding
remote: run npm fund for details
remote:
remote: found 7 vulnerabilities (3 moderate, 4 high)
remote: run npm audit fix to fix them, or npm audit for details
remote:
remote: > everestminds-task@0.1.0 build /tmp/build_ff6289e7/client
remote: > react-scripts build
remote:
remote: Creating an optimized production build...
remote: Failed to compile.
remote:
remote: Can't find self.__WB_MANIFEST in your SW source.
remote:
remote:
remote: npm ERR! code ELIFECYCLE
remote: npm ERR! errno 1
remote: npm ERR! everestminds-task@0.1.0 build: react-scripts build
remote: npm ERR! Exit status 1
remote: npm ERR!
remote: npm ERR! Failed at the everestminds-task@0.1.0 build script.
remote: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
remote:
remote: npm ERR! A complete log of this run can be found in:
remote: npm ERR! /tmp/npmcache.vnweW/_logs/2021-06-27T21_07_28_897Z-debug.log
remote: npm ERR! code ELIFECYCLE
remote: npm ERR! errno 1
remote: npm ERR! everestminds-task@1.0.0 heroku-postbuild: cd client && npm install && npm install --only=dev --no-shrinkwrap && npm run build
remote: npm ERR! Exit status 1
remote: npm ERR!
remote: npm ERR! Failed at the everestminds-task@1.0.0 heroku-postbuild script.
remote: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
remote:
remote: npm ERR! A complete log of this run can be found in:
remote: npm ERR! /tmp/npmcache.vnweW/_logs/2021-06-27T21_07_28_915Z-debug.log
remote:
remote: -----> Build failed
remote:
remote: We're sorry this build is failing! You can troubleshoot common issues here:
remote: https://devcenter.heroku.com/articles/troubleshooting-node-deploys
remote:
remote: If you're stuck, please submit a ticket so we can help:
remote: https://help.heroku.com/
remote:
remote: Love,
remote: Heroku
remote:
remote: ! Push rejected, failed to compile Node.js app.
remote:
remote: ! Push failed
remote: !
remote: ! ## Warning - The same version of this code has already been built: 2c4fee55f03ca310626cd12afa9d269f1d95cc34
remote: !
remote: ! We have detected that you have triggered a build from source code with version 2c4fee55f03ca310626cd12afa9d269f1d95cc34
remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch.
remote: !
remote: ! If you are developing on a branch and deploying via git you must run:
remote: !
remote: ! git push heroku :main
remote: !
remote: ! This article goes into details on the behavior:
remote: ! https://devcenter.heroku.com/articles/duplicate-build-version
remote:
remote: Verifying deploy...
remote:
remote: ! Push rejected to everestminds-task.
remote:
To https://git.heroku.com/everestminds-task.git
! [remote rejected] main -> main (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/everestminds-task.git'

server package.json
{
  "name": "everestminds-task",
  "version": "1.0.0",
  "engines": {
    "node": "12.16.2",
    "npm": "6.14.6"
  },
  "scripts": {
    "client": "cd client && npm start",
    "server": "nodemon server.js",
    "build": "cd client && npm run build",
    "dev": "concurrently --kill-others-on-fail \"npm run server\" \"npm run client\"",
    "start": "node server.js",
    "heroku-postbuild": "cd client && npm install && npm install --only=dev --no-shrinkwrap && npm run build"
  },
  "dependencies": {
    "body-parser": "^1.18.3",
    "cors": "2.8.5",
    "dotenv": "7.0.0",
    "express": "^4.16.4",
    "stripe": "6.28.0"
  },
  "devDependencies": {
    "concurrently": "^4.0.1",
    "nodemon": "^1.19.1"
  }
}

Client package.json
{
  "name": "everestminds-task",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:5000",
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "axios": "^0.21.1",
    "express-sslify": "^1.2.0",
    "firebase": "^8.6.8",
    "node-sass": "^6.0.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-redux": "^7.2.4",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "react-stripe-checkout": "^2.6.3",
    "redux": "^4.1.0",
    "redux-logger": "^3.0.6",
    "redux-persist": "^6.0.0",
    "reselect": "^4.0.0",
    "styled-components": "^5.3.0",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

thanks for the help in advance

A: Alright, for anyone who comes across this. I found the problem, it was the serviceworker.js... it seems that "Can't find self.__WB_MANIFEST in your SW source"  has something to do with it.
create-react-app no longer comes with service-worker.js. So it maybe that I need to install a package that "swSrc" or something I am not sure yet.


text:
Q: Python Cplex Ceil() Function ceil() in the constraint
Hello, I am studying a published paper. One of the constraints from this paper(which can be shown in the link) requires the ceil() function. We can use the ceil() function at the OPL but I couldn't find the Python equality.
Notice: I tried the math.ceil() and cp.moduler ceil(), but I did not get any solution.
Edit:
I still haven't found its Python equivalent, but there is an alternative way:
slack_var = model.continuous_var(name="slack")

ceiled_var = model.integer_var(name='ceiled')

Notice: The slack variable has to be less than "1". ( 0 <= slack < 1)

ceiled_var - slack_var = "your calculations"

A: For ceil, you can use both math or numpy, however, numpy can be overkill.
import math
ceiled_variable = math.ceil(your_variable)

or
import numpy as np
ceiled_variable = np.ceil(your_variable)

A: ceil is not a linear function so you should linearize. See example here.
from docplex.mp.model import Model

mdl = Model(name='ceil')

r=range(0,4)
x=[1.5,4.0,2.0001,5.9999]

y = mdl.integer_var_list(4,0,1000,name="y")
f = mdl.continuous_var_list(4,0,0.9999999,name="f")

for i in r:
    mdl.add(y[i]==x[i]+f[i])

mdl.solve()

for i in r:
    print(x[i]," ==> ",y[i].solution_value)

"""
which gives
1.5  ==>  2.0
4.0  ==>  4.0
2.0001  ==>  3.0
5.9999  ==>  6.0
"""


text:
Q: Unable to access the site Using Alternate Name after Alternate Access Mappings My server name is "dev" and I need to change the name to access the site Locally and as well as on LAN.
I changed the alternate name by using AAM to "abc":

On the Local Server, it says This page can't be displayed if I use http://abc/ to access the site
On the Other system on the network, it says Servers IP address could not be found:
[![enter image description here][2]][2]
I have tried putting the same in Intranet,Custom, Extranet Categories but the issue is same
If I Put IP Address in place of abc, it works fine although I need to use the name to access the site instead of IP Address
Please Help

when I add 127.0.0.1 abc  in Host file, it repeatedly ask for authentication on the local machine & unable to access on LAN still

A: You haven't mentioned updating the host file on your dev machine. You need to go the sytem32\drivers\etc and update the host file with your 'abc' to machine itself.
127.0.0.1 abc

A: You may need to run the "Disable LoopBack check command" if your site is continuously asking for authentication .
Please find the reference below :-
https://social.technet.microsoft.com/wiki/contents/articles/37664.sharepoint-2013-disable-loopback-check.aspx
Let me know in case of any concerns.

A: Your DEV-Machine is not called abc. It's name is dev. So you cannot reach it with this name without workarounding configuration steps as already mentioned by others (HOSTS-File, DisableLoopbackCheck).
Why do you call this machine with abc? Configure everything with dev and you won't need any workaround.

A: To access the site from another system you will need to add a DNS entry for "ABC" to point to the dev server.


text:
Q: I m trying to use a scalar function nd want to use taht in asp.net code but i am geeting error that 'incorrect syntax near f1 ' "Function name"f sql code
create function f1( @pay float)
returns float
as
begin
return(@pay*8*10)
end

C# code
protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["abc"]);

        float a;
        SqlCommand cmd = new SqlCommand("dbo.f1",con);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@pay",TextBox1.Text);
        //cmd.Parameters.AddWithValue("@uname", TextBox2.Text);

        con.Open();
        a = (float)(cmd.ExecuteScalar());
        TextBox2.Text = System.Convert.ToString(a);
        con.Close();
    }
}

A: You Can't call a function directly in C#.
Try like this,
cmd.CommandText = "SELECT COUNT(*) FROM dbo.f1";
Int32 count = (Int32) cmd.ExecuteScalar();

Hope this helps you, Thank you.


text:
Q: gotoAndPlay not working? I am very new to AS.
I have the following code that is used to go to the next frame after a sound is completed.
stop();
invisible_btn.enabled = false;
voice = new Sound();
voice.attachSound("introVoiceOver");
voice.start();
voice.onSoundComplete = function() {gotoAndPlay(2);
                                    main.sub1.gotoAndPlay(2);};

Now instead I would like it to go to the first frame of sub2. I changed the function with:
voice.onSoundComplete = function() { main.sub2.gotoAndPlay(1);};

But after the sound is complete it just does not do anything.
anything to help please?

A: Is there a stop(); command in the first frame of your sub animation?
The code of a frame gets executed even if you say gotoAndPlay(). When your frame says stop() then it will stop there!
What you could do is:

*

*Remove the stop and handle all animation play calls from a controller/other clip

*jump to the second frame insted


text:
Q: How do you avoid memory leaks with cast::forget() in rust? There's some code in the standard library along the lines of:
/**
 * Swap the values at two mutable locations of the same type, without
 * deinitialising or copying either one.
 */
#[inline]
pub fn swap<T>(x: &mut T, y: &mut T) {
    unsafe {
        // Give ourselves some scratch space to work with
        let mut t: T = uninit();

        // Perform the swap, `&mut` pointers never alias
        ptr::copy_nonoverlapping_memory(&mut t, &*x, 1);
        ptr::copy_nonoverlapping_memory(x, &*y, 1);
        ptr::copy_nonoverlapping_memory(y, &t, 1);

        // y and t now point to the same thing, but we need to completely forget `t`
        // because it's no longer relevant.
        cast::forget(t);
    }
}

In fact, this 'create temporary scratch space and then forget it' pattern turns up several times.
According to the docs intrinsics::forget() takes ownership but doesn't destroy a value, effectively forgetting the target.
Two pretty simple questions:

*

*Why is this necessary, rather than just letting t fall out of scope and be destroyed?

*Why does forget(t) not result in a memory leak?

A: If t is permitted to fall out of scope, it will be destroyed. That is problematic if the type has a destructor with side-effects; for example, assume that we have a destructor on a file that closes the file handle contained in itself. This would mean that on a swap call, one of the file handles would be closed, which is certainly undesirable. Any ~T has a destructor also: it frees the memory. If you were to immediately run the destructor, the memory would be freed, and so you would have a use-after-free/double-free bug.
forget(t) does not of itself result in a memory leak because inside forget, it takes its parameter by value, on the stack. Thus, when it returns, the stack memory is freed. If you were to forget a ~T, that ~T would indeed leak memory; but that is not what's happening in this case at all, even if you are swapping with T as ~U, because of the semantics: t is simply scratch space; just before the cast::forget(t) call, there is actually unsoundness, because the same memory is addressed by two owned pointers; that's why one is simply forgotten without running the destructor.
The point of the matter is that forget should only be used where you are moving a value about and so something that will run its destructor does actually still exist. You shouldn't use it in any other situation, or you can leak memory.


text:
Q: Under profile on all actions, closed status isn't indicated on questions On your profile, when you go to your 'all actions', I'm trying to find certain questions which may be reopened - that is, no longer closed (cough hats cough).
Example on my profile
Several of these are closed, but you can't tell until you click them.
Almost everywhere else, it'd indicated [Closed] or [Duplicate] or whatever.
It'd be useful to get this fixed/added?


text:
Q: Understanding Arrow functions with an Example I'm having trouble understanding a solution to a coding challenge that uses arrow functions and the .every() method and was hoping someone more knowledgeable  could explain what's going on. The challenge is to check a grid to see if it represents a true sudoku board. I understand the first part concatenates and multiplies a row/col/square, but can't understand the latter part...
// True, if product of #s in row is 9!
p = a => eval(a.join("*")) == (1*2*3*4*5*6*7*8*9);

// Check each row, column and 3 block grid using p()
sudoku = grid =>
  grid.every((r,i) =>
    p(r) &&
    p(grid.map(r => r[i])) &&
    p(r.map((_,j) => grid[3*(i/3|0)+(j/3|0)][3*(i%3)+(j%3)]) ) )

Thank you for the help!

A: sudoku = grid =>
  grid.every((r,i) =>
    p(r) &&
    p(grid.map(r => r[i])) &&
    p(r.map((_,j) => grid[3*(i/3|0)+(j/3|0)][3*(i%3)+(j%3)]) ) )

*

*For every item r in grid, p(r) is evaluated. If its true then second part will be evaluated

*grid.map(r => r[i]) will be evaluated which in turn will iterate through all grid items and return an array of their ith element.
Now after if p(grid.map(r => r[i])) is true then the latter part will be evaluated.

*Finally r.map((_,j) => grid[3*(i/3|0)+(j/3|0)][3*(i%3)+(j%3)]) ) will be executed but only if previous two conditions were true.This will also return an array of grid items, depending upon values of i & j.

So key points here is the usage of &&

A && B will return B if A evaluates to true(and B will only be evaluated when A is true)

A: For the most part, an arrow function is just a function. The only real different between the two is that this is preserved from the outer context when using an arrow function, whereas this is the this that was used to call the function with a normal function.

function A() {
  this.v = 1;
  this.a = () => console.log(this.v);
  this.b = function () { console.log(this.v) };
}

// Both will use `obj` as `this`
const obj = new A();
obj.a();
obj.b();

// The arrow-function `a()` will keep the same `this` as above, `obj` will change.
const obj2 = { v: 2 };
obj2.a = obj.a;
obj2.b = obj.b;
obj2.a();
obj2.b();

The other difference which may be throwing you off, is with an arrow function, if it only needs one line, you can omit the curly brackets ({}) and it will return the value. I.e.,
a => 1

Is the same as:
function (a) { return 1; }

In this sample code, being an arrow function or a regular function would make no different, as this isn't being invoked.
What the code is doing is:
grid.every((r, i) =>

Look through every element in the grid, and keep going as long as it returns true. r is the current value of grid and i is the current index it is processing.
grid.map(r => r[i])

is literally just getting the i-th value from r and returning it. This would be for checking the diagonals of a two-dimensional array. (So it gets grid[0][0], grid[1][1], and so on).
r.map((_, j) => grid[math])

Is then just looping through each element in r, and getting some element (based on that math) using the current i index from the outer loop and the j index from r. Using _ as a parameter name is a common convention to indicate that you just don't care about that parameter.

A: Seems input data for sudoku is 2d array like this one:
let grid = [
  [2,4,1,7,6,8,5,3,9],
  [5,7,3,9,2,4,1,8,6],
  [8,9,6,5,3,1,7,4,2],
  [7,3,4,2,9,5,6,1,8],
  [1,8,9,4,7,6,3,2,5],
  [6,5,2,8,1,3,4,9,7],
  [4,6,5,3,8,2,9,7,1],
  [3,2,7,1,5,9,8,6,4],
  [9,1,8,6,4,7,2,5,3]
]

To validate Sudoku we have to check all rows, columns and sub-grids

Code explanation:
p = a => eval(a.join("*")) == (1*2*3*4*5*6*7*8*9);

This is an equivalent for
p = function(a) {
  return eval(a.join("*")) == (1*2*3*4*5*6*7*8*9);
}

So function "p" gets array of integers
[2,4,1,7,6,8,5,3,9]

joins all integers with "*" and as a result we have:
"2*4*1*7*6*8*5*3*9"

then evaluates this string and as a result we have:
362880

This is the same value as 1*2*3*4*5*6*7*8*9
So now we can check each row, each column and each sub-grid with this function.
sudoku = grid =>
  grid.every((r,i) =>
    validRows &&
    validColumns &&
    validSubGrids )

is the same as:
sudoku = function(grid) {
  grid.every( function(r, i) {
    return
      validRows &&
      validColumns &&
      validSubGrids
  })
}

The every method executes the provided callback function once for each element present in the array until it finds one where callback returns a falsy value. Otherwise it returns true.
Valid Sudoku means that our every function's callback returns true for all elements.
p(r) - validate each row
p(grid.map(r => r[i])) - validate each column
function map creates new array.
E.g. for i=0 it will provide following result:
[ grid[0][0], grid[0][1], grid[0][2],...]

p(r.map((_,j) => grid[3*(i/3|0)+(j/3|0)][3*(i%3)+(j%3)]) ) ) - validate each sub-grid
Code equivalent:
p(
  r.map( function(_,j) {
    let row = 3 * Math.floor(i/3) + Math.floor(j/3)
    let column = 3 * (i%3) + (j%3)
    return grid[row][column]
  })
)

So as a result we validated all rows, all columns and all sub-grids.


text:
Q: How to force iOS device to determine it's orientation via gyroscope? I have a situation where my app sometimes forces particular view controllers to appear in a particular orientation.
The only way I've found to do this is to set the device orientation manually, and tell the app to attempt to rotate itself like this:
switch (forceOrientation){
    case Orientations.PORTRAIT:
        let value = UIInterfaceOrientation.portrait.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
        UIViewController.attemptRotationToDeviceOrientation()
    case Orientations.LANDSCAPE:
        let value = UIInterfaceOrientation.landscapeLeft.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
        UIViewController.attemptRotationToDeviceOrientation()
    default:
        break
}

This works just fine.  However, once I close this view controller, and go back to the previous one I am still in the forced orientation regardless of how the device is being held.  Is there a way to set the orientation value to 'dirty' or something and have it auto detect?
I have tried setting the orientation value to UIInterfaceOrientation.unknown.rawValue and then attempt rotation, but this doesn't work.
I am using swift 4.1
-- Edit --
To clarify what I'm doing a bit more:
When my view controller is created, it sets itself to be the root view controller (so that it's rotation settings will actually work, otherwise the root behaviour is what's used)  At some point during it's initialization, it can be told that it should be oriented in a particular way.  If so, then it does the above code, and also set's it's orientation mask appropriately.  I am using these overrides:
public override var shouldAutorotate: Bool{
    return allowOrientationChange // this is set at some point after initializing
}

public override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return orientationMask // this defaults to orientationMaskAll but is overridden
}

When closing the view controller, the previous root controller is added back in as the root.  (But it is still rotated to whatever was forced, and does not update unless you move the device around)

A: You can override var supportedInterfaceOrientations: UIInterfaceOrientationMask { get } and set it up in a way that returns the available orientations you want at any given time.
Basically, have this property return a variable that correlates with your forceOrientation enum.
See https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations for details.
To force a rotation, you could do:
let previousOrientation = UIDevice.current.orientation
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
//Rotates all view controllers
UIViewController.attemptRotationToDeviceOrientation()

//Find all UIViewControllers that need to be locked,  I recommend using a protocol

guard let appDelegate = UIApplication.sharedApplication().delegate,
      let window = appDelegate.window,
      let root = window.rootViewController,

else{
    fatalError("error")
}
var viewControllers : [UIViewController] = []()
if root.presentedViewController != nil {
    viewControllers += [root.presentedViewController]
}
viewControllers += root.children
viewControllers.filter{$0 as OrientationLocked}.forEach{ vc in
  vc.orientationMask = ... //whatever previousOrientation isn't
}

//undo rotation
UIDevice.current.setValue(previousOrientation, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()

//View controllers that had been filtered are now rotated, where as anything underneath were treated as if a rotation did not happen

...
    any view controller that can be locked, needs this protocol
protocol OrientationLocked {
    var orientationMask : UIInterfaceOrientationMask
}


text:
Q: Как написать таймер запуска кода Python Нужно, чтобы код запускался ежедневно в одно и тоже время.
Если делать через sleep(86400) после того как код отработал, то время запуска будет постоянно смещаться. Кто знает, как это можно реализовать?


text:
Q: Can I get a unit test coverage report specificly for a user story? We are using cobertura to show our unit test coverage, we have only just started using it (Im new to running this team) and our current unit test coverage is very low, rather than just go in and find areas where we need to get this coverage up I want to start it off by enforcing that all new user stories have over 80% coverage.
cobertura can show me the unit test coverage on areas affected by that user story but as far as I am aware it cant show me what the actual unit test coverage is for that story.
Bear in mind I come from a QA background, I have managed development teams a few times but dont have the actual coding experience.
thanks

A: Since user stories don't map directly to code (there will be many parts of the code shared between stories, and often the code for a user story is distributed throughout the application), this is generally impossible.

A: This is the traditional distinction between line coverage and functional coverage. It is interesting to achieve a high line coverage (your target of 80% seems like a good starting point), but this is not enough: what matters is functional coverage, and there is no automated tool that will properly measure that.
For more details, please see my answer here, which covers that.

A: Yes you can get code coverage specific to user story but I do not think that there is any out of the box solution available.
You can find code changed for a user story from SCM repository commits and map it to code coverage tool output to find the percentage of code covered for your user story.


text:
Q: How to loop over through columns of a table and based on the column name, I want to fetch values based on the column name from other table Table 1
| Id | ProductName | Is_JAipur | Is_Rajasthan | Is_Nagpur |
|----|-------------|-----------|--------------|-----------|
|  1 |         101 |         0 |            1 |         0 |
|  2 |         102 |         0 |            0 |         1 |

Table 2
| Id |      Name |
|----|-----------|
|  1 |    Jaipur |
|  2 | Rajasthan |
|  3 |    Nagpur |

Table 3
| Id | Product | City |
|----|---------|------|
|  1 |     101 |    2 |
|  2 |     102 |    3 |

I want to write a query to get the Id from table 2 while looping through table 1 column. and insert in table 3. I want to keep this dynamic since city may increase in the future.

A: I've already mentioned the required change in your table design. Unless you adopt this you will face bigger problems in future.
Nevertheless, I am giving you the solution on your current requirement:
INSERT INTO your_table_3(Product,City)

SELECT
t.ProductName,
your_table_2.Id
FROM
(
    SELECT
    ProductName,
    CASE WHEN is_JAipur = 1 THEN 'Jaipur'
             WHEN Is_Rajasthan = 1 THEN 'Rajasthan'
             WHEN Is_Nagpur = 1 THEN 'Nagpur' END AS cityName
    FROM your_table_1
) AS t
INNER JOIN your_table_2 ON t.cityName = your_table_2.`Name`

WORKING DEMO


text:
Q: redhat 7 + How to stop systemctl service permanent we are install some service on redhat 7
but for now we no need the service application anymore
is it possible to disable the start of the service?
I not mean to disable it on the next reboot
what we mean is to avoid starting the service , in spite service installed

A: There is also a stronger version of the disable command, which is mask. From the manual:

mask UNIT…
Mask one or more units, as specified on the command line. This will link these unit files to /dev/null, making it impossible to start
  them. This is a stronger version of disable, since it prohibits all
  kinds of activation of the unit, including enablement and manual
  activation. Use this option with care. This honors the --runtime
  option to only mask temporarily until the next reboot of the system.
  The --now option may be used to ensure that the units are also
  stopped. This command expects valid unit names only, it does not
  accept unit file paths.

While systemctl disable unit would prevent a unit from starting on the next boot, you could still start the unit manually. systemctl mask unit prevents the unit from being started either automatically or manually. It does so by overriding the unit file with a symlink to /dev/null.
Finally, the command to reverse the effects of mask is unmask: systemctl unmask unit.

A: systemctl disable servicename.
Running systemctl disable removes the symlink to the service in /etc/systemd/system/*.
From now on, that service won't start on boot anymore.


text:
Q: Не работает Visual Studio При установке Visual Studio Community (которая бесплатная) появляется ошибка "сбой пакета" у NuGet, Connected Services и пр (скриншот прилагается). При попытке запуска пишет об ошибке при запуске приложения (0xc000007b), скриншот тоже есть. Windows 7, x64, свежеустановленный.

A: Простые варианты решения проблемы:

*

*Отключить антивирусы

*Отключить EDP

*Запустить в режиме совместимости с другой платформой и правами администратор

*Удалить и установить другую версию приложения


text:
Q: Does Tailwind CSS work with express sendFile? I am trying to send a html file through express but it is not able to include tailwindcss
I did all the set up correctly (at least that's what I think)
Is sendFile not capable of sending tailwindcss
This is the express setup
// express setup
const app = express();
const port = 9000;
app.use('/static', express.static('static'))

the endpoint
app.get("/", (req, res)=>{
    res.sendFile(path.join(__dirname, "/template/home.html"))
});

html file
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Website</title>
    <link rel="stylesheet" href="../static/output.css" />

Doesn't Works

css file
@tailwind base;
@tailwind components;
@tailwind utilities;

tailwind config file
module.exports = {
  content: ["*"],
  theme: {
    extend: {},
  },
  plugins: [],
}

and yes the path are correct it works with normal css but not with tailwindcss
I also don't want to use pug for it
Is there a way around it?

A: You can simple Use the Play CDN to try Tailwind right in the browser without any build step.

Add the Play CDN script tag to the  of your HTML file, and
start using Tailwind's utility classes to style your content.

But remember :

The Play CDN is designed for development purposes only, and is not the
best choice for production.

Folder & file structure :

app.js
const express = require("express");
const path = require("path");
const app = express();
const port = 9000;

app.use(express.static("./public"));

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "/public/home.html"));
});

app.listen(port, () => {
  console.log(`Server is  listening at http://localhost:${port}`);
});

home.html
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Express & TailwindCss</title>

        Express with TailwindCss

It does works! ;-)

Output :


text:
Q: NHibernate Criteria.AddOrder(Order.Asc("Column.Property")) I have an OrderEntity that has a property OrderStatistics that has a property CreateDate. It looks like Order.OrderStatistics.CreateDate.
I will like to fetch all orders and sort them by CreateDate.

*

*fetchQuery.UnderlyingCriteria.AddOrder(Order.Asc("OrderStatistics.CreateDate")) does not wokr

*fetchQuery.UnderlyingCriteria.AddOrder(Order.Asc("CreatorName")) works
How can I make 1 work ?
Thank you,

A: fetchQuery
    .UnderlyingCriteria
    .CreateAlias("OrderStatistics", "stats")
    .AddOrder(Order.Asc("stats.CreateDate"))

Or
OrderStatistic stats = null;
fetchQuery
    .CreateAlias(order => order.OrderStatistics, () => stats)
    .OrderBy(() => stats.CreateDate);


text:
Q: Как отсортировать входные данные Входные данные:
4

200 50
203 50
202 50
300 65

На выходе должно получится
300 65
200 50
202 50
203 50

Мой ответ
300 65
200 50
203 50
202 50

Итог я смог сделать сортировку по баллам но как сделать по номеру?
def M(m):
  for b in m:
    print (*b)
N = int(input())
if N >=1 and N <= 1000:
  NM = []
  for i in range(N):
    NM.append(list(map(int, input().split())))
NM.sort(key = lambda x: x[1], reverse=True)
M(NM)
def M(m):
  for b in m:
    print(*b)

A: Сейчас у вас сортируется только по второму элементу, т.е. по баллам, а номер никак не учитывается.
Нужно добавить номеру в ключ вторым элементом в кортеж, так при равных баллах, сортировка будет делаться по номеру. Чтоб это делалось в порядке возрастания, нужно номер добавлять со знаком минус, так как для сортировки по баллам по убыванию используется reverse=True:
...
NM.sort(key = lambda x: (x[1], -x[0]), reverse=True)
...


text:
Q: Count the no. of non empty nodeset in XSLT 1.0 There are 24 rows returned by my dataview webpart. There's a column called NoExperience which has a number type. For some rows, it has value for NoExperience and some rows don't contain value for NoExperience. I only need to count the number in NoExperience column that would indicate total # of non empty value for that column. Sort of COUNTA function in Excel.
I m using xsl 1.0.
Any help?Below is my line of code. This always return 24. There are 10 non empty values for NoExperience column. I need to find that number.
<xsl:value-of select="count(/dsQueryResponse/Rows/Row/@NoExperience)" />

In XPAth builder the value of @NoExperience shows like this:
; ; ; ; ; ; ; 6; 6; ; 6; ; ; ; 6; ; 7; 7; ; ; 9; 9; 9; 9;
There are 10 non empty values.

A: Presumably the "empty" case has <Row NoExperience=""> rather than the attribute not being there at all, so you need something like
<xsl:value-of select="count(/dsQueryResponse/Rows/Row/@NoExperience[string(.)])" />

as a non empty string value will act as a true predicate.


text:
Q: Serve static files based on dynamic URLs with Flask+Nginx? In Flask, if you place a file in a directory called static/, then any URL of the form http://localhost/static/foo.jpg will serve that file from static/foo.jpg.
This can also be accomplished via an nginx config:
    location /static {
        alias    /var/www/mywebsite/static;
    }

However, I want to do dynamic URL rewriting.
If someone requests the URL http://localhost/username/foo.jpg, I want to tell nginx to fetch the static file from an arbitrary URL, say, /var/www/assets/11235/1bcd5.jpg. I want the user to see a pretty url, and I want the location to be transparent to the user.
Is there an easy way to do this? Ideally, I would be able to do something so that nginx serves the file. However, if Flask needs to serve it, then that is fine too (it isn't like my project has any users yet!)
What am I missing here?

A: If the files can be stored with the names that are directly referenced in the "pretty" URL, then you can do a simple rewrite in nginx.
However, it appears that you want to map URL path info to other representations on the disk, as in username -> 11235 and foo.jpg -> 1bcd5.jpg. If the content being served should be protected by authentication or sessions, then you should probably keep the mapping and rewriting inside your Flask app, since Flask provides the means to do that.
If the content can be treated as public and only needs the mapping done, then nginx can be configured to grab query string parameters, look them up in a datastore, and rewrite the URL.
Here's an example from agentzh that was originally posted on the nginx mailing list:
Consider you seo uri is /baz, the true uri is /foo/bar. And I have the
following table in my local mysql "test" database:
create table my_url_map(id serial, url text, seo_url);
insert into my_url_map(url, seo_url)values('/foo/bar', '/baz');

And I build my nginx 0.8.41 this way:
./configure \
--add-module=/path/to/ngx_devel_kit \
--add-module=/path/to/set-misc-nginx-module \
--add-module=/path/to/ngx_http_auth_request_module-0.2 \
--add-module=/path/to/echo-nginx-module \
--add-module=/path/to/lua-nginx-module \
--add-module=/path/to/drizzle-nginx-module \
--add-module=/path/to/rds-json-nginx-module

Also, I have lua 5.1.4 and the lua-yajl library installed to my system.
And here's the central part in my nginx.conf:
upstream backend {
    drizzle_server 127.0.0.1:3306 dbname=test
    password=some_pass user=monty protocol=mysql;
    drizzle_keepalive max=300 mode=single overflow=ignore;
}

lua_package_cpath '/path/to/your/lua/yajl/library/?.so';

server {
    ...

    location /conv-mysql {
        internal;
        set_quote_sql_str $seo_uri $query_string; # to prevent sql injection
        drizzle_query "select url from my_url_map where seo_url=$seo_uri";
        drizzle_pass backend;
        rds_json on;
    }

    location /conv-uid {
        internal;
        content_by_lua_file 'html/foo.lua';
    }

    location /jump {
        internal;
        rewrite ^ $query_string? redirect;
    }

    # your SEO uri
    location /baz {
        set $my_uri $uri;
        auth_request /conv-uid;

        echo_exec /jump $my_uri;
    }
}

Contents of foo.lua, the essential glue:
local yajl = require('yajl')
local seo_uri = ngx.var.my_uri
local res = ngx.location.capture('/conv-mysql?' .. seo_uri)
if (res.status ~= ngx.HTTP_OK) then
ngx.throw_error(res.status)
end
res = yajl.to_value(res.body)
if (not res or not res[1] or not res[1].url) then
ngx.throw_error(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
ngx.var.my_uri = res[1].url;

Then let's access /baz from the client side:
$ curl -i localhost:1984/baz
HTTP/1.1 302 Moved Temporarily
Server: nginx/0.8.41 (without pool)
Date: Tue, 24 Aug 2010 03:28:42 GMT
Content-Type: text/html
Content-Length: 176
Location: http://localhost:1984/foo/bar
Connection: keep-alive

<title>302 Found</title>

302 Found

nginx/0.8.41 (without pool)


text:
Q: Reading project parameters in Script Task This is what I'm trying to do in a script task:
long lngMaxRowsToPull = Convert.ToInt64(Dts.Variables["Project::MaxRowsPerPull"].Value);

I get an error message that the variable does not exist.
Yet Its defined as a ReadOnlyVariable to the script and it does exist as a project parameter.

A: So close. ;)
Your code is trying to access a variable/parameter named Project::MaxRowsPerPull
In fact, the $ is significant so you need to reference $Project::MaxRowsPerPull
Also note that you have the data type for the parameter as Int32 but are then pushing it into Int64. You can always put a smaller type into a larger container but if you tried to fill the parameter with too large a value your package will asplode.

A: You need to add $ to your parameter fetch name as per syntax.
long lngMaxRowsToPull = Convert.ToInt64(Dts.Variables["$Project::MaxRowsPerPull"].Value);


text:
Q: How do I replace or override or fix the node error "missing script build" when deploying my application to Firebase? I'm trying to deploy my project to firebase through node.js which I just downloaded but I am getting an error.
It says npm ERR! missing script: build
I already checked my package.json file and there is no build reference inside of there. I tried putting one in and that didn't work either. I am at an impasse. :(
Does anyone know how to fix this?
Package.json file
 {
 "name": "functions",
 "description": "Cloud Functions for Firebase",
 "scripts": {
"build:production": "node --8.9.1",
"serve": "firebase serve --only functions",
"shell": "firebase experimental:functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
 },
 "dependencies": {
"firebase-admin": "~5.4.2",
"firebase-functions": "^0.7.1"
 },
 "private": true
 }

Firebase.json
 {
 "functions": {
 "predeploy": "npm --prefix functions run build",
 "source": "functions"
 }
 }


text:
Q: AC Tacho used for speed measurement I have a task where I want to measure a 24Vdc motor's rotational speed using an AC tacho attached to the same shaft of the motor. When running the motor at full speed, the tacho generates around 9Vac at a max frequency of around 1kHz. So I was going to feed this through a precision rectifier and ADC to sample the digital value with MCU but this got me thinking:
If I am only interested in measuring the speed of the motor, do I only need to measure the frequency of the tacho signal? I don't think I need a rectifier and could use a zero crossing detector and counter to calculate RPM?
Or is it more complex and does the voltage magnitude have to be considered too as this changes with frequency?
How is this achieved in current technology?
EDIT
I have measured the AC tacho signal. At full speed it generates around 8.6Vac at a max frequency of 900Hz. When turned slowly by hand it produces approx 150mV at around 25Hz although I won't be running the motor this slowly so I suspect the low end voltage to be at least 0.5V to 1V.
EDIT 2
I am thinking of using an op amp comparator to convert the positive half of the AC tacho waveform to a square wave signal. So the square wave is high during positive cycle, and low during negative cycle.
I am thinking of measuring the time between the pulses to calculate the motor's rpm. I want to use a 16 bit counter that starts counting on the rising edge of the square wave pulse and capture the counter value during the next rising edge. How can I convert this counter value from 0 to 32768 to an rpm range from 0 to 4000?
Thanks for your help everyone!

A:
If I am only interested in measuring the speed of the motor, do I only
need to measure the frequency of the tacho signal?

Yes, this will provide a more secure method for inferring speed but, at low speeds the voltage level p-p may be a tad low to adequately detect frequency unless you have provided a signal stage that uses (say) a comparator with a little bit of hysteresis. (or maybe some form of automated gain method).

I don't think I need a rectifier and could use a zero crossing
detector and counter to calculate RPM?

I would recommend that you look at the output on an oscilloscope before making this judgement. You may need to jump through a couple of small hoops at low frequencies and only the visual display will tell you that.


text:
Q: Are these line codes the same in golang? Is A same as B?
A
if err := json.NewDecoder(r.Body).Decode(&t); err != nil {
    rnd.JSON(w, http.StatusProcessing, err)
    return
}

B
err := json.NewDecoder(r.Body).Decode(&t);
if err != nil {
    rnd.JSON(w, http.StatusProcessing, err)
    return
}

A: They are equivalent except one difference: the scope of the err variable. In the A version the scope of the err variable is the if statement: it's not accessible after the if.
In the B version the err variable will be in scope after the if statement too, and if err is already defined earlier, it could result in a compile-time error too.
It's good practice to always minimize the scope of variables (which gives you less chance to misuse them). If you do not wish to further examine the returned error after the if, it's better to use the A version. If you do need it after the if, then obviously the B version is the way to go.


text:
Q: How to create an image of an entire remote system for using on other (virtual) remote machines? I have ordered several virtual machines from a hosting provider, which all need exactly the same setup:

*

*same users

*same programs installed

*same config (except for hostname) including cron-jobs

Is it possible and save to create a tarball of my entire system, excluding /dev, /proc, /sys folders and the /etc/hostname file and just unpack it on the disk while the system is not running (using a repair mode, or a Live CD, in case of a physical server)?
What else do I have to consider?
Edit: Since I have no physical access to these machines, everything has to be done from the command line.
Edit 2: Also /etc/network/interfaces should not be copied.

A: Yes, you can.

*

*Make sure the /etc/fstab is still correct, based on where you put partitions and what types they are. Make sure you run mkswap on any swap partition. If UUIDs are used, then you'll need to update these. The blkid command will give you the UUIDs of all the new partitions. If labels are used, then use the e2label command (or equivalent command for your filesystem) to make sure that the labels match.

*Skip these, and make sure you create empty ones at the other end: /run (/var/run on older releases), /proc, /sys, /dev. Check /proc/mounts on the old (running) system for others (there are fewer on newer releases).

*Update /etc/hostname and /etc/hosts (which also contains the hostname).

*Check /etc/udev/rules.d/ for a 70-persistent-net.rules or similarly named file that contains any NIC MAC addresses. These are usually skipped for virtual machines though, and the only harm would be that you end up with an eth1 device instead of the usual eth0.

*As you've mentioned, you should check /etc/network/interfaces for correctness, especially with respect to ethernet device names.

*Re-run the bootloader installation. This is the awkward bit. It depends on how your VPS provider boots your instance. It's worth having a plan for this before you begin.

A: You can consider using the CloneZilla application, which allows you to either backup and restore, or directly clone, over the network.
It efficiently backs up (or clones) a disk, copying only the used parts of the partitions. It also copies the MBR.
After restoring your new partition, be sure to correct the following files:

*

*UUID in /etc/fstab (if required; in my experience, CloneZilla also clones the UUID).

*The computer name in /etc/hostname and /etc/hosts.

*If appropriate, any changes to /etc/samba/smb.conf.


text:
Q: Can I access the last computed result before a function 'stop's? Consider this code:
bad_function <- function() {
    # a lot of code
    x <- 1
    stop("error")
}

tryCatch(bad_function(), error = function(cond) {x})

Obviously, x is not accessible in the error handler. But is there another way to access the value of x without changing bad_function? Alternatively, is there a way to patch bad_function to skip over stop("error") and return x without having to copy all that # a lot of code?

A: This works if the result you are looking for is named (and the you know the name - here, x):
bad_function <- function() {
    # a lot of code
    x <- 1
    stop("error")
}

.old_stop <- base::stopifnot
.new_stop <- function(...) {
    parent.frame()$x
}

assignInNamespace("stop", .new_stop, "base")
bad_function()
assignInNamespace("stop", .old_stop, "base")

I still wonder if there are better solutions.

A: You could assign the value simultaneously to x in the function environment, as well to another x in an external say debug environment that you defined beforehand.
ev1 <- new.env()

bad_function <- function() {
  env <- new.env(parent=baseenv())
  # a lot of code
  x <- ev1$x <- 1
  stop("error")
}

tryCatch(bad_function(), error = function(e) ev1$x)
# [1] 1

The advantage is that .GlobalEnv stays clear (apart from the environment of course).
ls()
# [1] "bad_function" "ev1"


text:
Q: "Get" request method not working in vba I've written a code to fetch the name
of a restaurant using its phone number applying
"GET" http method but what i'm doing wrong
with this process is beyond my knowledge. So, if anybody extends a helping
hand to resolve this issue, i would be very grateful to him.
Thanks in advance.
Sub test()

Dim xmlhttp As New MSXML2.XMLHTTP60, myHtml As New HTMLDocument
Dim PostData As String, ele As Object, thing As Object
Dim x As Long

x = 2

PostData = "what=5197365924"
xmlhttp.Open "GET", "http://mobile.canada411.ca/search/" & PostData, False
xmlhttp.setRequestHeader "Content-Type", "text/xml"
xmlhttp.send
myHtml.body.innerHTML = xmlhttp.responseText

Set ele = myHtml.getElementsByClassName("merchant-title__name jsShowCTA")

For Each thing In ele
    Cells(x, 1) = thing.innertext
    x = x + 1
Next thing

End Sub

A: Your code is pretty fine, but your endpoint does not show anything, you can test in your browser and you will see.
I suggest you read the YellowAPI doc and test this kind of endpoint, changing the values YOUR_API_KEY_HERE and YOUR_UID_HERE.

A: Lots of issues were there in my post. However, I've fixed it already. Now, it is good to go.
Sub reverse_search()
    Dim http As New XMLHTTP60, html As New HTMLDocument
    Dim ArgumentString As String, post As Object

    ArgumentString = "what=5197365924&where=Canada&redirect=reversetobusiness"

    With http
        .Open "GET", "https://www.yellowpages.ca/bus/Ontario/Amherstburg/Downtown-Expresso-Cafe/522901.html?" & ArgumentString, False
        .setRequestHeader "Content-Type", "text/xml"
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
        .send
        html.body.innerHTML = .responseText
    End With

    For Each post In html.getElementsByClassName("merchant-title__name")
        x = x + 1: Cells(x, 1) = post.innerText
    Next post
End Sub


text:
Q: Sorting an arraylist based on objects value in another arraylist in Java I have an issue with sorting an Array List.
In a class i have two Array Lists of different objects, we can call the objects Foo and Bar.
public class Foo() {
   int value;
   //Some other fields, and setters and getters.
}

public class Bar() {
   int id;
   //Same here...
}

So the list fooList can be totally scrambeled. Say that i have 16 Foos, but Foo with value 5 can be on index 13 and so on.
What i'm trying to do is to order barList to match fooList after these values.
If Foo with value 5 is on index 13, i want Bar with value 5 to be on index 13.
My last attempt was this, but no success.
HashMap<Integer, Integer> positions = new HashMap<>();
for(int i=0;i<fooList.size();i++){
    positions.put(foo.get(i).getValue, i);
}
Collections.sort(barList, new Comparator<Bar>(){
    public int compare(Bar obj1, Bar obj2){
        return positions.get(barList.indexOf(obj1)) -
 positions.get(barList.indexOf(obj2));
    }
});

Does anybody have a clue how to do this in an efficient way?

A: I'm not sure why you are using the index of an element in barList to look into the map positions.
This should help you
Collections.sort(barList, new Comparator<Bar>() {
    @Override
    public int compare(Bar o1, Bar o2) {
        return positions.get(o1.getId()) - positions.get(o2.getId());
    }
});

This can be simplified with a one-liner
Collections.sort(barList, Comparator.comparingInt(bar -> positions.get(bar.getId())));

Basically, the problem boils down to this:
Given two lists of integers A = {a1, a2...an} and B = {b1, b2, ...bm}, sort the list B based on the position of occurrence of the element in the first list, A.
For two elements x, y in B

*

*x > y, if x appears before y in A.

*x < y, if x appears after y in A.

*x = y, if x = y
So, the comparator function for Bar has to compare the position at which a particular element has appeared in Foo (based on the above).
NOTE: This assumes (as you have said) that there is no element in Bar that is not there in Foo. (The elements in Bar are a subset of the elements in Foo).

A: I'd first index items of the barList on values so that it would be possible to quickly find a Bar instance with the appropriate value. Then use it to transform the fooList into the new barList. Something along the lines:
Map<Integer, Bar> barMap = barList
    .stream()
    .collect(Collectors
        .toMap(
            Bar::getValue,
            Function.identity());
barList = fooList
    .stream()
    .map(Foo::getValue)
    .map(barMap::get)
    .collect(Collectors.toList());

I think this must be as optimal as it gets in terms of time. In the expence of memory, you have to build a barMap here.


text:
Q: No layers when configuring TinyOWS with MapServer Am trying to expose a vector layer (loaded from shapefile into PostGIS) as a WFS layer using TinyOWS.
Following the instructions in the mapserver/tinyows documentation, here is the .map file I have come up with so far:
MAP
    NAME "world"
    CONFIG "MS_ERRORFILE" "/home/balajeerc/Projects/Build_Dir/myproject/data/logs/mapservice_errors.log"
    EXTENT -180.000 -90.000 180.000 90.000

    WEB
        METADATA
            "tinyows_schema_dir" "/home/balajeerc/Projects/Build_Dir/myproject/deps/mygis-services-0.1/data/schema"
            "tinyows_onlineresource" "http://192.168.43.164:19090/vectors/world/wfs?"
            "wfs_title" "MyGIS Feature Service: World"
            "wfs_contact" "support@giscompany.com"
            "wms_title" "MyGIS Feature Service: World"
            "wms_srs" "epsg:4326"
            "wms_enable_request" "*"
            "log_level" "15"
            "log" "/home/balajeerc/Projects/Build_Dir/myproject/deps/mygis-services-0.1/data/logs/wfs_world.log"
            "ows_contactorganization" "GeorbisServer"
            "ows_contactelectronicmailaddress" "contact@giscompany.com"
            "ows_contactperson" "Balajee.R.C"
        END
    END

    PROJECTION
        "init=epsg:4326"
    END

    LAYER
        NAME 'world_boundaries'
        CONNECTIONTYPE postgis
        CONNECTION "host=localhost user=mygis password=asdf123 dbname=mygis port=19095"
        DATA "geom from world_boundaries"
        TYPE POLYGON
        METADATA
            'wfs_title' 'world_boundaries'
            'wfs_namespace_prefix' 'tows'
            'wfs_namespace_uri' 'http://www.giscompany.com/'
            'wfs_srs' 'epsg:4326'
            'wms_srs' 'epsg:4326'
            'wms_title' 'world_boundaries'
            'tinyows_table'  'world_boundaries'
            'tinyows_writable' '1'
            'tinyows_retrievable' '1'
        END
        CLASS
            STYLE
                COLOR 128 128 128
                ANTIALIAS true
            END
        END
        PROJECTION
          "init=epsg:4326"
        END
        DUMP TRUE
    END
END

This .map file works fine with MapServer, i.e. I am able to render the feature layer as a WMS service using QGIS as a client.
However, the WFS service (served by tinyows) using the same file (set using TINYOWS_MAPFILE environment variable seems to show no layers in GetCapabilities (and hence QGIS is not able to load any).
The output from tinyows --check is as follows:
balajeerc@Balajee:~/Projects/tinyows-1.1.1$ ./tinyows --check
TinyOWS version:   1.1.0
FCGI support:      Yes
Config File Path:  /home/balajeerc/Projects/Build_Dir/myproject/data/service_data/data/wfs/world.map (Mapfile)
PostGIS Version:   2.1.8
PostGIS dsn:       host=localhost user=mygis password=asdf123 dbname=mygis port=19095
Output Encoding:   UTF-8
Database Encoding: UTF8
Schema dir:        /home/balajeerc/Projects/Build_Dir/myproject/deps/mygis-services-0.1/data/schema
Display bbox:      Yes
Estimated extent:  No
Check schema:      Yes
Check valid geoms: Yes
Available layers:
balajeerc@Balajee:~/Projects/tinyows-1.1.1$

Note that even though I am using a 1.1.1 version of TinyOWS, it prints TinyOWS version as 1.1.0. Also note that it prints no layers.
Wondering what is going wrong, I decided to step into the code. I recompiled code after turning off (-O2) optimizations and with debugging (-g) enabled.
I am only able to get so far as the ows_parse_config method in src/ows/ows_config.c. I am, for some reason not able to step into ows_parse_config_map in src/mapfile/mapfile.c. This probably has something to do with the fact that mapfile.c is generated by flex using src/map/mapfile.l.
At this point I am completely stuck and at a brick wall as to what might be going wrong. Can someone here please help?

A: I see you have WMS enabled with this statement:
"wms_enable_request" "*"
But where is the comparable statement for WFS?
"wfs_enable_request" "*"
This probably has an influence on your WFS not working


text:
Q: Android app with lots of external libraries vs application size I have an android app with a few external libraries (also native) and I will have to add another ones. My app is growing which becomes a real problem.
Single library is used by less than 5% of my app users so I do not want to force all my users to install app with all the libraries that they do not need. In fact most of my users do not need any of these libraries.
I was wthinking about expansion files (https://developer.android.com/google/play/expansion-files.html) but as far as I know this doesn't solve my problem as in most cases all the expansion files are downloaded with application anyway.
Is there a solution that allows my to download external code on the go?
Marcin


text:
Q: C++ When checking for equality between a variable and 0, gives segment fault (when debugging) let's say i have an array like this:
1 0 0
0 2 1
0 1 0

so i would like to check if the number above 2 is 0, and to change it to two if it's true. Assuming i = 1 and j = 1:
string var = "2";
if(tab[i][j] == var && tab[i-1][j] == "0") {
       tab[i-1][j] = "2";
}

here is where i get the segment fault, if i change 0 to 1 in if statement, it works fine. Why? tryied even to make the 2d array as int, same problem.
changing "0" to '0' or vice-versa = same problem.
for(int i = 0; i < n; i++) {
    vector<string> current_row;
    for(int j =0; j < m; j++) {
        myfile >> buff;
        current_row.push_back(buff);
    }
    tab.push_back(current_row);

}

that's how i populate it.

A: It seems that you are accessing memory outside of the bounds of the array. One thing that could cause that is if tab[0][?] == var. this causes your condition to check tab[-1][?] and generates an exception.


text:
Q: How to enter date/time for the datatype XMLGregorianCalendar
Possible Duplicate:
java.util.Date to XMLGregorianCalendar

I have a Java method with a parameter from the type XMLGregorianCalendar, but I don't know how to set Date/Time:
XMLGregorianCalendar startDateTime = ???

Thank you very much, for helping...

A: import javax.xml.datatype.DatatypeFactory;
// ...
XMLGregorianCalendar xc = DatatypeFactory.newInstance().newXMLGregorianCalendar(
    int year,
    int month,
    int day,
    int hour,
    int minute,
    int second,
    int millisecond,
    int timezone)

there are other versions of newXMLGregorianCalendar(), eg newXMLGregorianCalendar(GregorianCalendar cal).