text:
Q: Removing Vertical White Lines in ggplot Line Graph I've produced a graph using ggplot and some data that represents the occurrence of specific management actions over the past decade. The graph looks great except for some vertical white spaces that appear within the plotted lines. Is there a way to remove these lines? I'm guessing they are caused by the grouping of my data (group=1). Any help would be appreciated. My code is below.
Also, I've used this stackoverflow question as guidance.
library(scales)

# Build data frame.
a7.data <- data.frame(date = seq(as.Date("2002/01/01"), as.Date("2013/05/01"),     by="day"))
a7.data$year <- as.numeric(format(as.Date(a7.data$date), format="%Y"))
a7.data$month <- as.numeric(format(as.Date(a7.data$date), format="%m"))
a7.data$day <- as.numeric(format(as.Date(a7.data$date), format="%d"))
a7.data$status <- "Yes"
a7.data$filler_value <- 0

# Edit data frame for dates in which the management action was "no".
a7.data$status[a7.data$date >= "2002/01/01" & a7.data$date < "2002/07/01"] <- "No"
a7.data$status[a7.data$date >= "2005/05/20" & a7.data$date < "2005/08/25"] <- "No"
a7.data$status[a7.data$date >= "2005/12/31" & a7.data$date < "2006/04/12"] <- "No"
a7.data$status[a7.data$date >= "2006/11/06" & a7.data$date < "2006/12/31"] <- "No"
a7.data$status[a7.data$date >= "2007/01/31" & a7.data$date < "2007/07/02"] <- "No"
a7.data$status[a7.data$date >= "2008/02/01" & a7.data$date < "2009/08/11"] <- "No"
a7.data$status[a7.data$date >= "2010/02/28" & a7.data$date < "2010/03/15"] <- "No"
a7.data$status[a7.data$date >= "2010/05/09" & a7.data$date < "2010/07/07"] <- "No"

# Create a new column that creates a dummy year with which to plot the data in ggplot using faceting.
a7.data <- transform(a7.data, doy = as.Date(paste(1970, month, day, sep="/")))

# Custom colors.
ccolors <- c("#086CA2", "#FF8B00")

# ggplot code.
bb <- ggplot(a7.data, aes(doy, filler_value)) +
geom_line(aes(color=status, group=1), size=15, alpha=0.9) +
scale_x_date(label=date_format("%b"), breaks = "month") +
xlab("") + ylab("") + facet_grid(year~., scales="free") +
theme_bw() + theme(axis.text.y=element_blank()) +
theme(axis.ticks.y=element_blank()) +
scale_color_manual(values=ccolors, name="Article VII Restrictions?")

# Display plot.
bb

A: Interesting plot! I think if I understand your problem you either need

*

*to add an expand = c(0,0) to scale_x_date to get rid of the space
at the boundaries

*and/or use geom_linerange to make contiguous colour blocks

But you need to specify both a ymin and a ymax value to use geom_linerange. filler_value seems to be a natural choice for ymin so lets make a7.data$filler_value2 <- 1 to be our ymax and use a geom_linerange and include an expand argument:
a7.data$filler_value2 <- 1
bb <- ggplot(a7.data, aes(x = doy)) +
geom_linerange( aes(ymin = filler_value , ymax = filler_value2 , color=status, group=1), size=15, alpha=0.9) +
scale_x_date(label=date_format("%b"), breaks = "month" , expand = c(0,0)) +
xlab("") + ylab("") + facet_grid(year~., scales="free") +
theme_bw() + theme(axis.text.y=element_blank()) +
theme(axis.ticks.y=element_blank()) +
scale_color_manual(values=ccolors, name="Article VII Restrictions?")

# Display plot.
bb

If I make those changes I get a plot that looks like this...


text:
Q: How check max file size upload in C++? I have a server written in C++, that allow the uploading of files.
But I want to check  FIRST, the file size and THEN upload it if it is less than 100 MB, else error.
Is there a function that can do that?
This is my function:
long bytes_read = recv(client_fd, tempBuffer, sizeof(tempBuffer),0);

But I cannot control the var bytes_read while receiving the file, but only after.
This is the problem.

A: You should to send 4-bytes file length before file data:
int file_fize;
recv(client_fd, &file_fize, sizeof(file_fize),0);
recv(client_fd, buffer, file_fize,0);

A: You should send the size of the file from a client BEFORE sending the file itself. Check the size and responce to your client if you are ready to receive it or not

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display the current date & time in the Freemarker template section of smooks? I am able to display the contents of my incoming XML file using smooks in the freemarker template, but I want to add Current Date & time of my local system to identify the execution of my program.
<ftl:freemarker applyOnElement="CreditCard">
    <ftl:template><!--        <BalanceInquiryRequest>
        <TransactionId>${BalanceInquiryRequest.TransactionId}</<TransactionId>
        <ConfigurationId>${BalanceInquiryRequest.ConfigurationId}</ConfigurationId>
        <CardNumberr>${.vars["GiftCard"].CardNumber}</CardNumberr>
        <ExpirationDate>${.vars["GiftCard"].ExpirationDate}</ExpirationDate>
        <SecurityCode>${.vars["GiftCard"].SecurityCode}</SecurityCode>
       *****************************
Here I want to display the current Date & time
    </BalanceInquiryRequest>
    --></ftl:template>
</ftl:freemarker>

Can you tell me how can I add current date & time in the XML without having an entry in the incoming XML.

A: use .now, they introduced it some time ago, no need for java

A: There seems to be an answer here. The short answer, you need to pass in Java.

A: You cannot do it since XML like Freemarker are template engines, not objects. You have to pass it into the java object as new Date();

A: You could write a short groovy script in the Smooks configuration file to populate a bean in the beancontext with today's date. Then the freemarker script could use the value from that bean.
Edit: You can read more about Groovy and Smooks here: http://www.smooks.org/mediawiki/index.php?title=V1.3:Smooks_v1.3_User_Guide#Groovy_Scripting
You probably want to use methods from http://www.milyn.org/javadoc/v1.2/smooks-cartridges/javabean/org/milyn/javabean/repository/BeanRepository.html and do something similar to:
  <g:groovy executeOnElement="xxx">
    <g:script>
    <!--
    addBean("date", new Date());
    -->
    </g:script>
</g:groovy>

You should then be able to access the "date" bean in your freemarker.

A: You can do it without .now and you don't have to pass in new Date.
I'm having to work with old freemarker at the moment and did this instead..
<#assign dateNow = Static["java.util.Calendar"].getInstance().getTime()?datetime />


text:
Q: Is there a way to view the built-in documentation in C++? I just started to learn C++ this month.
In Python, I can view the documentation of a built-in function (for example, str.find) by using help(str.find).
However, I've no idea about how to view the documentation of std::find in <algorithm>, for example.
Does anyone have ideas about a quick way to look up documentation of a function in C++?

A: C++ doesn't have built-in documentation like Python.
The most comprehensive online reference guide is C++ reference, which covers the last three standards. This is not the top hit on most search engines but the top hit is full of inaccuracies and should be avoided.
You can also download archives of the site for offline viewing (English link).

Does anyone have ideas about a quick way to look up documentation of a function in C++?

In Google Chrome, I have a search engine set up with the keyword "cpp" and the URL "http://en.cppreference.com/mwiki/index.php?title=Special%3ASearch&search=%s" so that I can type cpp std::find
 in the address bar to find details of std::find in my browser.

A: C++ itself doesn't have "built-in documentation" per se. It is a language, not a system. Sure, Python is "just a language" too, but it's also an interpreter and this interpreter has certain features that C++ compilers don't have.
On Linux you may find manpages for what you need, because libstdc++ (GCC's C++ standard library implementation) installs them:
man std::string

C++ documentation may be found canonically at:

*

*http://cppreference.com (peer-reviewed and well-regarded)

*Your C++ book (peer-reviewed by SO)

*The C++ standard (authoritative)

You should not use:

*

*Wikipedia

*SGI STL documentation (the SGI STL is not the same as the C++ Standard Library)

*http:// cplusplus.com

A: There is no such thing as builtin documentation in C++. You may have some documentation that comes with you compiler, but that is mainly for commercial products and vendor specific. You are best off using google to find your site of choice.


text:
Q: How to get&modify metadata to supported audio files on Android? Background
Android supports various audio files encoding and decoding.
I record audio into an audio file using android.media.MediaRecorder class, but I also wish to show information about the files I've recorded (not standard data, but still just text, maybe even configurable by user), and I think it's best to store this information within the files.
examples of possible data to store: when it was recorded, where it was recorded, notes by the user...
The problem
The MediaRecorder class doesn't have any function that I can find, to add or even read metadata of the recorded audio file.
I also can't find a similar class that does it.
What I've tried
I tried searching how to do it for specific files types, and also tried to find a library that does it.
I haven't find even a clue about this information.
The only thing I've found for MediaRecorder class, is a function called "setLocation" , which is used to indicate where the recording has started (geographically), and looking at its code, I can see it sets parameters:
public void setLocation(float latitude, float longitude) {
    int latitudex10000  = (int) (latitude * 10000 + 0.5);
    int longitudex10000 = (int) (longitude * 10000 + 0.5);

    if (latitudex10000 > 900000 || latitudex10000 < -900000) {
        String msg = "Latitude: " + latitude + " out of range.";
        throw new IllegalArgumentException(msg);
    }
    if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
        String msg = "Longitude: " + longitude + " out of range";
        throw new IllegalArgumentException(msg);
    }

    setParameter("param-geotag-latitude=" + latitudex10000);
    setParameter("param-geotag-longitude=" + longitudex10000);
}

But setParameter is private, and I'm not sure if it's ok to put anything I want into it, even if I had a way to access it (reflection, for example) :
private native void setParameter(String nameValuePair);

I also don't get, given an audio/video file, how to get/modify this kind of information. It's not available for SimpleExoPlayer, for example.
The questions

*

*How can I read,write, and modify metadata inside supported audio files of Android?

*Are there any limitations/restrictions for those actions?

*Which file formats are available for this?

*Is it possible to add the metadata while I record the audio?

*Is it possible perhaps via MediaStore ? But then how do I do those operations? And which files are supported? And does the metadata stay within the file?

EDIT: ok I've looked at the solution offered to me (here, repo here, based on here) , and it seems to work well. However, it doesn't work on latest version of the library that it uses (org.mp4parser.isoparser:1.9.37 dependency of mp4parser) , so I leave this question to be answered : Why doesn't it work on latest version of this library?
Code:
object MediaMetaDataUtil {
    interface PrepareBoxListener {
        fun prepareBox(existingBox: Box?): Box
    }

    @WorkerThread
    fun <T : Box> readMetadata(mediaFilePath: String, boxType: String): T? {
        return try {
            val isoFile = IsoFile(FileDataSourceImpl(FileInputStream(mediaFilePath).channel))
            val nam = Path.getPath<T>(isoFile, "/moov[0]/udta[0]/meta[0]/ilst/$boxType")
            isoFile.close()
            nam
        } catch (e: Exception) {
            null
        }
    }

