text:
Q: How can I check if the content of a folder was changed I need a procedure that checks if new folders/files were added to a given selected folder.
I need this procedure to run upon application start up so the processing time at this stage is important.
I guess I can make a log of current state, log of the previous state, sort and compare them.

*

*First I need to know if there is another way.

*Second if there is no other way what is the best way to find difference between two lists of files paths: both structure and algorithms.
Old state:
c:\firstfolder\a.doc
c:\firstfolder\b.doc
c:\firstfolder\secondFolder\a.doc
c:\firstfolder\secondFolder\b.doc

New state:
c:\firstfolder\a.doc
c:\firstfolder\b.doc
c:\firstfolder\secondFolder\a.doc
c:\firstfolder\secondFolder\b.doc
c:\firstfolder\secondFolder\c.doc

I'm looking for c:\firstfolder\secondFolder\c.doc.

A: You can use the FileSystemWatcher class, I think it's doing exactly what you are after.

A: Since your application is not running continuously, using a FileSystemWatcher does not seem like a good option for you, but I did want to mention it since it might spark some ideas on your side.
If you have a list of the old state and create a list of the new state you can use an algorithm like the one outlined here to compare the two lists to determine additions and deletions since the first list was created. That accepted answer to the provided link also has a nice solution that works very well if the lists are not sorted.