    /**
     * @param boxType the type of the box. Example is "©nam" (AppleNameBox.TYPE). More available here: https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
     * @param listener used to prepare the existing or new box
     * */
    @WorkerThread
    @Throws(IOException::class)
    fun writeMetadata(mediaFilePath: String, boxType: String, listener: PrepareBoxListener) {
        val videoFile = File(mediaFilePath)
        if (!videoFile.exists()) {
            throw FileNotFoundException("File $mediaFilePath not exists")
        }
        if (!videoFile.canWrite()) {
            throw IllegalStateException("No write permissions to file $mediaFilePath")
        }
        val isoFile = IsoFile(mediaFilePath)
        val moov = isoFile.getBoxes<MovieBox>(MovieBox::class.java)[0]
        var freeBox = findFreeBox(moov)
        val correctOffset = needsOffsetCorrection(isoFile)
        val sizeBefore = moov.size
        var offset: Long = 0
        for (box in isoFile.boxes) {
            if ("moov" == box.type) {
                break
            }
            offset += box.size
        }
        // Create structure or just navigate to Apple List Box.
        var userDataBox: UserDataBox? = Path.getPath(moov, "udta")
        if (userDataBox == null) {
            userDataBox = UserDataBox()
            moov.addBox(userDataBox)
        }
        var metaBox: MetaBox? = Path.getPath(userDataBox, "meta")
        if (metaBox == null) {
            metaBox = MetaBox()
            val hdlr = HandlerBox()
            hdlr.handlerType = "mdir"
            metaBox.addBox(hdlr)
            userDataBox.addBox(metaBox)
        }
        var ilst: AppleItemListBox? = Path.getPath(metaBox, "ilst")
        if (ilst == null) {
            ilst = AppleItemListBox()
            metaBox.addBox(ilst)
        }
        if (freeBox == null) {
            freeBox = FreeBox(128 * 1024)
            metaBox.addBox(freeBox)
        }
        // Got Apple List Box
        var nam: Box? = Path.getPath(ilst, boxType)
        nam = listener.prepareBox(nam)
        ilst.addBox(nam)
        var sizeAfter = moov.size
        var diff = sizeAfter - sizeBefore
        // This is the difference of before/after
        // can we compensate by resizing a Free Box we have found?
        if (freeBox.data.limit() > diff) {
            // either shrink or grow!
            freeBox.data = ByteBuffer.allocate((freeBox.data.limit() - diff).toInt())
            sizeAfter = moov.size
            diff = sizeAfter - sizeBefore
        }
        if (correctOffset && diff != 0L) {
            correctChunkOffsets(moov, diff)
        }
        val baos = BetterByteArrayOutputStream()
        moov.getBox(Channels.newChannel(baos))
        isoFile.close()
        val fc: FileChannel = if (diff != 0L) {
            // this is not good: We have to insert bytes in the middle of the file
            // and this costs time as it requires re-writing most of the file's data
            splitFileAndInsert(videoFile, offset, sizeAfter - sizeBefore)
        } else {
            // simple overwrite of something with the file
            RandomAccessFile(videoFile, "rw").channel
        }
        fc.position(offset)
        fc.write(ByteBuffer.wrap(baos.buffer, 0, baos.size()))
        fc.close()
    }

    @WorkerThread
    @Throws(IOException::class)
    fun splitFileAndInsert(f: File, pos: Long, length: Long): FileChannel {
        val read = RandomAccessFile(f, "r").channel
        val tmp = File.createTempFile("ChangeMetaData", "splitFileAndInsert")
        val tmpWrite = RandomAccessFile(tmp, "rw").channel
        read.position(pos)
        tmpWrite.transferFrom(read, 0, read.size() - pos)
        read.close()
        val write = RandomAccessFile(f, "rw").channel
        write.position(pos + length)
        tmpWrite.position(0)
        var transferred: Long = 0
        while (true) {
            transferred += tmpWrite.transferTo(0, tmpWrite.size() - transferred, write)
            if (transferred == tmpWrite.size())
                break
            //System.out.println(transferred);
        }
        //System.out.println(transferred);
        tmpWrite.close()
        tmp.delete()
        return write
    }

    @WorkerThread
    private fun needsOffsetCorrection(isoFile: IsoFile): Boolean {
        if (Path.getPath<Box>(isoFile, "moov[0]/mvex[0]") != null) {
            // Fragmented files don't need a correction
            return false
        } else {
            // no correction needed if mdat is before moov as insert into moov want change the offsets of mdat
            for (box in isoFile.boxes) {
                if ("moov" == box.type) {
                    return true
                }
                if ("mdat" == box.type) {
                    return false
                }
            }
            throw RuntimeException("I need moov or mdat. Otherwise all this doesn't make sense")
        }
    }

    @WorkerThread
    private fun findFreeBox(c: Container): FreeBox? {
        for (box in c.boxes) {
            //            System.err.println(box.type)
            if (box is FreeBox)
                return box
            if (box is Container) {
                val freeBox = findFreeBox(box as Container)
                if (freeBox != null) {
                    return freeBox
                }
            }
        }
        return null
    }

    @WorkerThread
    private fun correctChunkOffsets(movieBox: MovieBox, correction: Long) {
        var chunkOffsetBoxes = Path.getPaths<ChunkOffsetBox>(movieBox as Box, "trak/mdia[0]/minf[0]/stbl[0]/stco[0]")
        if (chunkOffsetBoxes.isEmpty())
            chunkOffsetBoxes = Path.getPaths(movieBox as Box, "trak/mdia[0]/minf[0]/stbl[0]/st64[0]")
        for (chunkOffsetBox in chunkOffsetBoxes) {
            val cOffsets = chunkOffsetBox.chunkOffsets
            for (i in cOffsets.indices)
                cOffsets[i] += correction
        }
    }

    private class BetterByteArrayOutputStream : ByteArrayOutputStream() {
        val buffer: ByteArray
            get() = buf
    }

}

Sample usage for writing&reading title:
object MediaMetaData {
    @JvmStatic
    @Throws(IOException::class)
    fun writeTitle(mediaFilePath: String, title: String) {
        MediaMetaDataUtil.writeMetadata(mediaFilePath, AppleNameBox.TYPE, object : MediaMetaDataUtil.PrepareBoxListener {
            override fun prepareBox(existingBox: Box?): Box {
                var nam: AppleNameBox? = existingBox as AppleNameBox?
                if (nam == null)
                    nam = AppleNameBox()
                nam.dataCountry = 0
                nam.dataLanguage = 0
                nam.value = title
                return nam
            }
        })
    }

    @JvmStatic
    fun readTitle(mediaFilePath: String): String? {
        return MediaMetaDataUtil.readMetadata<AppleNameBox>(mediaFilePath, AppleNameBox.TYPE)?.value
    }
}

A: It seems there's no way to do it uniformly for all supported audio formats in Android. There are some limited options for particular formats though, so I suggest to stick with one format.
MP3 is the most popular one and there should be a lot of options like this one.
If you don't want to deal with encoding/decoding, there are some options for a WAV format.
There's also a way to add a metadata track to a MP4 container using MediaMuxer (you can have an audio-only MP4 file) or like this.
Regarding MediaStore: here's an example (at the end of page 318) on how to add metadata to it just after using MediaRecorder. Though as far as I know the data won't be recorded inside the file.
Update
I compiled an example app using this MP4 parser library and MediaRecorder example from SDK docs. It records an audio, puts it in MP4 container and adds String metadata like this:
MetaDataInsert cmd = new MetaDataInsert();
cmd.writeRandomMetadata(fileName, "lore ipsum tralalala");

Then on the next app launch this metadata is read and displayed:
MetaDataRead cmd = new MetaDataRead();
String text = cmd.read(fileName);
tv.setText(text);

Update #2
Regarding m4a file extension: m4a is just an alias for an mp4 file with AAC audio and has the same file format. So you can use my above example app and just change the file name from audiorecordtest.mp4 to audiorecordtest.m4a and change audio encoder from MediaRecorder.AudioEncoder.AMR_NB to MediaRecorder.AudioEncoder.AAC.


text:
Q: PowerShell Move-Object script task I want to create a scheduled script that will move all folder's .exe items to another dir.
This is what I tried to do:
$folderItems = Get-ChildItem -Path C:\Users\Administrator\Downloads\Test | where {$_.Extension -eq ".exe"}

This is the output:
PS C:\Users\Administrator\Downloads> $folderItems

Directory: C:\Users\Administrator\Downloads\Test

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----         6/4/2018  10:42 PM       10563368 bsplayer272.setup.exe
-a----        5/27/2018   9:46 PM         658488 setup.exe
-a----         6/4/2018   7:28 PM        2948240 uTorrent.exe

But when I try to move them:
$folderitems | % {
  Move-Item -Path C:\Users\Administrator\Downloads\Test\$_.name -Destination D:\Downloads\
}

This is the error I get:

Move-Item : Cannot find path
  'C:\Users\Administrator\Downloads\Test\bsplayer272.setup.exe.name'
  because it does not exist.

What am I doing wrong?
Thanks,

A: *

*Move-Item accepts piped input, so no ForEach-Object,%needed,
also not the intermediate variable.

*If you attach the wildcard to the path the where is also superfluous.

Get-ChildItem -Path C:\Users\Administrator\Downloads\Test\*.exe |
    Move-Item -Destination D:\Downloads\

Your own command could work if you put it like @Theo's suggestion, or
$folderitems | % {
  Move-Item -Path 'C:\Users\Administrator\Downloads\Test\'+$_.Name -Destination D:\Downloads\
}

or
$folderitems | % {
  $_ | Move-Item -Destination D:\Downloads\
}


text:
Q: Force reauthenticate with adfs I have seen a similar post but that was more related to ASP. I will explain my situation below.
I am developing a SP(Relying Party) and integrating with ADFS (IDP). Since I am in the integration phase, I want ADFS to forget that I have previously authenticated so that each time I hit the ADFS endpoint (/adfs/ls) with AuthnRequest, I want it to ask for my credentials.
I believe ADFS by default, remembers clients by their remote IP/host name so clearing cookies  on client machine does not help. There was a post that gave a link to logout from IDP (https:///adfs/ls/?wa=wsignout1.0&wreply=https:///adfs/ls/?wa=wsignoutcleanup1.0). The ADFS says I have been logged out but when I hit ADFS endpoint, ADFS redirects back to SP with successful AuthResponse.
Can you please tell me how to force reauthenticate/logout on ADFS or point me to the right articles?

A: The FederatedPassiveSignInStatus control (which should be part of VS if you've installed all the WIF stuff) will help you. Add it to your app. and clicking it will log you out of everything.
Also AD FS: How to Invoke a WS-Federation Sign-Out

A: Add wfresh=0 as a URL parameter.
This parameter indicates "freshness requirements".
According to the spec:

If specified, this indicates the desired maximum age of authentication specified in minutes.


text:
Q: Преобразовать ═юьхэъырЄєЁр в Номенклатура в С# Задача при чтении файла DBF III с записанной в поле файла заголовка CodePage 201, текст выглядит абракадаброй.
В частности слово Номенклатура как ═юьхэъырЄєЁр
Обычный подход не работает, так как дает то же самое на выходе ═юьхэъырЄєЁр
Encoding utf8 = Encoding.GetEncoding("UTF-8");
Encoding win1251 = Encoding.GetEncoding("Windows-1251");
var testStr = "═юьхэъырЄєЁр";

var result = Encoding.UTF8.GetString(Encoding.Convert(win1251, utf8,  testStr.ToByteArray(win1251)));

Есть варианты? Всем спасибо!
Тут преобразуется https://2cyr.com/decode/?lang=ru в Номенклатура

A: var result = Encoding.GetEncoding("windows-1251").GetString(Encoding.GetEncoding("cp866").GetBytes("═юьхэъырЄєЁр"));


text:
Q: Why this is a covering map between compact Riemann surfaces? Let $F:X\rightarrow Y$ be a non constant holomorphic map between compact Riemann surfaces
, If we delet the branch points (in $Y$) of $F$ and all their pre-images(in $X$), we obtain a map $F:U\rightarrow V$ between 2- manifolds which is a covering map in the sense of topology: every point of the target $V$ has an open neighborhood $N\subseteq V$ such that the inverse image of $N$ under $F$ breaks into a disjoint open sets $M_i\subseteq U$ with the map $F$ sending each $M_i$ homeomorphically onto $N$,
I do not understand why this is a covering map and I can not visualize why inverse image of $N$ is like that, please could any one make me understand with an example of map between known compact riemann surfaces?

A: The important point is that, once you have deleted all the branch points and their preimages, the function $F : U \to V$ is a differentiable function whose derivative is everywhere invertible. So, by the implicit function theorem, $F$ is a local homeomorphism.
Now, local homeomorphism is a notion quite close to "covering map": a map is a local homeomorphism if for every $x \in U$ you have neighbourhoods $\mathscr V_x$ and $\mathscr V_{y}$ such that $f$ is an homeomorphism $\mathscr V_x \to \mathscr V_y$ ($y$ being $f(x)$). Roughly, it being a covering map means that for every $y \in V$ you can find a neighbourhood $\mathscr V_y$ such that for every preimage $x$ there is a neighbourhood $\mathscr V_x$ such that $f$ induces an homeomorphism $f : \mathscr V_x \to \mathscr V_y$. (I'm conscious that this "definition" isn't equivalent to the correct one. But that's what is important: in a covering map, you have one neighbourhood in the target which works uniformly for every preimage). With this slogan in mind, it is quite easy to cook up examples of local homeomorphism which aren't covering maps when a point has infinitely many preimages. But it's basically the only problem, as shows the classical proposition : a proper map $f$ between locally compact spaces is a covering map if and only if it is a local homeomorphism. I'm sure you can find a proof in any textbook about covering maps, but the key is that properness allows you to have a uniform control on all the preimages of your $\mathscr V_y$.
So, your map $F : U \to V$ is a local homeomorphism, $F : X \to Y$ was clearly proper because $X$ is compact, so now you only have to check that deleting the branch points and all their preimages hasn't destructed properness. (If you think of a proper map as a map such that $f(x)$ goes to infinity as soon as $x$ does, it should be quite clear because of the continuity of $F : X \to Y$. And you have your proof!
(I reckon that what I have said is nothing like a rigourous proof. But you can find such a proof with all the necessary details in any textbook about compact Riemann surfaces, so I thought explaining to you why this result is reasonable was the best thing to do.)


text:
Q: How to save a Dictionary of Dictionaries to UserDefaults [Int:[Int:Int]]? I am trying to save a dictionary of dictionaries to UserDefaults.
I can save the dictionary in this way:
var dict = [Int:[Int:Int]]()
dict[1] = [4:3]
dict[10] = [5:10]

let data = try
NSKeyedArchiver.archivedData(withRootObject: dict, requiringSecureCoding: false)
UserDefaults.standard.set(data, forKey: "dict")

But when I try to retrieve it:
if let data2 = defaults.object(forKey: "dict") as? NSData {
let dict = NSKeyedUnarchiver.unarchivedObject(ofClasses: [Int:[Int:Int]], from: data2)
print(dict)
}

I get an error: Cannot convert value of type '[Int : [Int : Int]].Type' to expected argument type '[AnyClass]' (aka 'Array')
Is there a way to store a [Int:[Int:Int]] Dictionary in UserDefaults? Or I have to use other aproach?

A: You can simply use JSONEncoder and JSONDecoder to do the encoding, since Dictionary<Int,Dictionary<Int,Int>> conforms to Codable.
var dict = [Int:[Int:Int]]()
dict[1] = [4:3]
dict[10] = [5:10]

let encodedDict = try! JSONEncoder().encode(dict)

UserDefaults.standard.set(encodedDict, forKey: "dict")
let decodedDict = try! JSONDecoder().decode([Int:[Int:Int]].self, from: UserDefaults.standard.data(forKey: "dict")!) //[10: [5: 10], 1: [4: 3]]

Don't use force unwrapping when working with real values rather than these hard coded ones.

A: I tried with swift 4.1, And following method worked fine.
    var dict = [Int:[Int:Int]]()
    dict[1] = [4:3]
    dict[10] = [5:10]

    let data = try NSKeyedArchiver.archivedData(withRootObject: dict)
    UserDefaults.standard.set(data, forKey: "dict")

Retrieving:
    if let data2 = UserDefaults.standard.object(forKey: "dict") as? Data {
        let dict = NSKeyedUnarchiver.unarchiveObject(with: data2)
        if let dic = dict as? [Int:[Int:Int]] { print(dic) }
    }


text:
Q: Creating Toggle button dynamically inside a Table using Javascript I want to create a toggle button inside a new row which is created using javascript.
Here is my code
<?php
session_start();
?>
<?php require_once 'dbconnection.php'; ?>

<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<title>Training Attendance form</title>
<link rel="stylesheet" href="logincss.css">

<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">

Training Attendance form

<form class="form-horizontal" action="" method="post" id="loginform"
enctype="multipart/form-data">

 Trainer Name

 <input readonly class="form-control" id="trainername" name="trainername" value="">

 Training Name

 <input readonly class="form-control" id="trainingname" name="trainingname" value="">

 Date

 <input type="date" class="form-control" id="trainingdate" name="trainingdate" value="" onfocus="(this.type='date')" onfocusout="(this.type='text')">

 Time
 From

 <input type="time" class="form-control" id="fromtime" name="fromtime"
placeholder="Pick here">

 To

 <input type="time" class="form-control" id="totime" name="totime" value=""
placeholder="Pick here" >

 Venue

 <input type="text" class="form-control" id="venue" name="venue" value="">

<link  rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<?php
       //session_start();
//echo $_SESSION['year'];

mysql_select_db ("training_db");
$sql = "select * from training_nominated";
   $result = mysqli_query($connect,$sql);
   $num=mysqli_num_rows($result);
?>

    Empid
    Name
    Email ID
    Nominated and invited
    Attendance

        <?php $sno=0; while ($row = mysqli_fetch_assoc($result))
          {?>

          <?php echo $row['emp_code']?>
          <?php echo $row['emp_name']?>
          <?php echo $row['emp_mailid']?>
          <input type="text" name="nomination[]" class="form-control">

           <input type="checkbox"  id="attendance" name="attendance[]" data-toggle="toggle" data-on="Yes" data-off="No">

         <?php }?>


text:
Q: Iterated Conditional Mode approximation in E step of EM I wanted to know what is the mathematical justification for using ICM as an approximation for the E step in an EM algorithm.
As I understand in the E step the idea is to find a distribution that is equal to the posterior distribution of the latent variable, which guarantees that the likelihood increases or find the best possible distribution from some simpler family of distributions which guarantees that a lower bound of the likelihood functions increases.
How does one mathematically justify the use of ICM in such an E-step? Any reference/derivations/notes would be very helpful.
Thanks for your help.


text:
Q: Applying time.sleep on each element of a python list I want to independently iterate elements of a list in a marathon-like formation, such that each lane/element can move at a random/varied pace.
In order to still be able to access each element by index, I tried the following code:
cyclists = ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']            #each elements represent an athlete

choose_athlete = random.choices((range(len(cyclists))), k=len(cyclists))    # index select athlete from elements/lane
################################################################
def circular_shifts(runners, step=1):
    step %= min(len(e) for e in runners)
    return [e[step:] + e[:step] for e in runners]

for laps in range(10):
    for i in range(len(cyclists)):
        cycling = circular_shifts(cyclists, i)
        print(cycling)

#Problem:::
#is there a way I can apply the concept of time.sleep to each element as they loop so I can determine their speed of running, i.e while lane1/element[0] is looping fast, lane2 is slower, and so on?
Another example:
cyclists = ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']            #each elements represent an athlete

for i in range(5):
    for aa in cyclists[0]:
        time.sleep(0)
        print(aa)

    for bb in cyclists[1]:
            time.sleep(0.1)
            print(bb)

    for cc in cyclists[1]:
            time.sleep(0.2)
            print(cc)

    for dd in cyclists[1]:
            time.sleep(0.3)
            print(dd)

    for ee in cyclists[0]:
        time.sleep(0.4)
        print(ee)

But this approach print separately, instead, i want the output to still show up together as list so i can access them with index ([0:4])
Preferred output:
['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']
['bcdea', 'ghijf', 'lmnok', 'qrstp', 'vwxyu']
['cdeab', 'hijfg', 'mnokl', 'rstpq', 'wxyuv']
['deabc', 'ijfgh', 'noklm', 'stpqr', 'xyuvw']
['eabcd', 'jfghi', 'oklmn', 'tpqrs', 'yuvwx']
['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']
['bcdea', 'ghijf', 'lmnok', 'qrstp', 'vwxyu']
['cdeab', 'hijfg', 'mnokl', 'rstpq', 'wxyuv']
['deabc', 'ijfgh', 'noklm', 'stpqr', 'xyuvw']
['eabcd', 'jfghi', 'oklmn', 'tpqrs', 'yuvwx']

A: The way this was set up was a bit too confusing to me, so I coded up my own version of how a race could happen using time.sleep. I tried to add lots of comments to explain all the steps:
import time

runners = [
    {'name':'Samantha', 'speed':3.5, 'distance_traveled':0},
    {'name':'Ben',      'speed':2.9, 'distance_traveled':0},
    {'name':'Luis',     'speed':1.8, 'distance_traveled':0},
    {'name':'Jane',     'speed':2.2, 'distance_traveled':0}
    ]
# each elements represent an athlete. Their name and their speed. Also 'distance traveled' tracker
# let's set the speed to be units (m/s). The distance traveled is measured in (m)

# initialize a "finish line" which registers when the distance traveled is enough to win
finish_line = 30    # Distance required to win.             Units of (m)
time_tracker = 0    # Total time elapsed.                   Units of (s)
time_delta = 1      # Change in time for each iteration.    Units of (s)

# fun printing stuff
print("And we're off! Here's the standings: ")

# "while some of the athletes have not finished yet"
while any(i['distance_traveled'] < finish_line for i in runners):
    # we can use time.sleep with a while loop to register the race for each second.

    # update the distance traveled for each runner
    for r in runners:
        r["distance_traveled"] += r["speed"]*time_delta

    # sort the runners dict depending on who's in first place, etc.
    runners = sorted(runners, key=lambda d: d['distance_traveled'], reverse=True)

    print(f"\nAt time {time_tracker}s the current standings are:")
    for place, r in enumerate(runners):
        print(f'{place+1}.: {r["name"]} at {r["distance_traveled"]:.1f}m')

    time_tracker += time_delta
    time.sleep(time_delta)

There's a lot of stuff I haven't added such as:

*

*Changing speeds of runners as they run. Decide speeds randomly?

*Declaring winners when they cross the finish line.

*Other environmental factors such as wind or conditions?

Hopefully this helps! Have fun!


text:
Q: CDF on non-standardized t distribution What is the cumulative distribution function of the non-standardized student's t distribution in terms of inverse scaling parameter? I have found a number of related equations online, but not this one specifically. According to Wikipedia, the PDF in this form is:
$$
p\left(x \middle| v, \mu, \lambda\right) = \frac{\Gamma\left(\frac{v+1}{2}\right)}{\Gamma\left(\frac{v}{2}\right)}\left(\frac{\lambda}{\pi{}v}\right)^{\frac{1}{2}}\left(1+\frac{\lambda\left(x-\mu\right)^2}{v}\right)^{-\frac{v+1}{2}}
$$


text:
Q: Appearance of drawn circle on the apple watch is not smooth enough. How can I do it better? One approach I tried is the following:
let circle = Circle.init()
let path = circle.path(in: kServiceRightFrame)
let serviceRightPath = UIBezierPath.init(cgPath: path.cgPath)
serviceRightPath.lineWidth = 2.0
serviceRightPath.fill()
serviceRightPath.stroke()

I played around with flatness too, but that did not get the job done either. How can a smoother looking circle be drawn programmatically?
EDIT:A more extensive view of my code:
 UIGraphicsBeginImageContext(kWatchInterfaceSize)
 let context = UIGraphicsGetCurrentContext()

 //draw service path
 kSBScoreLabelFontColor.setStroke()
 kSBServiceBallColor.setFill()
 ---> code from above

 // Convert to UIImage
 let cgimage = context!.makeImage()

 //create scoreboardimage
 let scoreBoardImage = UIImage(cgImage: cgimage!)

  // End the graphics context'
  UIGraphicsEndImageContext()

A: George put me on the right track. It was a scaling issue. The code that I changed was the following:
//Replaced this
//UIGraphicsBeginImageContext(kWatchInterfaceSize)
//with this
UIGraphicsBeginImageContextWithOptions(kWatchInterfaceSize,
false, 4.0)

That fixed it. Now the circle looks a lot smoother in appearance.


text:
Q: Calling class in Jmeter Beanshell I want to call method in beanshell sampler from other beanshell sampler. The best way is to call from external jar but is it possible to interaction with each other.

A: There is bsh.shared namespace which can be used for sharing variables and more complex objects, i.e.

*

*In first sampler you can do something like:
MyClass someClass = new MyClass();
bsh.shared.someClass = someClass();

*In second sampler you can refer the instance of the class like:
MyClass someClass = bsh.shared.someClass();
someClass.someUsefulFunction();

Also be aware that since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting so you might want migrate to Groovy.
JSR223 Test Elements don't have access to this bsh.shared namespace but you can use props shorthand for this purpose:

*

*In first sampler:
MyClass someClass = new MyClass();
props.put("someClass", someClass);

*In second sampler:
MyClass someClass = props.get("someClass");
//etc.


text:
Q: Break row in colnames When plotting column headers is there a way to break the text so it appears in two rows?
x <- runif(n = 15, min = 1, 10)
y <- runif(n = 15, min = 1, 10)
z <- runif(n = 15, min = 1, 10)
w <- runif(n = 15, min = 1, 10)
k <- runif(n = 15, min = 1, 10)

df_exemplo <- data.frame(x, y, z, w, k)
colnames(df_exemplo) <- c("Previsto ARIMA", "Previsto Holtwinters", "Observado", "Erro ARIMA (%)", "Erro Holtwinters (%)")

Example:
From
Previsto Arima      |        Previsto Holtwinters
To
Example


text:
Q: Proper way to sort a backbone.js collection on the fly I can successfully do this:
App.SomeCollection = Backbone.Collection.extend({
  comparator: function( collection ){
    return( collection.get( 'lastName' ) );
  }
});

Which is nice if I want to have a collection that is only sorted by 'lastName'. But I need to have this sorting done dynamically. Sometimes, I'll need to sort by, say, 'firstName' instead.
My utter failures include:
I tried passing an extra variable specifying the variable to sort() on. That did not work. I also tried sortBy(), which did not work either. I tried passing my own function to sort(), but this did not work either.  Passing a user-defined function to sortBy() only to have the result not have an each method, defeating the point of having a newly sorted backbone collection.
Can someone provide a practical example of sorting by a variable that is not hard coded into the comparator function? Or any hack you have that works? If not, a working sortBy() call?

A: This is an old question but I recently had a similar need (sort a collection based on criteria to be supplied by a user click event) and thought I'd share my solution for others tackling this issue.  Requires no hardcoded model.get('attribute').
I basically used Dave Newton's approach to extending native JavaScript arrays, and tailored it to Backbone:
MyCollection = Backbone.Collection.extend({

    // Custom sorting function.
    sortCollection : function(criteria) {

        // Set your comparator function, pass the criteria.
        this.comparator = this.criteriaComparator(criteria);
        this.sort();
    },

    criteriaComparator : function(criteria, overloadParam) {

        return function(a, b) {
            var aSortVal = a.get(criteria);
            var bSortVal = b.get(criteria);

            // Whatever your sorting criteria.
            if (aSortVal < bSortVal) {
                return -1;
            }

            if (aSortVal > bSortVal) {
                return 1;
            }

            else {
                return 0;
            }

        };
    }

});

Note the "overloadParam".  Per the documentation, Backbone uses Underscore's "sortBy" if your comparator function has a single param, and a native JS-style sort if it has two params.  We need the latter, hence the "overloadParam".

A: Interesting question. I would try a variant on the strategy pattern here. You could create a hash of sorting functions, then set comparator based on the selected member of the hash:
App.SomeCollection = Backbone.Collection.extend({
    comparator: strategies[selectedStrategy],
    strategies: {
        firstName: function () { /* first name sorting implementation here */ },
        lastName: function () { /* last name sorting implementation here */ },
    },
    selectedStrategy: "firstName"
});

Then you could change your sorting strategy on the fly by updating the value of the selectedStrategy property.
EDIT: I realized after I went to bed :) that this wouldn't quite work as I wrote it above, because we're passing an object literal to Collection.extend. The comparator property will be evaluated once, when the object is created, so it won't change on the fly unless forced to do so. There is probably a cleaner way to do this, but this demonstrates switching the comparator functions on the fly:
var SomeCollection = Backbone.Collection.extend({
    comparator: function (property) {
        return selectedStrategy.apply(myModel.get(property));
    },
    strategies: {
        firstName: function (person) { return person.get("firstName"); },
        lastName: function (person) { return person.get("lastName"); },
    },
    changeSort: function (sortProperty) {
        this.comparator = this.strategies[sortProperty];
    },
    initialize: function () {
        this.changeSort("lastName");
        console.log(this.comparator);
        this.changeSort("firstName");
        console.log(this.comparator);
    }
});

var myCollection = new SomeCollection;

Here's a jsFiddle that demonstrates this.
The root of all of your problems, I think, is that properties on JavaScript object literals are evaluated immediately when the object is created, so you have to overwrite the property if you want to change it. If you try to write some kind of switching into the property itself it'll get set to an initial value and stay there.
Here's a good blog post that discusses this in a slightly different context.

A: Looking at the source code, it seems there's a simple way to do it, setting comparator to string instead of function. This works, given Backbone.Collection mycollection:
        mycollection.comparator = key;
        mycollection.sort();

A: Change to comparator function by assigning a new function to it and call sort.
// Following example above do in the view:

// Assign new comparator
this.collection.comparator = function( model ) {
  return model.get( 'lastname' );
}

// Resort collection
this.collection.sort();

// Sort differently
this.collection.comparator = function( model ) {
  return model.get( 'age' );
}
this.collection.sort();

A: So, this was my solution that actually worked.
  App.Collection = Backbone.Collection.extend({

    model:App.Model,

    initialize: function(){
      this.sortVar = 'firstName';
    },

    comparator: function( collection ){
      var that = this;
      return( collection.get( that.sortVar ) );
    }

  });

Then in the view, I have to M-I-C-K-E-Y M-O-U-S-E it like this:
this.collections.sortVar = 'lastVar'

this.collections.sort( this.comparator ).each( function(){
  // All the stuff I want to do with the sorted collection...
});

Since Josh Earl was the only one to even attempt a solution and he did lead me in the right direction, I accept his answer.  Thanks Josh :)

A: This is what I ended up doing for the app I'm currently working on. In my collection I have:
comparator: function(model) {
    var methodName = applicationStateModel.get("comparatorMethod"),
        method = this[methodName];
    if (typeof(method === "function")) {
        return method.call(null, model);
    }
}

Now I can add few different methods to my collection: fooSort(), barSort(), and bazSort().
I want fooSort to be the default so I set that in my state model like so:
var ApplicationState = Backbone.Model.extend({
    defaults: {
        comparatorMethod: "fooSort"
    }
});

Now all I have to do is write a function in my view that updates the value of "comparatorMethod" depending upon what the user clicks. I set the collection to listen to those changes and do sort(), and I set the view to listen for sort events and do render().
BAZINGA!!!!


text:
Q: Quantum operator order I have the following quantum mechanical Hamiltonian that the professor wrote down in class:
$$H = p^2 q + q^2p - pq.$$
He asked us to apply this to a wavefunction: $\Psi(q)$. I know that we define $$p = -i \hbar \partial / \partial q. $$
I am getting confused as to how to formally apply now, $H \Psi(q)$, since, the first term, for example would give:
$$H = (-\partial^2 / \partial q^2)q \Psi,$$ and so on...
In other words, what exactly is $$(-\partial^2 / \partial q^2)q~?$$

A: It is
$$-\frac{\partial}{\partial q}\left(\frac{\partial}{ \partial q}\left(q \Psi(q)\right)\right)$$
which is
$$-\frac{\partial}{\partial q} \left( \Psi(q) + q \Psi'(q)\right)$$
where $$\Psi'(q) = \frac{\partial \Psi}{\partial q}$$
You can take it from there.


text:
Q: Find free number in a range I have a range of numbers (say, 20-100). Lets say the following are occupied: 20, 21, 22, 24. 25, 26, 28.
I ask the user how many free numbers he wants. Lets say, he says three numbers. So my output should be 23, 27, 29.
How can I quickly do this with powershell?
Thanks!

A: $range = 20..100
$occupied = 20,21,22,24,25,26,28
$range | where-object {$occupied -notcontains $_} | `
select-object -first (read-host -Prompt "How many free numbers do you need?")

A: You can also use the Compare-Object cmdlet:
compare $range $occupied -PassThru

23
27
29
30
31
...
100


text:
Q: How do I adjust AppleScript in objective-c? As title, I can run the script in the script editor, but the Objective - C program inside out and use it every time you make mistakes, I find the Internet for a long time, tried three calls the method, but to no avail, AppleScript is as follows:
tell application "Numbers"
set thisDocument to open alias "Macintosh HD:Users:csw:Desktop:Folder:ExcelTest.xlsx"
tell thisDocument
    save thisDocument in file "Macintosh HD:Users:csw:Desktop:Folder:NumbersTest10000.numbers"
end tell
close thisDocument

end tell
The methods called in objective-c are as follows:
Method 1:
NSAppleEventDescriptor *eventDescriptor = nil;
NSAppleScript *appleScript = nil;
NSDictionary *errorDict;

NSString *scriptSource = @"tell application \"Numbers\" \r"
"set thisDocument to open alias \"Macintosh HD:Users:csw:Desktop:Folder:ExcelTest.xlsx\" \r"
"set thisFilePath to \"Macintosh HD:Users:csw:Desktop:Folder:NumbersTest10000.numbers\" \r"
"tell thisDocument\" \r"
"save thisDocument in file thisFilePath\" \r"
"end tell\" \r"
"close thisDocument\" \r"
"end tell";

eventDescriptor = [appleScript executeAndReturnError:&errorDict];
if (eventDescriptor)
{
    NSLog(@"%@", [eventDescriptor stringValue]);
}

Method 2:
NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"ExcelToNumbers" ofType:@"scpt"];
NSLog(@"scriptPath:%@", scriptPath);

if (scriptPath)
{
    NSDictionary *errorInfo;
    appleScript = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:scriptPath] error:&errorInfo];
    //perror("script");
    NSLog(@"errorInfo:%@", errorInfo);

    if (appleScript)
    {
        eventDescriptor = [appleScript executeAndReturnError:nil];

        if (eventDescriptor)
        {
            NSLog(@"%@", [eventDescriptor stringValue]);
        }
    }
}

And mothod 3:
NSTask *task = nil;
NSBundle *bundle = [NSBundle mainBundle];
NSString *scriptPath = [bundle pathForResource:@"ExcelToNumbers" ofType:@"scpt" inDirectory:nil];
if (scriptPath) {
    NSArray *array = [NSArray arrayWithObjects:scriptPath, @"hello", nil];
    task = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/osascript" arguments:array];
    NSLog(@"task:%@", task);
}

The first method does not print the error log.
In the second method, the error is:
2018-02-04 14:56:33.343060+0800 Storm[5077:223513] AppleEvents failed to encode extension for /Users/csw/Desktop/Folder/ExcelTest.xlsx, err=Operation not permitted/1
2018-02-04 14:56:35.553607+0800 Storm[5077:223513] AppleEvents failed to encode extension for /Users/csw/Desktop/Folder/ExcelTest.xlsx, err=Operation not permitted/1

In the third method, the error is:
2018-02-04 14:26:02.399776+0800 Storm[4675:205128] task:<NSConcreteTask: 0x6040000e3a00>
2018-02-04 14:26:02.772100+0800 osascript[4678:205194] AppleEvents failed to encode extension for /Users/csw/Desktop/Folder/ExcelTest.xlsx, err=Operation not permitted/1
2018-02-04 14:26:02.779600+0800 osascript[4678:205194] AppleEvents failed to encode extension for /Users/csw/Desktop/Folder/ExcelTest.xlsx, err=Operation not permitted/1
/Users/csw/Library/Developer/Xcode/DerivedData/Storm-dubdmupogfxhyvdftizqofiwkzrn/Build/Products/Debug/Storm.app/Contents/Resources/ExcelToNumbers.scpt: execution error: "Numbers"遇到一个错误:应用程序没有运行。 (-600)

What is the reason for this? It's my AppleScript problem or the method of calling.I can be sure that it's not a path problem, the script file has been added to the project.
Please help me, thank you.


text:
Q: When is it possible to split a non-linear operator into a composition of a linear and local one? Let $A: L^2(R^n)\to L^2(R^n)$ be a non-linear operator. Is it known when it's possible to split $A$ into a composition of a linear operator $B: L^2(R^n)\to (L^2(R^n))^k$ and a local operator $C: (L^2(R^n))^k\to L^2(R^n)$? Are there any techniques to do so?
Edit:
Perhaps I should explain what I am really looking for and why. The question arose from the need to efficiently compute certain functions in $R^2\to R$, based on the input $R^2\to R$ and certain operators. There are basically two approaches to do that in the industry: if the operator is local or has very small support radius then compute locally; if the operator is linear then do FFT (Fourier transform), compute locally, and do inverse FFT.
The question is basically about operators that can be split into a composition something local and spacial domain and something local in the frequency domain.
Sometimes operators are not local at all and not quite linear either, but it is still possible to compute them efficiently. A typical example: compute the slope of the signal given by transmission matrix $f: R^2\to R$ and a linear operator $K: L^2(R^2)\to L^2(R^2)$. Let $g=K\star f$. Although $f\to g$ is linear, and $f\to grad(g)$ is linear, $f\to slope(g)$ is not.
However, non-linearity of the slope never stopped anybody from computing it efficiently: one just perform the computation in two steps:
Step 1: compute $grad(g)$ using FFT: $grad_K: L^2(R^2)\to (L^2(R^2))^2: f\to grad(K\star f)$
Step 2: compute $slope_K(g): (L^2(R^2))^2\to L^2(R^2)$ locally from $grad_K(g)$.
Therefore the question: how far one can extend the above approach? What operators can be split into compositions of a local and a linear one? (Possibly) more generally, what operators can be split into a finite sequence of compositions of local and linear operators?


text:
Q: Пробелма с выбором конкретного делегата в QML Calendar Занимаюсь сейчас с Calendar в QML, при его описании имеется некое поле dayDelegate, в котором описывается то, что будет у нас выступать в качестве квадратика с датой.
В моем случае, я хочу чтобы при нажатии на такой вот день квадратик становился синим и при закрытии сохранял свой цвет, но когда я это делаю синими становятся все квадраты.
Как исправить чтобы квадратик с датой и менял только свой цвет, а не всех?

A: Во-первых, вам нужно разобраться с паттерном MVD, и его реализацией в QML, для этого рекомендую почитать вот эту статью. Реализация цветовой отметки принципиально ничем не отличается от того же списка.
Во-вторых, на сегодня компонент Calendar уже теряет актуальность, поскольку относится к Qt Quick Controls первой версии, а недавно вышла вторая, которая предлагает, например, автоматическое масштабирование на экранах с высокой плотностью пикселов. Так вот, там уже используется компонент MonthGrid.
В третьих, если вам всё-таки нужен Calendar, то при задании стиля делегата поможет таблица со вспомогательными переменными из документации по свойству dayDelegate, которые позволяют регулировать цвет в зависимости от выполнения условий.


text:
Q: Android - How to add image between ActionBar and Tabs?
I would like to insert an image between the ActionBar and ActionBar Tabs. What is the best way do it?
I'm using actionbarsherlock.
Thanks.

A: After doing a bunch of research, I found there is no way to make this work with native ActionBar tabs. So save yourself some time, create your own TabHost and place it below the image. Then implement tabchange listeners, etc.

A: Use a layout above actionbar tab having your image or just take imageview above it.


text:
Q: Page jumps abit up when an element above fades in I have 2 elements, the first one (at the top) has the following CSS properties:
header {
   position: relative;
   height: 100%;
   width: 100%;
   background-color: black;
}

This makes it in the size of the browser's viewport, what I did on purpose because I wanted that result. I also had to give the html, body element the CSS property's for this to work (filling the screen with the first element):
html, body {
   height: 100%;
   width: 100%;
}

The second element I have looks like this:
#content {
    display: none;
    position: relative;
    height: 1500px;
    width: 100%;

    background-color: yellow;
}

This element is underneath the first one.
As you can see, this element is hidden. That's because when I click on the button on the first element (which you can see in the jsFiddle) it shows  the #content element, scrolls to that, and hides the element where we came from (header) when it's done scrolling.
Which works perfectly, I've got the function here:
var showScrollHide = function(showTime, element, eleTime, hide, hideTime, func) {
    var _ele = $(element),
        _hide = $(hide);
    _ele.fadeIn(showTime, function() {
        $('html, body').animate({
            scrollTop: _ele.offset().top
        }, eleTime, function() {
            _hide.fadeOut(hideTime, func ? func : null);
        });
    });
};

I'm calling that function by this piece of code:
$('.exploreBtn').on('click', function() {
    showScrollHide(500, content, 1000, header, 250, function() {
        $(window).scrollTop(0);
        $('.scrollBackBtn').fadeIn();
    });
});

In the snippet above I had to call $(window).scrollTop(0); otherwise it would scroll down the page a bit when it was done scrolling. Also I displayed the scroll back button now, but that is the problem.
When I'm on the second element, and the element above it is hidden by the function above. And I try to use the same function to scroll it back up which means:

*

*Show the element above

*Scroll to it

*Fade out the element we came from

It only gives me a fade to the element I'm trying to scroll to.
When I removed all the code from the function, and only used this:
$('header').fadeIn();

It just did the same and automatically faded the screen to that element we have just faded in. Which means it scrolls up, but not with any animation or what so ever.
Here is a jsFiddle to show what I'm doing
Btw, I already fixed this issue with the help of @Loktar with this piece of code, but I'm still not sure if its the right way to do it:
$('.scrollBackBtn').on('click', function() {
     $(window).scrollTop(0);
    $(header).slideDown();
});

A: If I am understanding it correctly the following should work.
_scrollBackBtn.on('click', function() {
     _window.scrollTop(0);
    $(header).slideDown();
});

Live Demo


text:
Q: Data being send through android app and show on webpage I have an android app that sends data through HttpRequest using JSON format, that data is being received through php webpage, problem is I want to show all the data that is being transmitted through my app on webpage, perhaps in a table...I can insert into the MySQL db but data is being received very fast, and at this instant I just want to show on webpage, which keeps on changing when new data is received...
Hope you all can understand what I mean...
Thanks

A: If I understand what you mean, you can use websocket, to display changing in realtime.


text:
Q: Nginx redirect image to the post It is possible to redirect with nginx like :
http://mydomain.com/users/image/9999-some-word-some-word-some-word.f3fd78ba6853a5be0c9caf5517429b15.jpg
to http://mydomain.com/node/9999

A: well I guess you can try something like
location /users/image/([0-9]+) {
    try_files /node/$1.jpg =404;
}

or
Not sure about the rewrite exactly but it should be close to something like this
location /users/image/ {
    rewrite /users/image/([0-9]+).* /users/image/$1.jpg;
}


text:
Q: How to parse a date? I am trying to parse this date with SimpleDateFormat and it is not working:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Formaterclass {
    public static void main(String[] args) throws ParseException{
        String strDate = "Thu Jun 18 20:56:02 EDT 2009";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date dateStr = formatter.parse(strDate);
        String formattedDate = formatter.format(dateStr);
        System.out.println("yyyy-MM-dd date is ==>"+formattedDate);
        Date date1 = formatter.parse(formattedDate);

        formatter = new SimpleDateFormat("dd-MMM-yyyy");
        formattedDate = formatter.format(date1);
        System.out.println("dd-MMM-yyyy date is ==>"+formattedDate);
    }
}

If I try this code with strDate="2008-10-14", I have a positive answer. What's the problem? How can I parse this format?
PS. I got this date from a jDatePicker and there is no instruction on how modify the date format I get when the user chooses a date.

A: The problem is that you have a date formatted like this:
Thu Jun 18 20:56:02 EDT 2009

But are using a SimpleDateFormat that is:
yyyy-MM-dd

The two formats don't agree.  You need to construct a SimpleDateFormat that matches the layout of the string you're trying to parse into a Date.  Lining things up to make it easy to see, you want a SimpleDateFormat like this:
EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009

Check the JavaDoc page I linked to and see how the characters are used.

A: We now have a more modern way to do this work.
java.time
The java.time framework is bundled with Java 8 and later. See Tutorial. These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They are a vast improvement over the troublesome old classes, java.util.Date/.Calendar et al.
Note that the 3-4 letter codes like EDT are neither standardized nor unique. Avoid them whenever possible. Learn to use ISO 8601 standard formats instead. The java.time framework may take a stab at translating, but many of the commonly used codes have duplicate values.
By the way, note how java.time by default generates strings using the ISO 8601 formats but extended by appending the name of the time zone in brackets.
String input = "Thu Jun 18 20:56:02 EDT 2009";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "EEE MMM d HH:mm:ss zzz yyyy" , Locale.ENGLISH );
ZonedDateTime zdt = formatter.parse ( input , ZonedDateTime :: from );

Dump to console.
System.out.println ( "zdt : " + zdt );

When run.

zdt : 2009-06-18T20:56:02-04:00[America/New_York]

Adjust Time Zone
For fun let's adjust to the India time zone.
ZonedDateTime zdtKolkata = zdt.withZoneSameInstant ( ZoneId.of ( "Asia/Kolkata" ) );

zdtKolkata : 2009-06-19T06:26:02+05:30[Asia/Kolkata]

Convert to j.u.Date
If you really need a java.util.Date object for use with classes not yet updated to the java.time types, convert. Note that you are losing the assigned time zone, but have the same moment automatically adjusted to UTC.
java.util.Date date = java.util.Date.from( zdt.toInstant() );

A: You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.
To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):
SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");

Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.
        String input = "Thu Jun 18 20:56:02 EDT 2009";
        SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
        Date date = parser.parse(input);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = formatter.format(date);

        ...

JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

A: How about getSelectedDate? Anyway, specifically on your code question, the problem is with this line:
new SimpleDateFormat("yyyy-MM-dd");

The string that goes in the constructor has to match the format of the date. The documentation for how to do that is here. Looks like  you need something close to "EEE MMM d HH:mm:ss zzz yyyy"

A: In response to:
"How to convert Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México)) to dd-MM-yy in Java?", it was marked how duplicate
Try this:
With java.util.Date, java.text.SimpleDateFormat, it's a simple solution.
public static void main(String[] args) throws ParseException {

    String fecha = "Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México))";
    Date f = new Date(fecha);

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    sdf.setTimeZone(TimeZone.getTimeZone("-5GMT"));
    fecha = sdf.format(f);
    System.out.println(fecha);
}


text:
Q: Passing username and password to CryptRetrieveTimeStamp function I'm trying to retrieve a timestamp from a TSA using CryptRetrieveTimeStamp.
I can get it from some of the free services found on this answer, but always using the TIMESTAMP_NO_AUTH_RETRIEVAL flag.
But now that I want to use a paid service that uses credentials I cannot figure it out how to get it using a username and a password.
Does anyone know how to send a username and password to a TSA using CryptRetrieveTimeStamp?

A: I haven't tried to do this myself, but have you tried putting them in the URL? Something like:
https://username:password@server.domain.com/ts/

I'd be curious to know if that works. Currently we're using free timestamping servers, but you never know.
By the way: I see you tagged your post with RFC 3161. Does that mean CryptRetrieveTimeStamp works with RFC 3161 timestamp servers? The documentation is marvelously unclear. I'm going to try it as soon as I get a chance, but it's always worth asking.


text:
Q: RSS reader for iPhone with text-to-speech support? I have been using gReader for Android for a long time. Now, I would like to switch to iPhone and I need a replacement for this app.
Is there any RSS reader for iPhone that converts text-to-speech?

A: For RSS, I use Reeder 3, but you can probably use your favourite app, because…
iOS has built-in text-to-speech support system-wide for selectable or unselectable text.
Method 1: Select text and speak it
Open Settings → General → Accessibility → Speech and enable Speak Selection.

A Speak button will appear when you select text.

In an app like Reeder, hold down on the text, make a selection or choose Select All, then tap Speak.

Method 2: Speak all text
Open Settings → General → Accessibility → Speech and enable Speak Screen.

Swipe down with two fingers form the top of the screen to hear the content of the screen.

A HUD appears for controlling speech, which hide automatically or with the left arrow and unhidden with the right arrow.


text:
Q: Transformation to show mean, st.dev from dataset in python I have a dataset, df, where I would like to show the mean and st deviation comparisons across groups while keeping the id, start, end and value columns in the output.
id  start       end         value

a   5/1/2020    6/1/2020    2
a   6/1/2020    7/1/2020    3
a   7/1/2020    8/1/2020    4
a   8/1/2020    9/1/2020    20
b   5/1/2020    6/1/2020    15
b   6/1/2020    7/1/2020    2
b   7/1/2020    8/1/2020    1

Desired output
id  start       end         value   mean    stdev       1SD       2SD     3SD

a   5/1/2020    6/1/2020    2
a   6/1/2020    7/1/2020    3
a   7/1/2020    8/1/2020    4
a   8/1/2020    9/1/2020    20      29      8.539126    20.5      12     -5.5
b   5/1/2020    6/1/2020    15
b   6/1/2020    7/1/2020    2
b   7/1/2020    8/1/2020    1       18      7.81025     10.2      2.4    -5.4

The desired output, groups the id, as well as the value and finds the
mean, standard deviation and the 1SD, 2SD, and 3SD
This is what I am doing:
df = pd.read_csv("data.csv")

output = df.groupby('id')['value'].agg(['mean','std'])

output['1SD'] = output['mean'] - output['std']

output['2SD'] = output['mean'] - 2 *output['std']

output['3SD'] = out['mean'] - 3 *output['std']

However, I was not able to retain the start, end and value columns. I am still researching and any
suggestion is appreciated.

A: Use GroupBy.transform here:
g = output.groupby('id')['value']
output['mean'] = g.transform('mean')
output['std'] = g.transform('std')

output['1SD'] = output['mean'] - output['std']
output['2SD'] = output['mean'] - 2 *output['std']
output['3SD'] = out['mean'] - 3 *output['std']

If need only one row per group add Series.duplicated for match only last duplicated rows:
mask = ~df['id'].duplicated(keep='last')
g = output.groupby('id')['value']
output.loc[mask, 'mean'] = g.transform('mean')
output.loc[mask, 'std'] = g.transform('std')

output['1SD'] = output['mean'] - output['std']
output['2SD'] = output['mean'] - 2 *output['std']
output['3SD'] = output['mean'] - 3 *output['std']

print (output)
  id     start       end  value  mean       std       1SD       2SD        3SD
0  a  5/1/2020  6/1/2020      2   NaN       NaN       NaN       NaN        NaN
1  a  6/1/2020  7/1/2020      3   NaN       NaN       NaN       NaN        NaN
2  a  7/1/2020  8/1/2020      4   NaN       NaN       NaN       NaN        NaN
3  a  8/1/2020  9/1/2020     20  7.25  8.539126 -1.289126 -9.828251 -18.367377
4  b  5/1/2020  6/1/2020     15   NaN       NaN       NaN       NaN        NaN
5  b  6/1/2020  7/1/2020      2   NaN       NaN       NaN       NaN        NaN
6  b  7/1/2020  8/1/2020      1  6.00  7.810250 -1.810250 -9.620499 -17.430749


text:
Q: How to treat unhandled thread-exceptions in ASP.NET? How is an ASP.NET application supposed to deal with unhandled exceptions which are occuring on a non-request background thread (due to bugs)?
By default, such exceptions cause the process to terminate. This is unacceptable in the setting of an ASP.NET worker process because concurrently running requests are aborted unpredictably. It is also a performance problem.
Exceptions on a request thread are not a problem because ASP.NET handles them (by showing an error page).
The AppDomain.UnhandledException event allows to observe that an exception has occurred, but termination cannot be prevented at that point.
Here is a repro which needs to be pasted into an ASPX page codebehind.
protected void Page_Load(object sender, EventArgs e)
{
    var thread = new Thread(() =>
        {
            throw new InvalidOperationException("some failure on a helper thread");
        });
    thread.Start();
    thread.Join();
}

The only solution I know of is to never let an exception "escape" unhandled. Is there any other, more global and thorough solution for this?

A: Rx (Reactive Programming) was born to solve issues like this, try to consider changing the framework you currently use and replace it with Rx
http://msdn.microsoft.com/en-us/data/gg577609.aspx
The Nugget packages:
https://nuget.org/packages/Rx-Main/1.0.11226
This is the equivalent Rx code:
        var o = Observable.Start(() => { throw new NotImplementedException(); });

        o.Subscribe(
            onNext => { },
            onError => { },
            () => { Console.WriteLine("Operation done"); });

As you can see the error won't escape the background thread when you specify a handler for the error, onError => { }
If you do not specify an error handler, the exception will be propagated:
        o.Subscribe(
            onNext => { },
            () => { Console.WriteLine("Operation done"); });

In the example above, the exception will be propagated and will cause the same problems as your posted code

A: You can mark the exception as handled in an unhandled exception handler.
https://msdn.microsoft.com/en-us/library/system.windows.applicationunhandledexceptioneventargs.handled(v=vs.95)
That should prevent the worker process from recycling because of an error on the background thread.
You wouldn't do that for all exceptions though. Just the ones you know are safe to ignore.

A: I think "legacyUnhandledExceptionPolicy" option is your answer.
Unhandled exceptions causing ASP.NET to crash in .NET 2.0
; http://blogs.msdn.com/b/tom/archive/2007/12/04/unhandled-exceptions-causing-asp-net-to-crash-in-net-2-0.aspx


text:
Q: backtick in Perl printing output on terminal I am trying to get the output of a command in a variable and checking whether its matching with other variable.
   $login1=`ssh ****************** date`;

This command when typed manually will expect a prompt " Password: " . When i run it from the script it is ruuning that command and printing that prompt waiting for user to enter, but i dont need that. I just need to get that output and compare
     if($login1=~ /Password:/)
            {
              print " yes";
            }
         else
              {
                print "No ";
               }

However the script is just stopping at Password prompt . Please suggest me on how to achieve this .

A: You might want to look at the -f flag for ssh:

 -f      Requests ssh to go to background just before command execution.
         This is useful if ssh is going to ask for passwords or
         passphrases, but the user wants it in the background.  This
         implies -n.  The recommended way to start X11 programs at a
         remote site is with something like ssh -f host xterm.

If you want to avoid passwords, set up a public/private key pair with no passphrase (dangerous, but much less dangerous than putting a password in a script) and copy the public key to the remote site. IIRC, it goes something like this:
localhost $ ssh-keygen -b 2048 -t ecdsa -N '' -f ./datekey
localhost $ scp ./datekey.pub remotehost:/tmp
localhost $ ssh remotehost
(login)
remotehost $ cat /tmp/datekey.pub >> ~/.ssh/authorized_keys
remotehost $ logout

localhost $ ssh -i ./datekey remotehost date

Make sure you store ./datekey somewhere no other user can access it at all -- not even read access.

If you're just trying to detect, you might simply need to feed it EOF to get it to move along:
$login1=`ssh ****************** date < /dev/null`;


text:
Q: using texlive 2013 and 2014 in parallel I installed texlive 2014 but it broke things I need to finish a book (pgf related things). I still have an texlive 2013 backup and reconstructed the directory. Question: How can I switch to texlive 2013 while keeping the 2014 installation?

A: I found out that there should be a preference pane in Mac OS that can be used. However, this is broken in my system. However, replacing the symbolic link to texlive-2014 does the trick:
cd /Library/TeX/Distributions/.DefaultTeX
sudo rm Contents
sudo ln -s ../TeXLive-2013.texdist/Contents

A: In MacOs System, the Preferences Panes has a panel "TeX Live Distribtuion" which allows you to switch between distribution.


text:
Q: Unable to Install Guard I've seen Guard and it's usefulness in web development and would like to install it. Naturally, I expected to be able to use sudo gem install guard to do so (yes, it is a Ruby Gem). However the installation errors out. Here is what I'm getting:
Building native extensions.  This could take a while...
ERROR:  Error installing guard:
    ERROR: Failed to build gem native extension.

        /usr/bin/ruby1.9.1 extconf.rb
/usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- mkmf (LoadError)
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from extconf.rb:4:in `<main>'

Gem files will remain installed in /var/lib/gems/1.9.1/gems/ffi-1.9.3 for inspection.
Results logged to /var/lib/gems/1.9.1/gems/ffi-1.9.3/ext/ffi_c/gem_make.out

Does anyone know how I can fix this? Thanks for any help.

A: I figured out my problem. After looking at the error, I realised the problem was that mkmf was not installed. To fix this, I ran the command, sudo apt-get install ruby1.9.1-dev. After that, everything worked like a charm.

A: Download Guard via Mozilla and then install.
Option 2. Try to update again sudo apt-get update          Then sudo apt-gem-update       Then try sudo gem-get install guard
( or sudo gem install guard )


text:
Q: Визуализация сортировки по шагам Я делаю визуализатор сортировки на c++, можно ли используя обычные алгоритмы сортировки пошагово отсортировать массив, т.е. после одного шага прорисовывается один кадр.

A: Да, можно.
Берите код любого алгоритма сортировки и после каждого обмена значений рисуйте состояние (с паузой и подсветкой обменяшихся элементов, если вам нужно).


text:
Q: Regular expression for inserting span tags I need a regular expression for the replacement of a string into below wrapper format.
Example input:
C# Regular expression for combination of space, alpha and special-character. Also for delta

Output:
C# Regular expression for combination of space, alpha and special-character. Also for delta

A: You could use this replace call:

var txt = "C# Regular expression for combination of space, alpha and special-character. Also for delta";

var result = txt.replace(/[\w#]+\s*|[^\w#]+\s*/g, "$&\n");

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: xml tag optional with vba excel I would like to optionally show a parameter under a specific condition in my worksheet. I have these data :
orange 1
apple 2
I used the "Source" from the Developer ribbon, to make an xml map that associate with the parameters' values.
Thus I generate the following tree:
<orange>1</orange>
<apple>2</apple>

However, the apple value is optional. Sometimes it will not appear in my table. As a result I have the following problem:
<orange>1</orange>
 <apple>

which is not of course an accurate xml file. How can I overcome this? I m using the following macro to load the values and generate the xml.
Sub GenerateXML()
    Dim nameOfFile As String
    nameOfFile = ThisWorkbook.Path & "\" & "sample.xml"

    ActiveWorkbook.SaveAsXMLData Filename:=nameOfFile, _
    Map:=ActiveWorkbook.XmlMaps("my_Map")
End Sub

It's the first time I implement this and it took me a while to figure out how to generate the xml tree correctly. Should I somehow adjust my subroutine to make this optional?


text:
Q: Copy or delete whole tuple from the list with specific item in tuple I want to copy tuples from the list shown below having only a person as the first element of the tuple. How I can do it in efficient way to make it fast.
Also if is it possible to delete all tuples other than person it will also make it fast.
Input list is as below
[('person', '25.15', (515.781005859375, 380.65179443359375, 13.954371452331543, 24.346391677856445)),
('bicycle', '25.47', (213.2113037109375, 459.51116943359375, 13.021369934082031, 27.720993041992188)),
('person', '29.14', (247.71348571777344, 374.4739990234375, 45.45567321777344, 18.036327362060547))]

I want to get the resultant list as below
[('person', '25.15', (515.781005859375, 380.65179443359375, 13.954371452331543, 24.346391677856445)),
('person', '29.14', (247.71348571777344, 374.4739990234375, 45.45567321777344, 18.036327362060547))]

Any help will be appreciated.

A: Assuming your list is called records:
new_records = [record for record in records if record[0]=='person']

This is a compact way of writing:
new_records = []
for record in records:
    if record[0] == 'person':
        new_records.append(record)

A: Using list comprehension should work
Try:
ip = [('person', '25.15', (515.781005859375, 380.65179443359375, 13.954371452331543, 24.346391677856445)),
('bicycle', '25.47', (213.2113037109375, 459.51116943359375, 13.021369934082031, 27.720993041992188)),
('person', '29.14', (247.71348571777344, 374.4739990234375, 45.45567321777344, 18.036327362060547))]

ip = [x for x in ip if x[0] == 'person']
print(ip)

Output:
[('person', '25.15', (515.781005859375, 380.65179443359375, 13.954371452331543, 24.346391677856445)), ('person', '29.14', (247.71348571777344, 374.4739990234375, 45.45567321777344, 18.036327362060547))]

A: data = [('person', '25.15', (515.781005859375, 380.65179443359375, 13.954371452331543, 24.346391677856445)),
('bicycle', '25.47', (213.2113037109375, 459.51116943359375, 13.021369934082031, 27.720993041992188)),
('person', '29.14', (247.71348571777344, 374.4739990234375, 45.45567321777344, 18.036327362060547))]

data = list(filter(lambda x: x[0] == "person", data))

print(data)

I think it will give your desired output


text:
Q: R - sort function changes the matrix I want to sort a column of a matrix according to the rank of the row sums of the other columns. So I use this code:
for(j in 1:d) {
    X[,j]=sort(X[,j],decreasing=TRUE)[rank(rowSums(X[,c(1:d)[-j]]))]
}

But this code changes the values of the column, which I just want to rearrange.
When the row sums are equal, the value of the j-th column becomes equal too, despite the fact that there is every value just once in the original column. An example:
example
How can I avoid this issue?
Thanks

A: Hope this helps!
#sample data
x <- matrix(c(1,1,1,2,2,2,3,3,3), nrow=3, ncol=3, byrow=T)

#if you want to sort by row-sum of 2nd & 3rd column
x[order(rowSums(x[,-1]), decreasing = T),]
#if you want to sort by row-sum of 1st & 2nd column
x[order(rowSums(x[,-3]), decreasing = T),]

So the final looping could be
x <- matrix(c(1,1,1,2,2,2,3,3,3), nrow=3, ncol=3,byrow=T)
X <- x
for(j in 1:ncol(x)) {
  X[,j]=x[order(rowSums(x[,-j]), decreasing = T),j]
}


text:
Q: How to prepare audio files (wav or mp3) for Google speech recognition api in c#?        String jsonRequest = "{\"config\": {\"languageCode\":\"en-US\"},\"audio\": {\"content\": \"" + base64Content+ "\"}}";
        String str = "";
        var speech = SpeechClient.Create();
        var response =
        speech.Recognize(RecognizeRequest.Parser.ParseJson(jsonRequest));
        foreach (var result in response.Results)
        {
            foreach (var alternative in result.Alternatives)
            {
                Console.WriteLine(alternative.Transcript);
                str += alternative.Transcript;
            }
        }

This code is working fine with mono .wav files but it throws exception for stereo files. The exception says

Status(StatusCode=InvalidArgument, Detail="Must use single channel (mono) audio, but WAV header indicates 2 channels.")

So, my question is how can I add support for stereo files? How to convert multi channel audio to a single channel in c#? I have already tried this answer so plz don't refer to it. It is not working.

A: You should take a look into sox which can convert nearly any format into another including sample rate conversion, and in your case interesting, channel conversion. In the documentation you find many examples on how to use it.
In your case I would advise against just extracting one channel from the audio because that could mean that the desired audio is only on another channel which is not selected.
If you want to have full control over the audio you could dive into bass.dll in liaison with bass.net.dll, which allows you to mix channels together or select a specific channel.


text:
Q: CustomTableCellView's implementation of -layoutSubviews needs to call super , NSInternalInconsistencyException On using autoLayout in custom cell for tableView xib, i am getting following error.
When running in iOS 6 simulator
CustomCells's implementation of -layoutSubviews needs to call super
Assertion failure in

-[CustomCells layoutSublayersOfLayer:], /SourceCache/UIKit_Sim/UIKit-2372/UIView
     *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews. CustomCells's implementation of -layoutSubviews needs to call super.'
    *** First throw call stack:

When running in iOS 5 simulator
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'The NIB data is invalid.'
*** First throw call stack:

Temp Fix :
It is working fine if am disabling the autoLayout in custom cell.
But orientation handling is not fine in this case. Please help.

A: layoutSubviews needs to call super

Can be worked around on iOS6 by putting everything in your custom tableview cell in a container view.  ie Create a new view to fill the cell then place controls etc inside that.  Also make sure you set:
[theContainerView setTranslatesAutoresizingMaskIntoConstraints:NO];

for the container and subviews

A: iOS 5.1 and earlier versions are not compatible with AutoLayout. It's only for iOS 6.0+.
Assuming you're using storyboards, if you want to use AutoLayout but still preserve compatibility with iOS versions prior to 6.0, you'll need to create two targets: one for iOS 6 and another for iOS 5 (or earlier). For each, set a separate storyboard, one where AutoLayout is enabled (for iOS 6), and one where it is not (for iOS 5).
Here's a StackOverflow thread for best practices with AutoLayout and backward-compatibility with iOS 5:  Enabling auto layout in iOS 6 while remaining backwards compatible with iOS 5.
In my experience, it's not worth the effort to use AutoLayout if you want backwards compatibility. If you're using storyboards, it's a maintenance headache to have 2 targets and 2 storyboards to synchronize. If you're not using storyboards, you'll need separate code for iOS 5 and iOS 6, which will take longer to test and update.


text:
Q: Accessing the outer function element inside the nested one I have a problem with my code. Because I can't access the list from outer function inside the nested one. I tried nonlocal but it gives me an error "non binding for nonlocal "a" found.
def func(x, y):
        nonlocal a
        nonlocal b
        if x >= 0 and y >= 0:
            if x == 0 and y == 0:
                return (func(x - 1, y - 1) + a[x] * b[y])

            else:
                return max(func(x - 1, y - 1) + a[x] * b[y], func(x - 2, y) + a[x - 1] * a[x], func(x, y-2) + b[y - 1] * b[y])
        elif x >= 1 and y < 0:
            return func(x - 2, y) + a[x - 1] * a[x]

        elif y >= 1 and x < 0:
            return func(x, y-2) + b[y - 1] * b[y]
        else:
            return 0

def tvshows(a, b):

    x = func(len(a) - 1, len(b) -1)
    return x

test_a = [23,45, 12, 16]
test_b = [33,13, 17, 18]

tvshows(test_a, test_b)

Does anyone know what the issue might be?
Best Regards

A: nonlocal requires the variable to have been defined before
I don't see any nested functions in your code. But you can use nonlocal inside the nested function (not the outer function) to reference a previously defined list.


text:
Q: listing the data and the map moving when the data is clicked My title may have made me sound like an idiot.
I just didnt know how to name what I want to do here.
I get the location of individuals data from my database in Json format.
Than using the marker clusterer jQuery plugin, these individuals are pin pointed on the map.
But I really like what they did on this website.
http://www.fetalhope.org/patients-families/treatment?cid=168&x=35&y=14
I will appreciate if you can help me build the same setting.
I am willing to pay as well, but unemployed dont expect much.
I am just trying to learn.
{
  "users": [
    {
      "name": "John Doe",
      "latitude": "22.3430194444444",
      "longitude": "114.110386111111"
    },
    {
      "name": "John Doe",
      "latitude": "48.4048403957642",
      "longitude": "2.68452644348145"
    }
  ]
}

        $(function CheckinMap() {
            $.when($.ajax({
                type: "GET",
                dataType: "json",
                url: "content/sewerage/index.cs.asp?Process=ViewMap"
            })).done(      function initialize(data) {
                var MapData = data;
                var center = new google.maps.LatLng(41.00527, 28.97696);
                var map = new google.maps.Map(document.getElementById('checkinmap'), {
                  zoom: 6,
                  center: center,
                  mapTypeId: google.maps.MapTypeId.ROADMAP,
                  maxZoom: 14
                });
                var markers = [];
                for (var i = 0; i < MapData.users.length; i++) {
                  var location = MapData.users[i];
                  var latLng = new google.maps.LatLng(location.NIDLatitude,
                      location.NIDLongitude);
                  var marker = new google.maps.Marker({
                    position: latLng
                  });
                  markers.push(marker);
                }
                var markerCluster = new MarkerClusterer(map, markers);
            });
        });

A: Depending on the version of the api you are using (the example is for V3) of google maps what you can do is use the listener on the marker and when it's clicked you can get a value, let say an id, that identify the element you want to focus on the list.
So, assuming you have a marker, you can extend it and add your id.
var markerItem = new google.maps.Marker();
markerItem.metadata = {id: 1};

And then you add the event listener:
  google.maps.event.addListener(markerItem, 'click', function () {
            var targetId = markerItem.get("id");
            //do something with the target id like scrolling the desired point of the list

  });

Within the event you can the center the map to the lat/long of the clicked marker, create a new infoWindow and show it etc,,:
var infoWindowItem = new google.maps.InfoWindow({content: 'Some content here!'});
infoWindowItem.open(map, markerItem);


text:
Q: How can I parse Jade templates with PHP, without other dependencies? Given some Jade templates:
base.jade
div.container
    block content

home.jade
extends base
block content
    p Hello World

I want to be able to simply use require to call a component to render them using PHP, for example:
index.php
<?php
    require_once 'jadeParser.php';
    renderJade('home.jade');
?>

output

Hello World

https://github.com/everzet/jade.php seems like a solution, how can I use it without installing Symfony?
I can't configure the server I'm working on, I can't install things via Composer or .phar files. All I can do is add .php files via manual upload.
Is there any solution as simple as the one above?


text:
Q: Как создать свои кнопки управления окнами с помощью QT Designer C++? как сделать свой дизайн кнопок управления окном с помощью QT Designer C++, как реализовано на примере Telegram Desktop?
Дело в том, что не очень нравятся стандартные кнопки управления окном в Windows и Linux  и хотелось бы сделать свои кнопки.
Буду благодарен за ответ. Если уже есть такой же вопрос, на который дан ответ, то скиньте пожалуйста на него ссылку.


text:
Q: Why do we say that someone "practices" law or medicine? I'm wondering why we refer to providing legal or medical services as a practice of law or medicine, respectively. For example, we say that a lawyer practices law or a doctor practices medicine. This makes these fields sound like they're some special art, but what is the historical origin of the usage of the word practice in this context?

A: One of the principle meanings of practice is

the continuous exercise of a profession b : a professional business; especially : one constituting an incorporeal property

This derives no doubt from earlier meanings of systematic performance of a skill or action.
The term is not limited to law and medicine. Consultancies, engineering firms, architects, and many other kinds of professionals also refer to their firms, specialties or lines of business as practices.

A: The word's earliest meaning was, in the OED's definition, 'to pursue or be engaged in (a particular occupation, profession, skill, or art)'. It is first recorded as such in 1421 and that is the meaning it continues to have when we speak of practising (BrEng spelling) law or medicine. At around the same time, it seems to have been used to mean 'to exercise oneself in a skill or art in order to acquire or maintain proficiency, especially in music', but it is not until 1542 that it is recorded as meaning 'to perform (an activity) or exercise (a skill) repeatedly or regularly in order to acquire, improve or maintain proficiency'. That is the meaning it most commonly has today.

A: When there is no definitive way to do something in a particular profession, then it can be referred to as a practice.


text:
Q: Is it possible to add up the accuracy rates of 2 predictors? Weather channel 1 has a 65% accuracy rate of predicting tomorrows weather
Weather channel 2 has a 59% accuracy rate of predicting tomorrows weather

Is it somehow possible to take into account their respective accuracy rates and predictions to somehow make a more accurate predictor?
What would the rates be if the both channels had the same prediction?
What would the rates be if the both channels had different predictions?

What specific topics/subjects cover this particular problem (that of combining different predictors)?

*

*accuracy_rate will be defined in this question to avoid confusion as the
(# of correct predictions / # of total predictions) the channel has made

A: To do this well, you really need to understand the covariance between the two channels.  For example, in the 59% of cases where ch 2 is correct, the probability of channel 1 could be anywhere from 24% (always right when 2 is wrong) to 100% (always right when 2 is right), but I would imagine somewhere in between.
It is tempting to assume there is no correlation, in which case you can simply calculate the odds by multiplying the probabilities of the independent events and dividing by the sum of the probabilities of those which could have been.  For example, $$P(both right) = \frac{P(ch 1 right) * P(ch 2 right)}{ P(channels agree)}$$
$$=\frac{P(ch 1 right) * P(ch 2 right)}{ P(ch 1 right) P(ch 2 right) + P( ch 1 wrong) * P(ch 2 wrong)}$$
$$=\frac{0.65 \cdot 0.59}{0.65 \cdot 0.59 + 0.35 \cdot 0.41}\approx0.728$$
This stands to reason in the sense that it is better (more likely) than either alone when both are better than 50%.
However, considering they are both likely looking at the same radar maps, were instructed on the same techniques during school/training, etc, I find it very hard to believe that these would be independent.


text:
Q: Simple and secure way to display error page with IP address of visitor? With python? Fail2ban is used to block users on certain patterns via reject command.
Sometimes, especially when users are behind a NAT with a lot of users they get blocked unintendely. The user then writes an E-Mail and then I ask for his IP-Address to unblock (often E-Mail is forwarded to me, so I don't have the Mail header with his IP address).
To make this step easier, I'd like to redirect him to a special dynamic webpage that displays its IP-address and contact E-Mail. An example is here:

I'd like to have a similar webpage. An easy solution would be php, but that requires php to be installed and some webserver configuration. So simplest solution would be a small webserver that just serves a small text an IP address.
I've considered using python, because Python is already installed. I've found this article https://www.anycodings.com/1questions/2464569/how-do-i-get-the-client-ip-address-on-a-python-server but that prints the IP-Address only on stdout and serves files.
To use python as simple as with php it would require Flask or Django as far as I found out. However these are big frameworks and much oversized for this simple usecase. Also they probably can mean some security issue. This info page should also be secure by design so not creating any possible security issues compared to reject method. I know DOS is more likely because of more data transmitted than using reject, but size of this page is very small so this would be OK.
So what is an easy solution for this task? Python? If so could you hint some keywords I can search for to achieve this task? Are there other solutions? Maybe these fit even better than the python idea.

A: Found the solution here https://pythonbasics.org/webserver/
So basically you only need to add one line
self.wfile.write(bytes("
IP-Address: " + self.client_address[0] + "
", "utf-8"))
The client_address field is documented here https://docs.python.org/3/library/http.server.html#http.server.BaseHTTPRequestHandler.client_address
So the full code for displaying the IP address of visitor is:
from http.server import BaseHTTPRequestHandler, HTTPServer

listenAddress = "0.0.0.0"
serverPort = 8080

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(bytes("<title>https://pythonbasics.org</title>", "utf-8"))
        self.wfile.write(bytes("
Request: %s
" % self.path, "utf-8"))
        self.wfile.write(bytes("", "utf-8"))
        self.wfile.write(bytes("
This is an example web server.
", "utf-8"))
        self.wfile.write(bytes("
IP-Address: " + self.client_address[0] + "
", "utf-8"))
        self.wfile.write(bytes("", "utf-8"))

if __name__ == "__main__":
    webServer = HTTPServer((listenAddress, serverPort), MyServer)
    print("Server started http://%s:%s" % (listenAddress, serverPort))

    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass

    webServer.server_close()
    print("Server stopped.")


text:
Q: WebStorm and ES6 classes with getters, defined inside a function Trying to use ES6 classes in WebStorm 8/9 and getting this error when I add a getter:

'use strict';

(function () {
  class Collection {
    constructor(resource) {
      this._models = [];
      this._resource = resource;
    }

    fetch() {
      this._models = this._resource.query();
    }

    get models() {
      return this._models;
    }
  }
})();

Moving the class definition outside the anonymous function removes the error, but this isn't an option.
I disabled all inspections and intentions in the preferences. Any ideas how to remove/suppress this message?

A: WEB-13447 is fixed in webStorm 10. Please try WebStorm 10 RC


text:
Q: How to store large data in flutter? My app needs lots of data to display inside the flutter app offline. Previously I stored all the data in List format and looped through them to display items inside app but those data became very huge and exceeded more than 1000 lines and 100KB so I was wondering if it was fine or is there more efficient way to store data inside the app?
Lists Format I used:
const List<String> summaries = [
    "Lots of texts",
    "Another Lots of texts",
     // Lots of other large items
]

const List QnA = [
  [
    {
      'question':'My question?',
      'answer':"""My Answer""",
    },
    {
      'question':'My question?',
      'answer':"""My Answer""",
    }
]
// Lots of list items
];

Thank you!

A: I prefer converting allthose data's to a json format and place it inside asset folder and decoding it.
final data = rootBundle.loadString('assets/text_asset/data.json');

json.decode(data);


text:
Q: VSIX CS0426 The type name Views does not exist in the type 'ABC' I'm creating a VSIX plug-in and just added a WPF control like this:
<UserControl x:Class="ABC.Views.Configuration.MyControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:ABC.Views.Configuration"
             mc:Ignorable="d"
             Loaded="UserControl_Loaded"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
    </Grid>
</UserControl>

When I compile the project I am getting the error:
CS0426  The type name Views does not exist in the type 'ABC'
I've checked the projects' default namespace and other relevant configurations and everything looks good.  In fact, I have other User Controls in the same directory that are compiling just fine.
What am I doing wrong?

A: The root cause of this problem was this line in XAML above:
Loaded="UserControl_Loaded"

For some reason VSIX doesn't like wiring events in XAML.  I simply removed this and wired it up in Code-behind