A: You can save time info of the last state. Then you just can compare the creation times of files and folders with that. The following code may give you an idea:
foreach(FileInfo f in dir.GetFiles() {
   if(f.CreationTime > dtLastState ) {
         //do some interesting stuff
   }
}

Edit: This is not a complete answer. You cannot get the deleted files by this code.

A: I think the best bet is recursing through the directory and saving the state. Something like this:
public List<FileData> RecurseDirectory(string directory, int level, out int files, out int folders)
        {
            IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
            //long size = 0;
            files = 0;
            folders = 0;
            WIN32_FIND_DATA findData;
            List<FileData> list = new List<FileData>();

            IntPtr findHandle;

            // add global escape chars if not present.
            if (directory.StartsWith(@"\\?\"))
            {
                findHandle = FindFirstFile(directory + @"\*", out findData);
            }
            else
            {
                findHandle = FindFirstFile(@"\\?\" + directory + @"\*", out findData);
            }

            if (findHandle != INVALID_HANDLE_VALUE)
            {
                //if file exists:

                do
                {
                    if ((findData.dwFileAttributes & FileAttributes.Directory) != 0)
                    {
                        //if it's a directory:

                        if (findData.cFileName != "." && findData.cFileName != "..")
                        {
                            //increment folder counter.
                            folders++;

                            int subfiles, subfolders;
                            string subdirectory = directory + (directory.EndsWith(@"\") ? "" : @"\") +
                                findData.cFileName;
                            //Console.WriteLine("Dir:" + subdirectory);

                            //add it to list
                            String path = subdirectory;
                            FileData tempFileData = new FileData();
                            tempFileData.path = path;
                            tempFileData.fileProperties = findData;
                            list.Add(tempFileData);

                            //allows -1 to do complete search.
                            if (level != 0)
                            {
                                //recurse through to next subfolder
                                list.AddRange(RecurseDirectory(subdirectory, level - 1, out subfiles, out subfolders));

                                folders += subfolders;
                                files += subfiles;
                            }
                        }
                    }
                    else
                    {
                        // File
                        files++;
                        string subfile = directory + (directory.EndsWith(@"\") ? "" : @"\") +
                                findData.cFileName;
                        //Console.WriteLine("File:" + subfile);
                        //list.Add("File:" + subfile);
                        String path = subfile;
                        FileData t = new FileData();
                        t.path = path;
                        t.fileProperties = findData;
                        list.Add(t);

                        //size += (long)findData.nFileSizeLow + (long)findData.nFileSizeHigh * 4294967296L;
                    }
                }
                while (FindNextFile(findHandle, out findData));
                FindClose(findHandle);

            }

            return list;
        }

After this, you'll have the list of the state. If you have the old-state in the list also. Compare the lists Now.


text:
Q: Need explanation to call autocompletion for a custom swift struct memberwise initializer in separate file in Xcode I have encountered a small problem but got the solution on my own just recently.
I declared a struct in a separated file in Xcode. Suppose it is Television.swift where the struct Host located inside. But whenever I call the struct for the first time in a separate file, it appears no memberwise initializer in autocompletion.
struct Host {
    var host: Int
}

This happened in a class scope.
If I call the memberwise initializer for the second time inside a class scope, it appears correctly as I desired to be.
Class scope initialization

But, if I call the struct in a function scope, the memberwise show up correctly.
Call initializer in function scope

Does Xcode encourage us to avoid any custom type initialization inside the class in the separate file? Or is there something I've left behind when learn to code in Swift or learn Xcode?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Play Framework Error in Routes file I have the following route that takes in an optional set of parameters:
GET  /data  com.controllers.MyController.data(ids: Option[Seq[Long]])

When I compile the project, I get the following error:
[warn]  ivyScala := ivyScala.value map { _.copy(overrideScalaVersion = true) }
[warn] Run 'evicted' to see detailed eviction warnings
[error] (compile:managedSources) @6plhijkoi: Compilation error in /Users/joe/projects/my-project/conf/routes:26
[error] Total time: 5 s, completed Apr 12, 2016 12:03:55 PM

Line number 26 in my routes file is exactly what I have posted above. Any ideas as to why this error occurs? Is it not possible to have an optional Seq of parameters? The goal is to have one route for the following:
localhost:9000/data           - should fetch all the data
localhost:9000/data?id=1&id=2 - should fetch data with id 1 and 2
localhost:9000/data?id=1      - should fetch data with id 1

Any suggestions?

A: I figured out what the problem is and here is how I managed to get it work:
GET  /data  com.controllers.MyController.data(ids: List[Long])

Notice the datatype, I changed the type from Seq to List and I did not need the Option. So the calls would become:
/data?ids=1&ids=2 - filters based on id 1 and 2
/data             - gets me all the data

A: It might not know how to handle an Option[Seq[Long]]
You could have a router as such:
GET  /data  com.controllers.MyController.data(id1: Option[Long], id2: Option[Long])
Then handle None values in your controller.


text:
Q: How to make an event: click on random area in ListView? If I want to catch events on clicking RMB on Col1 and Col2, and events should be different, is there any chance to do that ?

A: as  @HansPassant said add the mouseup event
void listview1_MouseUp(object sender, MouseEventArgs e)
    {
        ListViewItem item = listview1.GetItemAt(e.X, e.Y);
        ListViewHitTestInfo info = listview1.HitTest(e.X, e.Y);

        if ((item != null) && (info.SubItem != null))
        {
            //item.SubItems.IndexOf(info.SubItem) gives the column index
            MessageBox.Show(item.SubItems.IndexOf(info.SubItem).ToString());
        }
    }

A: Use DataGridView insted of ListView. DataGridView already supports cell click:
    private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        string message = "You have clicked " + (e.ColumnIndex + 1).ToString() + " cell inside " + (e.RowIndex + 1).ToString() + " row!";
        MessageBox.Show(message, "Click info", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

ListView is not ment to be used with tabular data. It's primary use is for lists, good example is Windows Explorer.


text:
Q: How do you install vckpg for Visual Studio Code on Windows? I am trying to install libcurl for my C++ project on VSCode and I came across a method to install via vckpg from this link: How do you properly install libcurl for use in visual studio 2017?
Hence, I looked for the documentation by Microsoft but only found that you can install vckpg for VSCode for Linux and MacOS but I couldn't find anything on how to install vckpg for VSCode on Windows.
Any idea how do you install vckpg for VSCode on Windows? Or is there an alternative method of installing libcurl on VSCode?

A: Currently VS Code does not support vcpkg on Windows.
As mentioned here the following issue is directly connected with VS Code support of vcpkg on Windows: https://github.com/microsoft/vcpkg/issues/10217. The issue is currently open and no workaround is provided.
The support may be provided in the future. Here are the comments from the thread:
ghost: "If there are enough requests, a feature request could be initiated to see what would be needed to integrate with CODE RUNNER and/or a plugin for VSCODE."
strega-nil: "Code Runner is not currently a supported way of building with vcpkg; we may add support eventually, but more likely it should be added by the community (or, even better, vcpkg support should be added to Code Runner). However, we do have features hopefully coming down the pipeline which will make life a lot easier for community members adding that support."

A: Unfortunately i was struggling with the same issue and installing C++ Redistributable which @mutantkeyboard recommended didn't solve the problem.
I installed VS Community Edition with English language pack and now it's OK.


text:
Q: Status 403 Forbidden Error : Microsoft graphs API https://graph.microsoft.com/v1.0/me/onlineMeetings We have to generate an online meeting request from our Dynamics CRM System. We tried using the Microsoft graphs API, and were able to generate the token. However while submitting the request, we get a 403 Forbidden Error.  We have registered our application in Azure and also given the required API permissions.
I have attached the screenshots of our testing. I am testing this on my personal Azure test account.
Screenshots

A: The user has to consent the permission:
Consent experience
Azure AD will sign the user in and ensure their consent for the permissions your app requests.

At this point, the user will be asked to enter their credentials to authenticate with Microsoft. The Microsoft identity platform v2.0 endpoint will also ensure that the user has consented to the permissions indicated in the scope query parameter. If the user has not consented to any of those permissions and if an administrator has not previously consented on behalf of all users in the organization, they will be asked to consent to the required permissions.


text:
Q: Is it possible to upload multiple images via Media Library tab in Thickbox I've created? I have a meta box upload button and I want to upload multiple images using that button.
Firstly I enqueue required scripts:
add_action( 'admin_print_scripts-post-new.php', 'mycpt_admin_script', 11 );
add_action( 'admin_print_scripts-post.php', 'mycpt_admin_script', 11 );

function portfolio_admin_script() {
    global $post_type;
    if( 'mycpt' == $post_type )
    wp_enqueue_script( 'mycpt-script', get_stylesheet_directory_uri() . 'mycpt.js' );
    wp_enqueue_script('media-upload');
    wp_enqueue_script('thickbox');
}

mycpt.js looks like:
jQuery(document).ready(function() {
   jQuery('#cptbutton').click(function() {
       tb_show('', 'media-upload.php?type=image&TB_iframe=true');
       return false;
   });
});

And then I just simply add meta box with this button:
<input id="cptbutton" type="button" value="Upload Image" />

Of course when I click it the Thickbox pops up with:

 Drop files here or
    [ Select Files ]

Plot twist - the files are already on the server (so I don't want to upload them all over again for every other post) and I want to just attach them to current post via Media Library tab:

When I click on any of these above and click "Insert into Post" it just adds one image, and it's over.
How to select multiple images from Media Library? Is it even possible or my logic is wrong and I have to try something else?
In short words - I want to upload / attach images for post's sidebar (it's replacing Featured Images). I'd love to just drag & drop multiple images or select multiple images from Media Library although I have no idea how to do that? I don't want to use Gallery.


text:
Q: Dynamic Bootstrap accordion display issue when first-of-type and last-of-type is the same child When creating Accordion children objects dynamically, in most cases you have multiple children, so first-of-type and last-of-type work great. There is an instance where Accordion only has 1 child. In such case, that 1 child is both first-of-type and last-of-type, causing weird CSS to display (without radius and no bottom border):
.accordion > .card:last-of-type {
    border-top-left-radius: 0;
    border-top-right-radius: 0;
}
.accordion > .card:first-of-type {
    border-bottom: 0;
    border-bottom-right-radius: 0;
    border-bottom-left-radius: 0;
}

How do you fix this issue?

A: Best way to resolve this is to add CSS that will cover 1 child scenario, and undo the previous CSS:
.accordion > .card:first-of-type:last-of-type {
    border-bottom: 1px solid rgba(0, 0, 0, 0.125);
    border-radius: 0.25rem;
}

Make sure this code is placed after bootstrap.css.


text:
Q: Decoding HTTP Audio Stream from Icecast with minimal latency I'm using Icecast to stream live audio from internal microphones and want the listener to have as small a latency as possible.
A naive solution would be to simply access http://myhostname:8000/my_mountpoint to get the stream but the <audio> tag does internal buffering before playing and results in a pretty high latency.
Current solution: I used the ReadableStreams API to decode (using decodeAudioData of Web Audio API) and play chunks of data by routing the decoded data to an Audio Context destination (internal speakers). This works and brings down the latency significantly.
Problem: This streams API, while experimental, should technically work on the latest Chrome, Safari, Opera, FF (after setting a particular flag). I'm however having problems with decodeAudioData in all other browsers except Chrome and Opera. My belief is that FF and Safari cannot decode partial MP3 data because I usually hear a short activation of the speakers when I start streaming. On Safari, the callback on a successful decodeAudioData is never called and FF simply says EncodingError: The given encoding is not supported.
Are there any workarounds if I want to at least get it to work on Safari and FF? Is the decodeAudioData implementation actually different on Chrome and Safari such that one works on partial MP3 and the other doesn't?

A: Don't use Icecast if you need sub-second latency!
Don't use Icecast if you need sub-10-second latency and don't have full control over the whole chain of software and network!
Yes, this is an answer, not a comment. Icecast is not designed for such use cases. It was designed for 1-to-n bulk broadcast of data over HTTP in non-synchronized fashion.
What you are explaining sounds like you really should consider something that was designed to be low latency, like web-RTC.
If you think you really should use Icecast, please explain why. Because your question speaks otherwise. I'm all for more Icecast use, I'm it's maintainer after all, but its application should make sense.

A:
I'm using Icecast to stream live audio from internal microphones and want the listener to have as small a latency as possible.

There are a few issues with your setup that prevent the lowest latency possible:

*

*HTTP Progressive (the type of streaming used by Icecast and similar) runs over TCP, a reliable transport.  If a packet is lost, there is some lag time while it is re-transmitted to the client, before data is delivered to the browser.  This ensures every bit of audio is heard, in-order, but can cause a delay.  For low latency, UDP packets are commonly used so that any lost packets can just be skipped over rather than waited for, causing a glitch, but the client keeps the latency down.

*MP3 isn't a great codec for low latency.  There are better codecs, such as Opus, which are more efficient and can generate smaller segments.

*As you have seen, clients will buffer more by default, when streaming over HTTP.
However, in ideal conditions, I've streamed over HTTP Progressive with less than 250ms latency in Chrome, with a custom server.  I bet you could get similar performance out of Icecast if you turned off the server-side buffering and used a different codec.

I'm however having problems with decodeAudioData in all other browsers except Chrome and Opera. My belief is that FF and Safari cannot decode partial MP3 data

Yes, decodeAudioData() is meant for decoding an entire file.  You'll have a hard time decoding arbitrarily segmented chunks in a sample-accurate way.
Fortunately, there is a method to do what you want... MediaSource Extensions.
https://developer.mozilla.org/en-US/docs/Web/API/Media_Source_Extensions_API
Basically, you can use that exact same ReadableStream interface and push the data to a SourceBuffer to be eventually played out a normal <audio> tag.  This does work with normal MP3 audio from Icecast and similar servers, provided you've worked around any cross-origin issues.

A: As @Brad mentioned, Opus is excellent for low-latency.  I wrote a low-latency WASM Opus decoder that can be used with Streams, and I started another demo that demonstrates how to playback partial files with decodeAudioData():

*

*opus-stream-decoder is production-ready

*fetch-stream-audio
is a non-maintained POC demo that should point you in the right direction.


text:
Q: PHP Can't read cookies? I like to use PHP to see if a cookie PHPSID27258STATUS is present with the value COMPLETE en if so do stuff.
In google chrome (in Options) I can see this cookie is present and has the value COMPLETE.
If I run this PHP script I get 'Not Set'. What am I doing wrong here?
$cookiename="PHPSID27258STATUS";
if (isset($_COOKIE[$cookiename]) && $_COOKIE[$cookiename] == "COMPLETE")

--update
The cookie is set by "limesurvey" an open source survey platform. Although its probably not the best way. I use limesurvey to have a small survey (iframe) on an site i'm building. I like to let the survey disappear on the next visit when it has bin posted.
Limesurvey runs from the same host (localhost now). And is in a sub directory of the site.
I guess (but there's a lot of code in LS) this is how the cookie is made after an poll/post is completed.
$cookiename="PHPSID".returnglobal('sid')."STATUS";
setcookie("$cookiename", "COMPLETE", time() + 31536000); //Cookie will expire in 365 days

A: You can only read cookies which belong to the same domain as the reading script. For instance if the cookie PHPSID27258STATUS was set by domain xyz.com, you can not read it using a script on abc.com. So make sure the domain of your desired cookie is the same. Also show us the code part where you are setting your cookie.
Edit:
setcookie($cookiename, "COMPLETE", (time() + 31536000) , '/');

A: Try setting the cookie with this code:
setcookie("cookiename", "cookievalue", time() + 31536000, "/");

This makes the cookie available to the whole domain, I recently encountered the same issue and when I tried this, it made it work, the reason is, your browser stores cookies for both domain.com and www.domain.com so you never know which your setting and getting from, it's good practice to set the domain even if you don't have this problem.

A: You cannot access a cookie immediately after you set it. At least last time it was like that. Make sure you do not have this issue. If it is not may be you have a problem setting the cookie, and in that case please post that part as well.

A: You mention that the cookie is set by a program running in its own sub-directory. You don't mention whether the cookie itself is set to be in that sub-directory, but I suspect this is where your problem is.
If a cookie is set to a path, then it will only be accessible to pages within that path. This behaviour is described in the PHP setcookie() manual page.
When you're setting cookies from a page within a sub-directory, then in order for the cookie to be accessible to the whole site, setcookie() needs to be called with the optional path parameter set to "/".
You state that the cookie is being set by LimeSurvey. I don't know this software, but you should be able to look at the source and see whether it's using the path parameter when it sets the cookie. If not, your best option would be to modify it so that it does. Then the cookie will be accessible to the whole site. (It would be quite understandable if the LineSurvey developers had chosen not to set it for the whole site, because it would allow the software to be run as a more isolated entity from anything else on the site).


text:
Q: Coming back on a page with the same quicktab and fields expanded (items do not remain expanded) I have a website with Drupal 7. On one page, we have two quicktabs (using quicktabs module), under each quicktab we have expendable fields. Those fields are expandables thanks to this code:
jQuery(".ideas-content").hide();
jQuery(".ideas-title").click(function () {
jQuery(this).toggleClass('ideas-closed').toggleClass('ideas-open').next(".ideas-content").toggle();
});

The user can click links inside these expandable fields to go to another inside page. When the user goes to the previous page (the page with these expandable fields), quicktabs are back to default and the fields the user previously expanded are not expanded anymore.
How can I do to have the user coming back on the page with the right quicktab and fields expanded? I was thinking to create anchor links but I do not know more.
I googled the issue with no success.
Thank you for any input and help.

A: If you are able to access the exact HTML of your page, through template.php function overrides, .tpl.php overrides, or by writing the HTML yourself within the page.tpl, you can add IDs and classes around the elements you want, and then since you are using javascript, you can try using a library such as https://github.com/browserstate/history.js in order to get functionality to take the user back to the state they were in -- with open sections -- after going to another page.


text:
Q: How to join a schedule at fixed rate thread If you have a an executor service which you submit via scheduleAtFixedRate such as this
public void methodName() {
    executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            //do some operations
            //getSomeResults()
        }

    }, x, y, TimeUnit.SECONDS);
}

Is it possible to join with another thread which is responsible for getSomeResults()? For example, I want the thread to wait for the getSomeResults() to finish before it continues - is this possible?
Thanks

A: Yes, you want to submit a FutureTask rather than a Runnable. (A FutureTask is a Runnable, so you don't need to change anything else.)
If you create a FutureTask then you can have another thread invoke its .get() method, which will block until the task is complete, and it will return the result.
(The cleanest way will be to get rid of your getSomeResults() method entirely, and just use the get() method of FutureTask; but there's nothing to stop you leaving your code more or less as it is, and just using get() as a way of blocking, if you want to try that first to check it's all working.)


text:
Q: template named constructor struct omit typename I have a class looking like
template <typename T> class CClass
{
    public:
        struct NamedCtor;

        CClass(T a, T b, T c);

    private:
        // data members
};

tepmlate <typename T> CClass<T>::NamedCtor : CClass<T> { NamedCtor(T x) : CClass(x, x, x) {}; };

With CClass<T>::NamedCtor() as named constructor.
This is perfectly usable if I know the template parameter when using with CClass<int>::NamedCtor(3).
But if I do not know the template parameter here, for example when I'm in a template function, I have to write something like typename CClass<T>::NamedCtor(3) with the template parameter T of the function.
Is there any way to bypass this typename as I don't really like it?


text:
Q: Need help using John Resig's Simple Javascript Inheritance John Resig's Simple Javascript Inheritance: http://ejohn.org/blog/simple-javascript-inheritance/
I tried to do such thing:
var SomeClass = Class.extend({
    init: function() {
        var someFunction = function() {
            alert(this.someVariable);
        };

        someFunction(); // should alert "someString"
    },

    someVariable: "SomeString"
});

var someClass = new SomeClass();

This should alert "someString", but it doesn't because inside the closure function someFunction, the value of this doesn't refers to the class, it is changed. That makes me unable to get access to the properties and functions of the class inside a closure function.
Any suggestions?

A: I believe your problem lies in what "this" refers to. "this" is referring to the function in this case, not the object. What you want is probably:
var SomeClass = Class.extend({
    init: function() {
        var self = this;
        var someFunction = function() {
            alert(self.someVariable);
        };

        someFunction(); // should alert "someString"
    },

    someVariable: "SomeString"
});

var someClass = new SomeClass();

VERY LATE EDIT: See also:

*

*$.proxy - http://api.jquery.com/jQuery.proxy/

*_.bind - http://underscorejs.org/#bind


text:
Q: How to use lapply with mutate function how to use lapply with mutate function
hello, I'm trying to use lapply with mutate function. I'm dealing with nested list data.
Let's take an example. given is nested list with two elements. Each element is 10*2 list.
given<-replicate(2,list(matrix(unlist(replicate(10,sample(c(0.2,0.3,0.4,0.1),2,replace=FALSE),simplify=FALSE)),ncol=2)))
colnames(given[[1]])<-c('a','b')
colnames(given[[2]])<-c('a','b')
given

I will convert 0.1 and 0.2 to 'low', 0.3 to 'middle', 0.4 to 'high'. I used lapply, mutate and if_else function.
new_given<-lapply(seq_along(given), function(x){
  mutate(x,
         given[[x]][['new']] = if_else(given[[x]][['a']] %in% c(0.1,0.2),'low',
                                      if_else(given[[x]][['I12']] %in% c(0.3),'middle','high')))})

However, the errored occured. It said there was an 'unexpected ')''. However, the number of bracket are paired right.
> new_given<-lapply(seq_along(given), function(x){
+   mutate(x,
+          given[[x]][['new']] = if_else(given[[x]][['a']] %in% c(0.1,0.2),'low',
Error: unexpected '=' in:
"  mutate(x,
         given[[x]][['new']] ="
>                                       if_else(given[[x]][['I12']] %in% c(0.3),'middle','high')))})
Error: unexpected ')' in "                                      if_else(given[[x]][['I12']] %in% c(0.3),'middle','high'))"
>

Would you tell me what was the problem and how to solve it?
*additional information : I read this article, Using lapply with mutate in R
However, it used data.frame, not dealing with list data. So the approaches seemed different.

A: First of all you have got list of matrices and not dataframes. Also you can direct lapply over given here instead of doing seq_along
library(dplyr)

lapply(given, function(x) {
   data.frame(x) %>%
     mutate(new = if_else(a %in% c(0.1,0.2),'low',
                             if_else(a %in% c(0.3),'middle','high')))})

#[[1]]
#     a   b    new
#1  0.2 0.1    low
#2  0.1 0.2    low
#3  0.4 0.4   high
#4  0.3 0.2 middle
#5  0.1 0.3    low
#6  0.3 0.1 middle
#7  0.4 0.2   high
#8  0.1 0.3    low
#9  0.3 0.1 middle
#10 0.4 0.3   high

#[[2]]
#     a   b    new
#1  0.3 0.1 middle
#2  0.1 0.3    low
#3  0.3 0.1 middle
#4  0.2 0.3    low
#5  0.1 0.4    low
#6  0.4 0.1   high
#7  0.1 0.2    low
#8  0.2 0.3    low
#9  0.4 0.4   high
#10 0.3 0.1 middle

Moreover, a better way is to keep the approaches separate. So a pure base R solution would be
lapply(given, function(x)
      transform(data.frame(x),
       new = ifelse(a %in% c(0.1,0.2),'low',ifelse(a %in% c(0.3),'middle','high'))))

while if you prefer tidyverse
map(given, ~ data.frame(.) %>%
             mutate(new = if_else(a %in% c(0.1,0.2),'low',
                               if_else(a %in% c(0.3),'middle','high'))))

A: There are numerous problems with your approach. First, the error you  are getting is only a side effect of copying the rest of the line after the first error (unexpected '=') occurred.
The reason for that error is different, however. You are applying mutate to x. x is a numeric vector of length 1. However, mutate works only on data frames (not even matrices!). You could convert your matrices to data.frames first, though (as Ronak suggests in the other answer).
Finally, your matrices are doubles. Your approach might work most of the time, but it is not guaranteed to work always, because even if a number looks like 0.3, it might be in reality 0.3000000000000000001, in which case %in% 0.3 will return FALSE. It might not look likely right now, but trust me, sooner or later this approach will hurt you and you won't see it coming. I speak from experience.
Let us first create a function that takes a matrix and based on its first column decides whether it should be 'low', 'middle or 'high'.
cut function takes a number of breaks and for each number assigns a factor level denoting a given interval:
cut(given[[1]][,1], c(-Inf, 0.2, 0.3, Inf))

result:
 [1] (0.3, Inf] (-Inf,0.2] (-Inf,0.2] (0.3, Inf] (-Inf,0.2] (0.3, Inf]
 [7] (-Inf,0.2] (-Inf,0.2] (0.3, Inf] (-Inf,0.2]
Levels: (-Inf,0.2] (0.2,0.3] (0.3, Inf]

We can directly assign labels to the result:
cut(given[[1]][,1], c(-Inf, 0.2, 0.3, Inf), labels=c("low", "mid", "high"))

We can make it into a function:
mklevels <- function(mtx) {
  cut(mtx[,1], c(-Inf, 0.2, 0.3, Inf), labels=c("low", "mid", "high"))
}

Rather than converting matrices to data frames and adding a new column, why not create a new data frame with one column per matrix:
data.frame(sapply(given, mklevels))

This has the advantage that if the matrices are large and used for other computational purposes, changing them into data frames is not an efficient approach.
If you really, really want to work with %in%, then convert the data to factors. That way you will be able to inspect the factor levels and see whether there is a problem. For example:
x <- c(0.3, 0.2, 0.3 + 1e-11, 0.1)
x

Looks innocent enough:
> x
[1] 0.3 0.2 0.3 0.1

However, x[4] %in% .3 returns FALSE. But convert it to a factor and look at the levels:
factor(x)

[1] 0.3           0.2           0.30000000001 0.1
Levels: 0.1 0.2 0.3 0.30000000001

Once you converted your data to factors, you can safely take Ronak's approach. But I would never try it with numeric vectors!


text:
Q: Weird "number of generic arguments doesn't equal arity" error in unit test after program compiled and worked I created a generic class, as shown below, which worked perfectly when I coded it and tested the program in Visual Studio. However, in automated build, a unit test ran which can't deal with the assembly, although no compile or runtime error was visible previously:
Error   18  Error occurred during processing of assembly '....dll': The number of generic arguments provided doesn't equal the arity of the generic type definition.
Parameter name: instantiation   ...Test
The unit test has no usage of the generic class.
I commented out all code, constructor, field from the class, then auto-implemented the interfaces with Visual Studio, generating stubs with "throw new NotImplementedException()".
public class RequiredPropertiesProfile<TPropertyGroup, TProperty>
    : IDictionary<bool, IDictionary<TPropertyGroup, ICollection<TProperty>>>
{
    // auto implementations of IDictionary, with throw new NotImplementedException();
}

It again compiled, but compiling the unit test failed again, with no visible cause. The test has "Microsoft.VisualStudio.QualityTools.UnitTestFramework" referenced.
The class is mainly to define property configurations, required to be set or not set (bool). It is supposed to be generic, to have either strings (user friendly, including helper classes), data objects or database identifiers (int type), with additional methods to translate one into the other.
I found several articles about this error, but none fit my case - especially compiling and running without error first, then stumbling across a stupid unit test, which is not even using the generic class.

A: While this is not an answer what the cause of the problem might be, it helped to create a base class with a fully generic interface, then put my implementation with 1st level type bool on top:
public class RequiredPropertiesGenericBase<TState, TPropertyGroup, TProperty>
    : IDictionary<TState, IDictionary<TPropertyGroup, ICollection<TProperty>>>
{
    private _innerDict = new Dictionary<TState, IDictionary<TPropertyGroup, ICollection<TProperty>>>();

    // _innerDict wrapping methods;
}

public class RequiredPropertiesProfile<TPropertyGroup, TProperty>
    : RequiredPropertiesGenericBase<bool, TPropertyGroup, TProperty>
{
    public RequiredPropertiesProfile(IEnumerable<PropSetting> settings)
    {
        foreach (var set in settings)
        {
            this.AddPropertySetting(set.MustBeSet, set.PropertyGroup, set.Property);
        }
        // ...
    }

    // implementation
}

I still don't know what caused this, and it's still very strange that the initial code would compile and run, but stumble across an unit test not even creating instances of the class (but using it's assembly).
The problem would occur on several machines, first, on the build machine with automated unit tests (usually doing a total cleanup before build/test). Then also on a workstation, when running the unit test.
The problem still occured in the initial version, after removing constructor (leaving only the auto constructor) and all code, except the fake interface implementations, with the class being used nowhere.


text:
Q: Как решить, с помощью if или for? Написать программу, которая по номеру месяца выдает название следующего за ним месяца. (При m = 1 получаем - februari, 4 - may и т.д.)
A: Во-первых, February
Во-вторых,
char months[12][20] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
mplusone = months[m];

A: Оформите в виде функции, аргумент строка с названием месяца, результат int (-1 нет такого месяца).
Создаете массив строк из 12 элементов (лучше static), инициализируете его константами.
При поиске перебираете элементы этого массива в for(...) { ... }. Внутри цикла if с strcmp(). Если нашли, возвращайте текущий индекс. После цикла return -1 (не нашли).
По поводу синтаксиса, запуска и т.п. см. книжки (учебник). Успехов !
UPD
Пардон, облажался, не так прочел условия задачи, просили по номеру выдать название,
а я наоборот.
Правильный ответ (для функции):
char *
get_month(int n)
{
    static char *m[] = {"jan","feb","mar","apr","may", ... "dec"};

    return (n < 0 || n > 11)? NULL: m[n];
}

Не надо ни for ни if. Впрочем, проверку аргумента можно отнести к if, но смысл в том, что искать не надо, надо просто вернуть имя по номеру.
UPD 2.  Да, что же такое, сегодня ? Опять не так прочел вопрос. Требуется не месяц по номеру, а месяц следующий за запрошенным номером.
Суть дела не меняется, только надо решить, идет ли за декабрем январь или это ошибка.
Допустим не ошибка. Тогда запрашиваемые номера д.б. 0:11 (как и в приведенном примере), а m[n] превращается в m[(n+1)%12];
Кажется, все.
A: Обязательно if или for? А если switch? Например:
int iMonth;
scanf("%d", iMonth);
char* chMonth=(char*)malloc(10*sizeof(char));
switch(iMonth){
case 0:
   chMonth="January";
   break;
case 1:
   chMonth="February";
   break;
///////////// И так далее до December////////
default:
   printf("Invalid month number");
   scanf("%d", iMonth);
   continue;}

Если только if/for, то цикл for будет плохим тоном программирования, т.к. это лишняя нагрузка системы.
A: Подобное отображение проще делать с помощью for, нежели одного if, потому что код получается менее громоздкий при больших размерностях вариантов
const char *months[] = {"January", "Feburary", "March"};

for (int i = 0; i < sizeof(months) / sizeof(months[0]); i++)
    if (n == k)
        printf("Month #%i is %s\n", i, months[i]);

а для if
if (k == 0)
    printf("Month #1 is January\n");
if (k == 1)
    printf("Month #2 is Feburary\n");
if (k == 2)
    printf("Month #3 is March\n");


text:
Q: Question about android: I Want to upload images to server Helllo
I am trying to upload some images to the server. If i placed the code in the subclass of activity, will the sending be interrupted by the onPause function when the user leaving the activity while the user want to use other application.
If this is the problem would it be better to use service to upload the file instead?

A: Your best best is to use an AsyncTask.  This will execute in the background and give any feedback on the UI thread if you need.


text:
Q: HTML Picture coding I was wondering. I see the favicons on the website tab in my browser, and was wondering how to do this for my website also. If you don't know what I'm talking about, just look at the picture.

A: <!DOCTYPE html
      PUBLIC "-//W3C//DTD HTML 4.01//EN"
      "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon"
      type="image/png"
      href="http://example.com/myicon.png">
[…]
</head>
[…]
</html>

The <link> tag is where you configure the icon.
This link should help you with what your looking for.

A: Simply, just add:
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">

in your html head elements.


text:
Q: SQL Server : combine query result to one row
I want to format the query like this. is it possible?

A: With conditional aggregation:
SELECT
  MAX(CASE WHEN CHECKTYPE = 'I' AND TIMETYPE = 'AM' THEN FORMAT(CHECKTIME, N'HH:mm') END) [AM-IN],
  MAX(CASE WHEN CHECKTYPE = 'O' AND TIMETYPE = 'AM' THEN FORMAT(CHECKTIME, N'HH:mm') END) [AM-OUT],
  MAX(CASE WHEN CHECKTYPE = 'I' AND TIMETYPE = 'PM' THEN FORMAT(CHECKTIME, N'HH:mm') END) [PM-IN],
  MAX(CASE WHEN CHECKTYPE = 'O' AND TIMETYPE = 'PM' THEN FORMAT(CHECKTIME, N'HH:mm') END) [PM-OUT]
FROM [dbo].[CHECKINOUT]
WHERE [USERID] = N'21477' AND [CHECKTIME] BETWEEN N'2020-02-3 00:00:00' AND N'2020-02-4 00:00:00'
GROUP BY [USERID]


text:
Q: How can I see the status of my favorite servers without logging in to the game? I have a short list of servers that I visit whenever I play TF2. Sometimes these servers are well-populated, other times completely empty.
When I unwind at my computer, I'd like to check to see the status of those servers before launching the game. How can I see how many people are on a specific TF2 server without using the in-game server browser?

A: You can right click on the Steam icon in the System Tray (next to the clock) and select servers, and this useful tool will come up :

 There you will have every server, grouped just as you did in-game for every game you own.
You can also access it this way:


text:
Q: How to programmatically trigger the click on a link using jQuery? How to programmatically trigger the click on a link using jQuery?

A: $('#your_link_id').click()

See the excellent jquery docs for more information

A: If you have an anchor link:
My Link

it will fail as other answers have mentioned. Calling .eq and .trigger('click') doesn't work for me, but this does:
$('#your_link_id').get(0).click();

In my specific case, I've assigned a blob url programmatically to the anchor's href.

A: You can use trigger:
$('#your_link_id').trigger('click');

A: $('#your_link_id').eq(0).trigger('click');

or you can use
$('#your_link_id')[0].trigger('click');
is needed as jQuery returns an array and we cannot trigger click on multiple eventlinks. You have to target only a single element


text:
Q: Can Spotlight index a MacFUSE filesystem? Spotlight indexes at the file level, so a file containing a complicated data structure may need to be split into a set of files for Spotlight to index it in a useful way.
Can you use MacFUSE to achieve this more dynamically?
Will Spotlight index a MacFUSE volume?
Can MacFUSE handle the necessary per-file metadata?
Can a MacFUSE process notify Spotlight when attributes of a file change?

A: I've been testing with this myself.
I found this on the MacFuse Wiki:
(http://code.google.com/p/macfuse/wiki/OPTIONS)
if you wish to use Spotlight on a MacFUSE volume, you'll need to use allow_other.
I've discovered that it also works with allow_root.
However, I had to enable indexing myself by using
mdutil -i on /Volume
(as codelogic already mentioned)
So, if it does not work, try allow_root or allow_other
More testing:
Allow_root does not work. it can index once, but it doesn't seem to index newly created files in subfolders. When changing to allow_other, it seems spotlight CAN detect the new changes, and index the new files. ==> allow_other is a requirement

A: You can use the mdutil command to enable indexing on external volumes. It should be applicable to MacFUSE volumes as well.
sudo mdutil -i on /Volumes/SomeVolume

A:
so a file containing a complicated data structure may need to be split into a set of files for Spotlight to index it in a useful way.

If you want to index a custom file, you need to write your own Spotlight indexer that understands this file type - XCode has a template for this.


text:
Q: Padding binary files from a specific address point to another specific address point in address Problem description:
I have two binary files(lets call them file A and B). File A is the kernel and file B is the application to be run on(yes it is an embedded operative system). With file A i need to fill the gap from the end of the kernel to the program start which starts at address 0x00020000.
And then from 0x00020000 + program length i need to fill the gap to 0x00080000.
I tried looking into arm-none-eabi-objcopy gap fill with no luck.(contiki uses it)
I basically have two questions. How do i know when to start the padding from file A to 0x00080000 and obviously how to do the padding.
If something was not clear please let me know and i will try to explain in more detail to the best of my capabilities.

A: To use objcopy to append padding after the last section you need to use --pad-to <address> in combination with --gap-fill <fillvalue>.
e.g.:
arm-none-eabi-objcopy --gap-fill 0x00 --pad-to 0x80000 filea.out filea_padded.out

It is necessary however that objcopy is performed on the object file rather than a raw binary.  A raw binary lacks the address information and section meta-data that tells it where the gaps and end-address are.
If your "binary" is in fact a hex file (Intel or S-Record format for example), you can use the SRecord utility suite to manipulate those, as the format included address/location meta-data.  You can also use this to concatenate the two files into a single image.


text:
Q: Any changes made to Laravel blade templates will not show in my local environment - tried cache clearing Using:
MAMP 5.7
Laravel 5.4
I have my company's main website cloned into my local environment. I have gotten everything up and running and all the views render correctly. My problem comes when I attempt to alter any of the blade templates. Any HTML I add to it or remove from it is completely ignored when I run it on the Apache server.
What I have tried:
-Clearing the Apache and Laravel caches (php artisan cache:clear, php artisan view:clear)
-Opening up r/w file permissions on every folder
I am stumped. Any insight would be appreciated.
Update
When going directly to the blade template file path (/views/path/to/template/template.blade.php), the content I added will render. It just seems to not render when I run it though the localhost/path route.

A: Try these commands
php artisan dump-autoload
php artisan cache:clear
php artisan config:cache

I hope it helps


text:
Q: How to reduce the total after every iteration I have a $paymentsTotal variable which is the sum of all payments. I then want to loop through all outstanding amounts and reduce the $paymentsTotal variable for each outstanding amount.
eg:
TotalPayments = 900 - 200
                700 - 300
                400 - 100
                300 - 300
Stop             0

And as long as the $paymentsTotal is greater than the outstanding amount, it should return true.
I tried this:
foreach ($invoices as $invoice) {
  if($paymentTotal >= $paymentTotal -= $invoice->amount) {
        echo $invoice->amount . ' - PAID
';
   }
}

but it echos out each result no matter what.

A: Try something like...
$paymentTotal = 0; // whatever this is before iteration

foreach($invoices as $invoice) {
    if ($invoice->amount > $paymentTotal) {
        $paymentTotal -= $invoice->amount; // assuming you have a field for the paid amount
        $invoice->amount = $paymentTotal; // new invoice amount
    echo "{$invoice->amount} - PAID
";
    }
}


text:
Q: Concrete 5 CMS index of Magento 2.1 I would like to have the index page of concrete5 and magento 2 store. How do I configure nginx to use the index of concrete5 and not that of magento 2.
This site is multilanguage, use map to redirect in to the domain ITA/ENG/DE

Thank you!

A: Go into nginx config and change the line `index index.php;'
To 'index ****.php;'
Please change ****.php to the file name of the concrete 5 index page
Once done 'Sudo service nginx restart'


text:
Q: Caught VariableDoesNotExist while rendering: Failed lookup for key [time_filter] in u'[{}, views.py
def when(request):
    user = request.user
    report = Report.objects.get(user=request.user)
    reportform = ReportForm(instance=report)
    settings = Settings.objects.get(user=request.user)
    settingsForm = SettingsForm(instance=settings)
    settings=Settings.objects.get(user=2)
    if settings.date_format == '0':
        date_filter = 'd/m/Y'
    else:
        date_filter = 'm/d/Y'
    if settings.time_format == '0':
        time_filter = 'I:Mp'
    else:
        time_filter = 'H:M'
    if request.method == 'POST':
        reportform = ReportForm(instance=report,data=request.POST)
        if reportform.is_valid():
            report = reportform.save(commit=False)
            report.user = request.user
            report.save()
            return redirect('/member/media/')

    return render_to_response('incident/when.html',{
                  'newreport_menu': True,
                  'form': reportform,
                  },
                   context_instance=RequestContext(request))

template is
{{ form.manual_time|date:time_filter }}
{{ form.manual_date|date:date_filter }}

Giving error in date_filter and time_filter in template,the error is "Caught VariableDoesNotExist while rendering: Failed lookup for key [time_filter] in u'[{},"

A: You haven't included time_filter or date_filter in the context dictionary you pass to render_to_response.


text:
Q: Looping through Dictionary of Unicode Data I'm trying to loop through a list of unicode data. type(d['results']) is a list.  However, organization_fields is actually a dict but formatted as unicode when looking at the load.  The question is, how can I access organization_fields? I've tried to change the format using ast.literal_eval(k) but have had some errors in trying to do so.
Also, I'm getting my response r and saving it as d = r.json()
I have
       for a in d['results']:
 ...:     for k,v in a.iteritems():
 ...:         print k
 ...:         print type(k)
 ...:         print('------break-----')

Here is the output:
 name
 <type 'unicode'>
 ------break-----
 shared_comments
 <type 'unicode'>
 ------break-----
 url
 <type 'unicode'>
 ------break-----
 organization_fields
<type 'unicode'>
------break-----

organization_fields
    u'organization_fields': {
       u'account_type': None,
       u'id':  u'some_id',
       u'value': None
  },

UPDATE
When i try printing d['results'][0] I do get a list of items that are in here Ex. url, name, except organization_fields does not exist in it.  It only exists when i loop through a in the above for loop

A: organization_fields is not stored as unicode. The key is a unicode string, but the type of the value stored by the key u'organization_fields' is a dictionary of more values stored with unicode string keys. Accessing values of organization fields is identical to accessing values of any other dictionary.
If you want to access organization_fields in your for loop:
for a in d['results']:
    org_fields = a['organization_fields']
    print org_fields

Edit: It does not sound like every element of d['results'] contains a dictionary with a value stored by the key organization_fields. This should do the trick.
for a in d['results']:
    if 'organization_fields' in a:
        org_fields = a['organization_fields']
        print org_fields

If you want to see which index of d['results'] contains the value of organization_fields, then do this:
for i, a in enumerate(d['results']):
    if 'organization_fields' in a:
        org_fields = a['organization_fields']
        print org_fields
        print 'index: %s' % i

Then, with the index you printed from there, you can access it directly:
org_fields = d['results'][index printed]['organization_fields']

A: I'm not sure to understand your question...
But if I did, you should try something like :
print d['result'][0]['organization_fields']['id']

which should print
some_id

--> I don't think there's any "unicode data" : there are dictionnaries with unicode strings as keys.


text:
Q: Do high and low side labels on bidirectional logic level converters matter? Logic level converters like this one from Sparkfun have high side and low side labels on them. Now i have an application where I think I need to shift logic levels but the high side and the low side are likely to swap at some point due to changes in battery voltage over time.

This is intended for a battery powered project with an expected runtime of a year where an ATTiny85 that can natively work between 2.6V and 6V and is directly connected to the battery will be talking to an ESP that is behind a 3.3V regulator because it can not handle more than +-0.5V deviation from 3.3v on any of the pins. The ESP (regulator) will brownout much earlier but that is OK.
I started reading the BSS138's Datasheet and could not find any mention for or against swapping sides.
So I built a very minimalistic simulation of the circuit. According to the simulation the source-drain is passed in either direction in "normal" operation while sticking to the high and low side labels.

Further simulations swapping the high/low sides and even having them the same voltage did seem to work.
Is there any downside to swapping the high/low sides with a logic level converter based on a BSS138?
Thank you Dave for your answer.
Now I see that the sides do matter and swapping them would lead to failure.
Here is the sideswapped state with both sides pulled high which would lead to failure:

The left side is pulled down to 4.1V (should be 5V) and the right side is pulled up to 3.8V (should be 3V) potentially destroying the ESP, definitely destroying the ESP if the battery was at 6V and connected to the converter's low side!

A: Yes, they matter. See that body diode on the MOSFET? It must be reverse-biased when both signal lines are being pulled high.
Otherwise, the HV side is trying to pull the LV side higher than the LV supply voltage. If that wasn't a problem, you wouldn't need the level shifter in the first place.

If you can find a MOSFET that doesn't have its substrate internally shorted to the source pin (i.e., it is brought out to a fourth pin), then you can do what you want. Connect the substrate to ground (the most negative point in your circuit), and then you can use the source and drain terminals interchangeably.


text: Q: Check array for consecutive sets of 1s and 0s I am trying to access elements in a DArray (which I have created by copying elements from a linked list) 3 at a time, searching for sets of 3 consecutive 1s and 0s. For ex: if indices 0 through 2 hold the values of 1 1 1, my output would be a 1. If indices 3 through 5 hold the values 0 0 0, my output would be 0. If indices 6 through 8 hold a mixture of 1s and 0s, the output would be nothing. I've tried several approaches and cannot seem to find one that works right. Does anyone have any ideas? This is not a homework assignment.


text:
Q: use button to pass td data I have a table that I want to give the user the ability to select.  I added an button, value="Update", to the beginning of the row, and assigned an onclick value.  My problem is that I want to send other items(in td>s on the same row) from the row to the function called by the button.
How do I get the information from the row the button is on?  I would like to pass the "Name" and "Last Update Time" to the function the button calls.  I tried using the following:
$("#Report input[name=btn_id]").closest('td').attr('text')

but it returns "undefined," which I am not surprised by, as I think this is due to it not knowing what row of the table to pull from.
Here is a view of the table:
Here is the code behind the table:

        Update
        Name
        Info
        location
        Last Update Time

            <input type="button" name="btn_id" value="Update" onclick="UpdateRec(d1)">

        Test1
        None
        Desktop
        2014-06-30 18:22:39

            <input type="button" name="btn_id" value="Update" onclick="UpdateAppRec(d1)">

        Test1
        None
        Server
        2014-03-30 16:20:15

Any help would be appreciated.

A: Embrace the power of this.
Using:
onclick="UpdateRec(this)"

..in your function:
function UpdateRec(el) {
   var targetRow = $(el).parents('tr')
   ...
}

Using this passes a reference to the clicked element. You can then use jQuery to select the parent table row. From there you can use .find() to select anything in that row.
Another way to do this would be to use HTML5 data- attributes on this button itself:
<input type="button" name="btn_id" value="Update" onclick="UpdateRec(d1)" data-appName="something" />

In the same function you can then use $(el).data('appName') to get the value directly without looking up values in other DOM elements.

A: //Add a click listener on all your buttons using event delegation
$('#Report').click(onUpdateButtonClicked, 'input[name=btn_id]');

function onUpdateButtonClicked() {
    var rowValues = $(this)
        .parent() //select parent td
        .nextAll() //select all next siblings of that parent td
        .map(function () { //loop through the tds, collecting their text value
            return $(this).text();
        }).get(); //return the result as an array

    //do what you want with rowValues
}

A: I would suggest you to use common class for all update buttons with common click event handler.
Here is the fiddle: http://jsfiddle.net/jwet6z6x/
HTML:

        Update
        Name
        Info
        location
        Last Update Time

            <input class="updateBtn" type="button" name="btn_id" value="Update">

        Test1
        None
        Desktop
        2014-06-30 18:22:39

            <input class="updateBtn" type="button" name="btn_id" value="Update">

        Test1
        None
        Server
        2014-03-30 16:20:15

Javascript:
$(".updateBtn").click(function(){
    var name =  $(this).parent().parent().find('td').eq(1).html()
    var time =  $(this).parent().parent().find('td').eq(4).html()
    alert (name);
    alert (time);
})

A: I would do as follow : http://jsfiddle.net/Lk91cpup/2/

        <input type="button" id="btn_row_1" class="btn" value="Update">

    Test1
    None
    Desktop
    2014-06-30 18:22:39

        <input type="button" id="btn_row_2" class="btn" value="Update">

    Test2
    None
    Server
    2014-03-30 16:20:15

And Javascript
$(document).ready(function(){

    $(".btn").click(function(){

        var id = this.id.substring(this.id.lastIndexOf("_") + 1);

        alert($("#text_row_" + id).text());

    });

});

A:

        <input type="button" name="btn_id" value="Update" onclick="UpdateRec(d1, 'Test1', 'None',  'Desktop', '2014-06-30')">

    Test1
    None
    Desktop
    2014-06-30 18:22:39

Since you have already written a javascript function call why not just include the things you need right?
This is simplier but not the best practise.


text:
Q: How to add class to element if inner value changes on ajax request? I want to write a piece of code which requests some cryptocurrency prices by ajax, it will request a FIAT currency price as well.
So, I want to add "increased" class when the price goes up & "decreased" class when the price goes down. The script runs every 3 seconds to check the new prices.
I've tried to define a variable on the innerHTML of the price element, and an if/else on what should the script do when the price changes. Here is a sample code:
var btn = document.querySelector("#refreshprice");
var price = document.querySelector("#price-text");
var btcirr = document.querySelector("#btcirrrealtime");
var currency_symbol  = document.querySelector("#currency-symbol");
var usdirrinner = usdirr.innerHTML;
var priceinner = price.innerHTML;

window.onload = function(){
    var USDIRR = getUSDIRRRequest();
    USDIRR.send();
    var XHR = getXHRRequest();
    XHR.send();
    var BTCIRR = realtimeirr();
};

setInterval(function(){
    var USDIRR = getUSDIRRRequest();
    USDIRR.send();
    var XHR = getXHRRequest();
    XHR.send();
    var BTCIRR = realtimeirr();
},3000);

function getUSDIRRRequest(){
    var USDIRR = new XMLHttpRequest();
    USDIRR.open("GET","http://call2.tgju.org/ajax.json");
    USDIRR.onreadystatechange = function(){
        if(USDIRR.readyState == 4 && USDIRR.status == 200){
            var parsedData = JSON.parse(USDIRR.responseText);
            dollarrealtimeprice = parsedData.current.price_dollar_realtime.p.replace(",", "");
            var dollarrealtimepricetoman = dollarrealtimeprice/10;
            usdirr.innerHTML = dollarrealtimepricetoman;
            if(usdirrinner >= dollarrealtimepricetoman){
                usdirr.classList.add("increased");
            }
            else {
                usdirr.classList.add("decreased");
            }
        }
    }
    return USDIRR;
}

function getXHRRequest(){
    var XHR = new XMLHttpRequest();
    XHR.open("GET","https://api.coindesk.com/v1/bpi/currentprice.json");
    XHR.onreadystatechange = function(){
        if(XHR.readyState == 4 && XHR.status == 200){
            var parsedData = JSON.parse(XHR.responseText);
            price.innerHTML = parseFloat(parsedData.bpi.USD.rate_float).toFixed(2);
            if(priceinner >= parseFloat(parsedData.bpi.USD.rate_float).toFixed(2)){
                price.classList.add("increased");
            }
            else {
                price.classList.add("decreased");
            }
            currency_symbol.innerHTML = parsedData.bpi.USD.symbol;
        }
    }
    return XHR;
}

It was expected to change the class to "increased" when the price goes up. but it just remains decreased.


text:
Q: Newton's laws and the maximum speed According to Newton's second law of motion : $F = ma$
In an certain occasion, we exert 2 forces (the magnitudes of the forces are the same) on 2 different objects, Object A and Object B, in the same direction (let's assume that the beginning velocity of the two objects is 0). The duration time of the force that we exerted on object A was much longer than the duration time of the force that we exerted on object B.

*

*Will eventually the two objects will have the same velocity even though the duration time of the forces is different? After all, the maximum speed they could possibly move at is the speed of the light. What will happen in the next time unit (e.g. seconds) after the objects will reach the maximum speed? Will the two objects keep accelerating or will they move at the same velocity (the maximum speed in nature)?

*During the time where both forces are applied, both of the objects were able to reach a speed which is near to the speed of light.

*What brought the scientists to the assumption that a maximum speed exists?
On what is such assumption based?

A:
1. Will eventually the two objects will have the same velocity

Newton
No, in the Newtonian model the longer you apply a force to an object the faster it travels (assuming no other forces apply, in an atmosphere for example, there might be a terminal velocity regardless of the continuing application of force).
However Newton's laws are only valid for $v \ll c$
SR
Not in any measurable time. As $v$ increases closer to $c$ the acceleration due to the constant force will be less and less. $v$ will only approach $c$ as time approaches infinity.

What will happen in the next time unit

There is no next time unit after $t = \infty$

2. What brought the scientists to the assumption that a maximum speed exists?

It is more an observation (or a prediction from the application of a mathematical model based on observations). It isn't really an assumption.

On what based such assumption? [assertion]

As I understand it, it all follows from the observation that the speed of light is a constant, different observers, moving inertially relative to one another, all record the same speed. Everything follows mathematically from that.

the special relativity and Newton's laws of motions contradict each other

They don't contradict one another. If you take SR equations of motion and use the constraint $v \ll c$ you arrive at Newton's equations of motion. This view may be controversial - e.g. see THE NEWTONIAN LIMIT OF RELATIVITY THEORY AND THE
RATIONALITY OF THEORY CHANGE
Both Newton's equations of motion and those of SR produce the same results for macroscopic velocities typically experienced directly by humans. At least, the differences are insignificant, too small to measure conventionally.

A: $F=ma$ is a classical approximation to a more complete expression $\vec{F}=\dfrac{d\vec{p}}{dt},$  so it doesn't work well at speeds about approximately 0.1c (c is speed of photons).
That means we find the change in momentum, $$\Delta\vec{p}=\int_{t1}^{t2}\vec{F}dt.$$ To continue the simplified version you started, let the force be constant. That means that $$\Delta\vec{p}=\vec{F}(t_2-t_1).$$
In your problem, both particles start with $\vec{p}=0,$ and $t_1=0.$ Therefore, $\vec{p}_A=\vec{F}t_A$ and $\vec{p}_B=\vec{F}t_B.$ Because the forces are identical and $t_A > t_B$, then $p_A>p_B$ for all $t>0$. They never reach speed $c$. You also state that there is a time for each object at which the force ends. When this happens, the momentum (and velocity) of each will remain constant.
In classical language, when the forces stop, the accelerations will stop and the velocities will remain constant. So different times in your problem guarantee different final velocities.
The existence of a maximum speed limit is a consequence of the rotation of spacetime coordinates.  It so happens that this limit is the same as the speed of photons.  The basis for the way the rotation works is found in Einstein's postulates of special relativity.  It's actually the rotation of Minkowski space.


text:
Q: How to replace strapis default wysiwyg editor to CKEditor I am trying to use CKEditor for strapi project, but failing to integrate.
What I did so far:

*

*strapi new cms --quickstart It is starting me new cms application.

*npm install ckeditor

*Edit the code located at ./plugins/content-manager/admin/src/component/Edit/index.js to CKEditor implementation

*npm run build to see my changes, tried npm run setup too

But here I'm getting error webpackJsonp is not defined
I'm not providing the code how I modified, because, build command is not reaching till there.
I appreciate any help you can provide

A: In order to change the default WYSIWYG in Strapi you will need to

*

*Fork the repository check out the CONTRIBUTING GUIDE

*Once you have the development setup you can directly modify the code in packages/strapi-plugin-content-manager/admin/src/components/WYSIWYGWithErrors and its related children. Install the dependency in strapi-admin

*Uninstall the content manager plugin (again make sure you are running the latest version of Strapi

*Copy the strapi-plugin-content-manager package inside your app's plugin folder (rename it content-manager)

*Copy the following file in my-app/admin/src/plugins.js and change the paths of the plugins so it matches your new one

*run yarn develop


text:
Q: How to use boost json lib to parse a json file with comments? I'm new to boost library and I really need some help. In my case, I need to use boost lib to parse an external JSON file with comments(eg. "//" symbol). I use the following code to parse the unformatted json.
boost::property_tree::ptree root;
boost::property_tree::read_json<boost::property_tree::ptree>(file_path,root);

It fails since the json file is not a standard file. I also noticed the reference in Are comments allowed in a JSON file for boost read_json?. However. I still use this unformatted file for my case.
My question is whether there is a 'ignore_comments' like nlohmann lib in boost lib or not. How I can handle this issue under the condition of boost lib.

A: There is an option to allow non-standard behaviour for the boost.json.parser:
https://www.boost.org/doc/libs/develop/libs/json/doc/html/json/input_output.html#json.input_output.parsing.non_standard_json
parse_options opt;                                  // all extensions default to off
opt.allow_comments = true;                          // permit C and C++ style comments to appear in whitespace
//opt.allow_trailing_commas = true;                   // allow an additional trailing comma in object and array element lists
//opt.allow_invalid_utf8 = true;                      // skip utf-8 validation of keys and strings

value jv = parse( "[1,2,3,] // comment ", storage_ptr(), opt );

This should do what you want. You'll probably need to read your file as text first, though.


text:
Q: Playing long sound in local notification iOS10 I have a custom sound playing on local notification, in iOS 10 when the device is locked everything works fine and the sound plays till the end. But when the device is unlocked, as soon as the notification bar hides ( in about 5 Secs.) the sound stops playing.
PS. It works fine in iOS 9, the notification bar stays on top as long as the notification sound is playing.
Is it a bug or am I missing something?
EDIT:
I've tested with either UNUserNotificationCenter and deprecated UILocalNotification. Both the same result.


text:
Q: "Best Java book you have read so far" migrated? I noticed that the post "Best Java book you have read so far" has been recently migrated to Programmers:

While a similar post The Definitive C++ Book Guide and List is still sitting silently on SO, enjoying its time, and not even being closed.
My confusions:

*

*Is there anyone so hostile to Java, that s/he did this to this post? EDIT: Okay, I take it back. This is actually a joke, so if I offended anyone, I apologize.

*Is this migration really necessary, considering this is definitely programming related, and is a good place for people to learn from, and is a pretty famous question?

*Is this migration appropriate, since this post has such a long and glorious history (not only near three years, but also with almost 200 upvotes and many great replies)?
I am confused about the distinction between programmers and SO. At times it just seems there is a fine line too thin for us mortals to comprehend.

A: The migration was appropriate because it's not a technical code programming question.  Stack Overflow is just for those.  Resource questions belong on Programmers (and yes, they're picky about those).

A: There are two moderators involved here.

*

*A Stack Overflow moderator migrated the question to Programmers. Possibly in response to flags, I don't know the story.

*A Programmers moderator (and at least one other user, there might have been flags as well) closed the question as not constructive.

The difference in treatment between the questions has nothing to do with the language involved. Moderators don't judge questions based on their programming language preferences (your suggestion that someone was "hostile to Java" is ridiculous), they base their judgement on the question's quality. Consider the difference between the two:

*

*One question, still open, asks for "QUALITY books and an approximate skill level", with "a short blurb/description about each book". The question is maintained, with an organised selection of books together with explanations of who might find each book useful.

*The other question, now closed, asks for "the best Java book you have read so far". It even insists on "one book per answer", which is a sure-fire way of getting a long list with absolutely no organization. Most answers say "this book is great", not "this book is good because …".

I think the migration was not appropriate — because the low-quality question should have been closed in situ. It might have been salvageable if someone had gone through the effort of improving it until it reached the level of the C++ book question.
The line between Stack Overflow and Programmers is indeed thin, but the fate of this particular question has nothing to do with it.


text:
Q: Add class on li element (filter) depending on url hash in order to have a filter link with instruments already filtered, I'm trying to add classes on "a links" depending on data-attributes in URL (hash).
I'm not using input [checkbox] for the filter list/terms.
The website is on Wordpress and I'm using this awesome plugin for the filter : https://github.com/Robbertdk/wordpress-ajax-filter-posts
JS code based on : https://stackoverflow.com/a/36796926/8544865
Filter terms example :

Instrument 1

Instrument 2

Instrument 3

Instrument 4

Instrument 5

JQuery
1/ adding data-term="value" on url. Url will be like: http://website/our-instruments/#term1+term2+term3 (if term1/2/3 are manually checked) :
var hash = $(".ajax-posts__filterlist ul a.chkd-el").map(function() {
    return $(this).data("term");
    }).toArray();
    hash = hash.join("+");
    location.hash = hash;

2/ here is the part where I have troubles. I want to add classes only on  elements corresponding on data-term value. I'm able to put all values from URL on data, but I can't use them to add classes on correct elements :
if (location.hash !== "") {
        var hash = location.hash.substr(1).split("+");

        hash.forEach(function(data) {
        console.log(data); // return right strings term1, term2, etc...

        $(".ajax-posts__filterlist ul a[data-term=" + data + "]").addClass("is-active enabled chkd-el"); // that line is not working
    });
}

3/ I guess I will need a trigger to simulate checked element (ajax is used for the filter process, with click Event Listeners)
Here the whole JS code :
var $checkedEl = $(".ajax-posts__filterlist a");

$checkedEl.on("click", function() {
    if ( $(this).hasClass("chkd-el") ) {
        $(this).removeClass("chkd-el");
    } else {
        $(this).addClass("chkd-el");
    }

    var hash = $(".ajax-posts__filterlist ul a.chkd-el").map(function() {
        return $(this).data("term");
    }).toArray();
    hash = hash.join("+");
    location.hash = hash;

    if (location.hash !== "") {
        var hash = location.hash.substr(1).split("+");

        hash.forEach(function(data) {
            console.log(data);
            $(".ajax-posts__filterlist ul a[data-term=" + data + "]").addClass("is-active enabled chkd-el");
        });
    }
});

I hope my problem is understandable.
Thanks !


text:
Q: How to refer to the object property if the property name can be any I have, for example, the following array of objects:
data = [{id:name1, num1:12, num2:8},
        {id:name2, num1:5, num2:13},
        {id:name3, num1:21, num2:4}];

I am wondering, how can I refer only to property "num1" of all objects or "num2", considering, that I don't know the exact name of the property.
So if I want to find the Sum of all num2 I cannot do it simply writing the following piece of code:
data.forEach(function(obj) {
Sum += obj.num2;
};

Cause "num2" may not be called "num2" but any other name, depending on the generated report (data is taken from the Microstrategy reporting system). And it is inconvenient to change the code every time just to meet the property name.
Any help is highly appreciated! :)

A: This may be overkill, but this is what I would do to create a Sum object from the original
data = [{
  id: 'name1',
  num1: 12,
  num2: 8
}, {
  id: 'name2',
  num1: 5,
  num2: 13
}, {
  id: 'name3',
  num1: 21,
  num2: 4
}];

var Sum = {};
data.forEach(function(obj) {

  var keys = Object.keys(obj);
  keys.forEach(function(k) {
  if( i )
    if (Sum.hasOwnProperty(k)) {
      Sum[k] += obj[k];
    } else {
      Sum[k] = obj[k];
    }
  })
})

console.log(Sum);

https://jsfiddle.net/d6vttp9v/
Note: this also sums the string field, so its kind of nonsense, but you could easily specify an array of column to exclude (exercise for the reader).
So this answer doesn't get you exactly what you want (I'm not sure exactly what you want), but hopefully its a good step in right direction.

A: You can access an objects properties like so:
var x = { someProp1: 'x', someProp2: 'y' };
for(prop in x) {
  console.log(prop);
}

Heres a handy reference
If this question is more generally about schema changes in JSON objects and whats the best approach to that, heres an angle I use.
for example the ajax call getPeople
myApp.ajaxSchemas.getPeople = {
  NAME: 'Name',
  AGE: 'Age'
};

I would then refer to the schema in my code:
someObject[myApp.ajaxSchemas.getPeople.NAME];

This means that when theres a schema change it is managed in one place, the myApp.ajaxSchemas.getPeople definition.
I hope this helps.
Rhys


text:
Q: spliting java string and adding characters at end and start of of alphanumeric I want to add a character at end and start of aplhanumeric in a string(max 8 characters). Any example will be great help to me in java
String S1 = "xnXrmXWBidhksyn70rGyTH==QNujyRMdrQi8dO9X+RunER==LTy+K
mGI+KRCcRtmP5ehfR==";

I will add a,b,c,d,e,f,g and h at every end and start of aplhanumeric in above string and I want output as
 xnXrmXWBidhksyn70rGyTHa==bQNujyRMdrQi8dO9Xc+dRunERe==fLTyg+hK
mGI+KRCcRtmP5ehfR==

Please note that the string I will get will be dynamic and contains the non alphanumberic characters anywhere in the string.

A: String [] splits = S1.split("\\p{Punct}{1,}");
and then iterate over array and add what you want to the end

A: Your question is not explained well and your output is not following any pattern.Still according to what I did understand u can split string on index of first non-alphnumeric charcter and next alphnumeric character until eof string.And then add whatever u want at the start and end of subString.Something like
    int startIndex = 0, endIndex = 0;
    int index = 0 , tempIndex = 0;
    char ch1 = json.charAt(index);
    while (startIndex == 0) {
                if (!Character.isLetter(ch1)) {
                    startIndex = index;
                } else {
                    index++;
                    ch1 = S1.charAt(index);
                }
            }
     while (endIndex == 0) {
                if (Character.isLetter(ch1)) {
                    endIndex = index;
                } else {
                    index++;

                    ch1 = S1.charAt(index);
                    }
                }

   S1 = S1.substring(tempIndex, startIndex) + "a" + S1.substring(startIndex, endIndex)

+"b"+S1.substring(endIndex, S1.length);
tempIndex = index;

Now continue with index andtempIndex untill eof string .


text:
Q: Exception csrfToken is not a function when called by supertest I have a NestJS backend with CSRF protection and an endpoint to get the CSRF token. I'm getting TypeError: req.csrfToken is not a function when testing this endpoint with jest and supertest.
My code is like this:
// main.ts
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.use(cookieParser());
  app.use(csurf({ cookie: true }));

  await app.listen(process.env.BACKEND_SERVER_PORT);
}

// authController.ts
import { Controller, Req, Get } from "@nestjs/common";
import { Request } from "express";
import * as AuthDto from "./modules/auth/dto/auth.dto";

@Controller("auth")
export class AppController {
  constructor() {}

  @Get("csrf")
  async getCsrfToken(@Req() req: Request): Promise<AuthDto.CsrfOutput> {
    return { csrfToken: req.csrfToken() };  // <-- ERROR HAPPENS HERE
  }
}

// app.controller.spec.ts
import { Test, TestingModule } from "@nestjs/testing";
import { INestApplication } from "@nestjs/common";
import request from "supertest";
import AppModule from "../src/app.module";

describe("AppController (e2e)", () => {
  let app: INestApplication;
  let server: any;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
    server = app.getHttpServer();
  });

  it("/csrf (GET)", () => {
    return request(server).get("/auth/csrf").expect(200).expect("hello");
    // I'll add more validations here once I get past this error
  });
});

I believe this may be related with the test itself, since this endpoint is working fine when called by an external client (our frontend application or Postman). It just doesn't work with supertest.
Anybody has an idea why? Thanks.

A: You only register csurf in main.ts, but your test uses AppModule directly. AppModule doesn't register csurf on its own. Therefore, when the test creates your AppModule, it doesn't have the necessary middleware.


text:
Q: Android to React Native: TypeError: Network request failed I am trying to convert an Android app into React Native, and I came across one of the following API requests on the Android app:
public Result checkModule(Bundle params) {
  String strURL =

  HttpURLConnection conn = null;

  try {
    URL url = new URL(strURL);
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(HttpVerb.GET.name());
    setBasicAuth(conn);
    conn.connect();
    Log.d("Req", "[" + conn.getRequestMethod() + "] to " + url.toString());

    String body = readStream(conn.getInputStream());
    return new Result(conn.getResponseCode(), body);
  }
}

And I tried my attempt to convert it like so to React Native:
export const practiceFetch = () => {
  var requestHeader = {
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'
  }

  var request = {
    method: 'GET',
    headers: requestHeader,
  }

  return dispatch => {
    fetch('https://apipractice.io:3000/monitor/module', request)
    .then(res => res.json())
    .then(payload => {
      console.log('Return success')
      console.log(payload)

    })
    .catch(error => {
      console.log(error);
    })
  }
}

But I'm getting an error TypeError: Network request failed. And I tried adding <key>NSAllowsArbitraryLoads</key><true/>, yet getting the same error.
What may be the issue for the error? And how can I convert from Android to React Native properly?


text:
Q: How to plot vertical line in octave? What it the best way to plot a vertical line using Octave?

A: So, I have two methods for this. One, I found, and the other I made up.
Method 1: From here.
%% Set x value where verticle line should intersect the x-axis.
x = 0;
%% plot a line between two points using plot([x1,x2],[y1,y2])
plot([x,x],[-10,10]);

Method 2: A slightly different approach, exact same result
%% Setup a vector of x values
x = linspace(0,0,100);
%% Setup a vector of y values
y = linspace(0,10,100);
%% Plot the paired points in a line
plot(x,y);

I think Method 2 may write more information to memory before the plot process and it's a line longer, so in my eyes, Method 1 should be the better option. If you prefer Method 2, make sure your x and y vectors are the same dimension or you'll end up with a bunch of dots where you're line should be.

A: Unfortunately the Octave documentation for doing obvious things can be ridiculously lousy with no working examples. Drawing a simple line on top of a plot is one.
As already mentioned, it's is very silly to plot straight lines in octave. It's a waste of memory and processing. Instead use the line() function, to draw on top of your plot.
The line() function require 2 non-standard x-values and y-values vectors, instead of the standard point-slope arguments for point A and point B, normally represented by (x1,y1) and (x2,y2). Instead, you need to write this as: X=(x1,x2) and Y=(y1,y2). Thus confusing every living soul!
Here is an example of the correct way to do this in Octave language:
pkg load statistics     % Need to load the statistics package
x = randn (1,1000);     % Normal Distribution of random numbers
clf; histfit(x)         % Make a histogram plot of x and fit the data
ylim ([-20,100])        % Change the plot limits (to lift graph up)

% Draw the (vertical) line between (0,-10) and (0,90)
line ("xdata",[0,0], "ydata",[-10,90], "linewidth", 3)

With the result:

A: notation (x1,x2),(y1,y2) is really confusing and against textbooks.
Anyway, this is my way:
figure;
hold on;
% vertical line x=0
plot([0,0],[0,10]);
%horizontal line y=0
plot([0,10],[0,0]);
% vertical line x=2
plot([2,2],[0,10]);
hold off;


text:
Q: Dynamically import posts from one wordpress site to another I have found some topics related to this issue but no solution...
I have 2 different websites. I would like that, when I post some posts on the first one, they are automatically posted on the second one, including the featured image. I tried using a plugin called "RSS Post Importer" but it doesn't get the featured image. I did some research and found that a solution is to use fetch_feed and wp_insert_post and create a custom plugin (or function) using these two functions. Is there an easier/better way ?

A: I see you posted you found a solution, but just to add for others (and in case you're interested in another method):
You could hook Site A on the post's status change to Published to POST all relevant post data to an endpoint on Site B's api you've set up to function as a webhook.
(Authenticating can be done on this endpoint as well with a permissions callback that is called before the callback).
You can send/receive everything as json, or handle it like a form $_POST if you prefer, of course.
If you're just migrating, rather than keeping in sync, you could also reverse that flow and have Site B grab and process an endpoint on Site A that has all relevant posts.

I give a rough example in this WPSE answer after the heading "Import Bridge with WP-JSON API" if you want to look at some mocked up code on what I'm talking about.

I've also found this resource for WP_REST request class methods quite useful.
And of course there is the
Wordpress wp-json developer handbook for a walkthrough.

A: You can create a custom plugin, but it'd take some work and you'd have to pay someone to do that. They could develop it either using RSS or the REST API. I recommend giving Pipes a try first though: https://wordpress.org/plugins/wp-pipes/. It's a great plugin that I've used in the past for this sort of thing.

A: I finally achieved it using the RSS Post Importer plugin. Then I used another plugin that allows to tweak the RSS feed on the first website to add the featured image in the content of the feed item. Then you just need to strip the first image from the content of the newly created post.


text:
Q: how to access a file placed outside karaf in karaf bundle i have a file check placed at /home/abc. I want to read this file from a bundle running in karaf.
Location of that file is fixed. So, i can hardcode that. But i am not able to find a way for it.

A: one way- you need to copy the file into the /etc/ folder.
second way- you need to define JAVA_OPTS=-DprojectName="/directorypath/filename" into the /bin/karaf.bat or .sh file and restart the karaf.
write the code like this you are reading the file from
String s= System.getPropety("projectName/filename");
 File f = new File(s);


text:
Q: Workaround for java.lang.UnsupportedClassVersionError to not show it After migration to Java 8, my tool throw the follwing exception if somebody try to run it on earlier Java environments.
Exception in thread "main" java.lang.UnsupportedClassVersionError: com/myapp/MyTool: Unsupported major.minor version 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)

Is there some way to not show this error, and show nice error message with proposition to upgrade Java.
As I understood I should create some small class like:
public class CheckerJavaVersion {
    public static void main(String args[]) {
        String sVersion = System.getProperty("java.version");
        sVersion = sVersion.substring(0, 3);
        Float f = Float.valueOf(sVersion);
        if (f.floatValue() < (float) 1.8) {
            System.out.println("Please upgrate your Java to 1.8 version");
            System.exit(1);
        }
    }

}

and compile it via older compiler. I need some solution how to run this class firstly before the main method of MyToll class starts.
PS. Aplication is packed in jar.

A: The problem is that the error occurs when the class is loaded, so you'd either have to use a "starter app" which starts the actual application in a separate process or dynamically load the application after the Java version has been checked.
I didn't test it but what might work is something like this:
public static void main(String args[]) {
  if( javaVersionOk ) {
    Class.forName("actual.mainclass.name").getMethod("actual.main.method.name").invoke();
  }
}

The idea is to access the class via its name and thus make the runtime load and initialize it at that time. I'm not sure, however, if you can delay class loading like that in all cases so you'd have to go on from there.
And btw, IIRC there already are applications/libraries that provide this kind of functionality, I just don't rember their names. So a search might be worth your while.
Edit: you might want to have a look at appstart if not for using it then for inspiration.
Another launcher would be Apache Commons Launcher.
Alternatives:
Alternatively you could just provide a launch script for each platform you want to support , call java -version and check the returned version before launching the application.
Another alternative would be to use JNLP/WebStart locally, which allows you to specify a minimum version and which AFAIK even provides for download/upgrade functionality.


text:
Q: Strange behavior in Python 3 using the sys module While I was trying some stuffs in my Python 3 interpreter (Python 3.4.2, installed via brew), I encountered some weird outputs I didn't expected:
>>> import sys
>>> sys.stdout.write("foo")
foo3
>>> sys.stderr.write("bar")
3
bar

After experimenting with different strings, I think the number is the length of the inputs I pass.
I've tried this in Python 2.7.8 (gives no numbers in the outputs) and Python 3.4.2 created by virtualenv (gives the same result)
Is the output supposed to be like this?

A: You're right that it's the length. In Python 2, the File.write() method returned None. When the move was made to Python 3, the return value changed to be the number of characters written.
The reason you're getting the different output from stdout and stderr will probably have to do with the order in which things show up on the file handles.
For stdout, write outputs "foo" then the REPL loop (in the grand tradition of PIN numbers and ATM machines) outputs the count to the same stream.
For stderr, it's likely that the REPL loop outputs standard output first (the length) then the content of standard error.
Or, it may be totally non-deterministic, it's probably not something you should rely on, especially as the REPL loop doesn't really exist except in the interactive mode of the interpreter.

A: In the python interpreter, when you print something, it shows you the result on stdout and stderr.
I tested it out in my python 3.4. Here is what I think is happening
sys.std.write("foo") = > foo3

Interpreter writes "foo" to stdout. The interpreter then prints the result of the sys.stdout.write method, which is 3. The end result is foo3. Try sys.stdout.write("foo\n\n"). And this might help you see.
sys.stderr.write("bar") =>
3
bar

The err stream is not as fast as the stdout. The 3 result from the write shows up first with a new line character. The bar is printed after.

A: This behaviour is normal. This happens because sys.stdout.write() returns the length of the text. Try this code again in a python file. you see, this doesn't happen anymore. This "weird stuff" happens because python automatically prints the return value in the REPL.
'text'
# 'text'

if you do this in a python file, there will be no result.
you can prevent this by stopping the return such as this:
_=sys.stdout.write('text')
# text

or doing this:
def noreturn(value):
   pass

noreturn(sys.stdout.write('text'))
# text


text:
Q: C++: undefined reference to function, parameters appear changed I'm confused with this error message. New to C++, and trying to troubleshoot a build.
Why is the error saying char const* and long? I don't see anywhere these being used. (it's supposed to be const char* and int32). The parameters look changed in the error.
error says
undefined reference to `JobContainer::UpdateStatus(char const*, long)'

but prototype is
void UpdateStatus(const char* status, int32 perc_complete=-1);

definition is:
void JobContainer::UpdateStatus(const char* status, int32 perc_complete/*=-1*/)

call is:
static const char* status_ok = "OK";
JOB->UpdateStatus(status_ok, (int32) 0);

Oh, and how do I fix this?

A: Your function is declared, and it is defined in a cpp file (say foo.h and foo.cpp).  The compiler will define a symbol to identify your function, and put the function code in an object file (foo.o).
The function is referred to from another module (main.cpp).  The compiler, through the #included declaration, will see that your main needs a reference to the function - it will leave an unresolved symbol that needs to be resolved for your code to be able to execute.
This unresolved symbol needs to be resolved by the linker; you will have to tell the linker it needs to lookup unresolved symbols in a bunch of object files (main.o and foo.o).
Possibly, you didn't tell the linker to use the object file containing your function body.

A: That's because there are real types and aliases, e.g.
typedef long int32;

The alias does not show up in the real signature, which will always contain the real types that are used.
The error you are seeing is unrelated to that. It is most probably a linker error because you are not linking against the file which contains the definition of the method. How to fix it? That depends, which compiler/build-system are you using? Can you show the commands you use to build your application?


text:
Q: TC - how to assert on  I'm trying to use selenium webdriver to assert a
logo.svg == context.driver.find_element_by_xpath("//img[@src='../logo.svg']"

on Python3.
So, when I'm running the testcase I get:
raise exception_class(message, screen, stacktrace)
      selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//img[@src='../logo.svg']"}

Snapshot of the HTML:

I been trying to "find" this particular image on a header with no success. Can anyone help me?
#----
reviwing the issue, logo_company = logo.svg is a string and context.driver.find_element_by..... it's the imagin object. I thinking how can i compare string == string or, maybe, the file.svg == context.driver that return file.svg something like that?

A: The xpath seems to be a bit off. To locate the element you can use either of the following Locator Strategies:

*

*xpath A:
context.driver.find_element_by_xpath("//img[starts-with(@src, '/static/media/logo-Caja-los-andes')]")

*css_selector A:
context.driver.find_element_by_css_selector("img[src^='/static/media/logo-Caja-los-andes']")

*xpath B:
context.driver.find_element_by_xpath("//img[starts-with(@src, '/static/media/logo-Caja-los-andes') and @alt='Logo Caja Los Andes']")

*css_selector B:
context.driver.find_element_by_css_selector("img[src^='/static/media/logo-Caja-los-andes'][alt='Logo Caja Los Andes']")


text:
Q: HP elitebook 240 G3 touchpad bad performance after upgrading from 16.04 LTS to 18.04.03 LTS on an HP EliteBook 840 G3 my touchpad now performs really badly, with very little options to set it up. The basic issues are:

*

*very (I mean, VERY) low sensitivity, i.e., I need to press or click the touchpad way more strongly than before

*very slow motion, even when set up at the max possible speed

Clicking works fine (here I refer to several post reporting right-click problems).
For information:

> xinput list
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ PS/2 Generic Mouse                        id=11   [slave  pointer  (2)]
⎜   ↳ SynPS/2 Synaptics TouchPad                id=12   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Sleep Button                              id=8    [slave  keyboard (3)]
    ↳ HP HD Camera: HP HD Camera                id=9    [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=10   [slave  keyboard (3)]
    ↳ HP Wireless hotkeys                       id=13   [slave  keyboard (3)]
    ↳ HP WMI hotkeys                            id=14   [slave  keyboard (3)]

And:
xserver-xorg-input-synaptics/bionic,now 1.9.0-1ubuntu1 amd64 [installed]

Any suggestion to improve my touchpad experience?
Cheers,
JP