text:
Q: PyDev plugin for Eclipse I just installed the PyDev plugin for Eclipse. Everything seems to be configured properly but I do not see syntax highlighting. D you know what might be the problem?

A: You're probably not opening the file with the PyDev editor.
Make sure that the file association in window > preferences > general > editors > file associations for .py files is correct (it should be marked to be opened by Python Editor as the default option).
If it still didn't open, you can try right-clicking the file and choosing 'Open With > Python Editor'
Also, I'd recommend you follow the PyDev Getting Started Guide


text:
Q: Draw table with row and column count given with angularjs Let's say I have defined the following variables in my controller:
$scope.rows, $scope.columns
I should draw a table in my html file, that has $scope.rows amount of rows and $scope.columns amount of columns.
(Later they will be coloured with jQuery...)
Any ideas?

A:

In your Controller:
$scope.columns = new Array(10);
$scope.rows = new Array(10);

The you could also do this in a function like :
$scope.setSizeOf(column, rows){
$scope.columns = new Array(column);
    $scope.rows = new Array(rows);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: For the given function find k such that f(x)≠f(x+k) for any value of x
Let $f(x)=\frac{x}{x^2+k}$ then find k such that $f(x)≠f(x+k)$ for any
  value of x.

In my first attempt, I tried to solve $f(x)=f(x+k)$. But on solving this further, I get a biquadratic(including terms of odd power). Hence, I cannot impose any condition on k from here.
Here are some other things I observed about this function:
A) Function will be continuous for positive values of k and will be discontinuous for negative values of k.
B) $f(x)=f(x+k)$ means that the function is periodic with period k. If the function is periodic about k, then we can write for integers n that $f(x-nk)=f(x+nk)$ .
But I don't know where to go with this analysis.
How to solve this question?

A: $f(x+k)=\dfrac{k+x}{(k+x)^2+1}$
$f(x+k)=f(x)$ if $\dfrac{k+x}{(k+x)^2+k}=\dfrac{x}{k+x^2}$
which is
$$\dfrac{k+x}{(k+x)^2+k}-\dfrac{x}{k+x^2}=0$$
Together
$$\frac{-kx^2+k^2-k x^2}{\left(k+x^2\right) \left(k^2+2 k x+k+x^2\right)}=0$$
which is verified if the numerator is zero
$$k \left(x^2+k x-k\right)=0$$
That is $x=\dfrac{-k\pm\sqrt{k^2+4k}}{2}$
We want NO solutions for this equation, so we put
$k^2+4k<0$ that is $-4<k<0$
for $k\in(-4,\;0)$ doesn't happen that $f(x+k)=f(x)$
Hope this helps
PS
also for $k=-4$ doesn't happen that $f(x-4)=f(x)$
so we can say
for $k\in[-4,\;0)$ doesn't happen that $f(x+k)=f(x)$
for $k=0$ we get the same function so the are identical


text:
Q: How do I get the definition for a sense in NLTK's senseval module? In the NLTK senseval module, senses are of the form HARD1, HARD2, etc. (see source here). However, there doesn't seem to be a way to get the actual definition. I'm trying to implement the Lesk algorithm, and I'm now attempting to check whether the sense predicted by the Lesk algorithm is correct (using a definition from WordNet).
The problem I'm running into is how to unify the WordNet definition with the senseval answer (HARD1, HARD2). Does anybody know how to translate the SENSEVAL sense into a definition, or look it up somewhere?

A: I ended up finding out that these correspond to the senses in WordNet 1.7, which is pretty archaic (doesn't seem easily installable on Mac OS X or Ubuntu 11.04).
There are no online versions of WordNet 1.7 that I could find.
This site also has some useful information about these three corpora. For example, it says that the six senses of interest were taken from the  Longman English Dictionary Online (circa 2001). See here
It describes the source of HARD as WordNet 1.7.
Ultimately, I ended up manually mapping the definitions to those in WordNet 3.0. If you're interested, here's the dictionary. Note, however, that I'm not an expert on linguistics, and they're not exact
# A map of SENSEVAL senses to WordNet 3.0 senses.
# SENSEVAL-2 uses WordNet 1.7, which is no longer installable on most modern
# machines and is not the version that the NLTK comes with.
# As a consequence, we have to manually map the following
# senses to their equivalent(s).
SV_SENSE_MAP = {
    "HARD1": ["difficult.a.01"],    # not easy, requiring great physical or mental
    "HARD2": ["hard.a.02",          # dispassionate
              "difficult.a.01"],
    "HARD3": ["hard.a.03"],         # resisting weight or pressure
    "interest_1": ["interest.n.01"], # readiness to give attention
    "interest_2": ["interest.n.03"], # quality of causing attention to be given to
    "interest_3": ["pastime.n.01"],  # activity, etc. that one gives attention to
    "interest_4": ["sake.n.01"],     # advantage, advancement or favor
    "interest_5": ["interest.n.05"], # a share in a company or business
    "interest_6": ["interest.n.04"], # money paid for the use of money
    "cord": ["line.n.18"],          # something (as a cord or rope) that is long and thin and flexible
    "formation": ["line.n.01","line.n.03"], # a formation of people or things one beside another
    "text": ["line.n.05"],                 # text consisting of a row of words written across a page or computer screen
    "phone": ["telephone_line.n.02"],   # a telephone connection
    "product": ["line.n.22"],       # a particular kind of product or merchandise
    "division": ["line.n.29"],      # a conceptual separation or distinction
    "SERVE12": ["serve.v.02"],       # do duty or hold offices; serve in a specific function
    "SERVE10": ["serve.v.06"], # provide (usually but not necessarily food)
    "SERVE2": ["serve.v.01"],       # serve a purpose, role, or function
    "SERVE6": ["service.v.01"]      # be used by; as of a utility
}


text:
Q: Why Does Ruffle Play This SWF File Better Than Adobe? I am helping my teacher fix some links in her web quest, both of which involved Flash. However, there is this one link that is troubling me. The link - a BBC interactive - works partially in the Ruffle Flash Player but almost not at all in the official Flash Player. In Ruffle, only the Home and Organs sections work correctly, but the Muscles section is what needed, while in the official Flash Player (both through a link and the downloaded file), only the menu loads, and selecting a section loads a white screen. When run in the debug player, no errors show up. Why does the Ruffle Flash Player play it better than the official one? And, more importantly, how do I fix it entirely, or at least the Muscles section? I have Adobe Creative Cloud and have Adobe Animate downloaded, but the .swf file doesn't open in Animate.
Since there hasn't been an answer to the second part of the question yet after 10 days, I'm removing it from this post. I might make a new post for it sometime in the future if I have time and still need an answer.

A: Although I don't have a precise and definite answer to your problem, as a Flash-ninja who's been with the technology for almost 20 years I will share some insights as will shed some light on the technical nuances, which is — alas — exceeds the comment limits by far.

*

*Why does the Ruffle Flash Player play it better than the official one?
A Flash application goes in a form of an SWF file, which also might have some external extras to download (text, binary, images and also additional SWF modules). There are multiple factors that might render an application unusable.
Why downloaded SWF might fail:

*

*You download the main file, but not the additional files (personally I think this is the cause).

*Application is URL-locked.

*Application has a server back-end it cannot reach because it tries to access it via a relative URL.

*Application has a server back-end it cannot reach because it is published with local-with-files security which doesn't matter via HTTP but matters if you run the application locally.

Why SWF by URL might fail:

*

*Flash treats relative URLs in a very weird way: relatively to the current top-frame location on the current HTML page. If SWF is in different folder than the HTML it belongs to, then relative URLs could lead who knows where.

*Application has a server back-end which rejects requests because SWF without HTML page does not have a valid session.

*Application gets its settings (or checks the environment) from its HTML page which is not present in case of direct SWF link.

Well, then.

*More importantly, how do I fix it entirely, or at least the Muscles section?
Per suggestion above, try to figure (monitor the requests from the working application somehow) all the downloadable additions to the main file and download them as well — then the downloaded version just might work.
Otherwise, there's not much you can do, because of this. As you can see, Ruffle is still far from supporting Flash and ActionScript completely, one incompatible instruction — and the whole application just fails and will continue to fail until Ruffle covers the said instruction as well.


text:
Q: Instagram API - Comment Reply/Delete deprecated but some of platforms still working As you know that Instagram closed
POST /media/{media-id}/comments
DEL /media/{media-id}/comments/comment-id
these endpoints.So we can't delete or reply any comment through Instagram API anymore. But, agorapulse.com still can delete and reply these comments without any other authentications(bussiness account not required).
I just signed up and connect my instagram account (created new one for test) and I can delete or reply comments through this platform but on my own product i'm gettimg an error like endpoint retired.
I also tried to move API from the old one to Graph API but due to privacy updates, we don't have ability to upgrade new Graph API it says that
Access to this data is temporarily disabled for non-active accounts due to changes we are making to the Facebook Platform
So If I have correct Instagram user access_token, how can I still delete or reply comments through API ?
Any thoughts?


text:
Q: read a variable while multithreading I get two streams of data from an API, so there are 3 threads, main one, stream1 and stream2. Stream1 and Stream2 need to process this data and once they're done they store them on main_value1 and main_value2.
From main thread I need to read the last value at any given time (so if I need this value and it is still processing then I get the last processed/stored one), what would be the optimal way? from the code example here I need help in coding functions get_main_value1() and, of course, get_main_value2()
def stream1():
    while True:
         main_value1 = process()
def stream2():
    while True:
        main_value2 = process2()
def get_main_value1(): ?
def get main_value2(): ?
def main():
    threading.Thread(function=stream1,).start()
    threading.Thread(function=stream2).start()
    while True:
        time.sleep(random.randint(0,10))
        A = get_main_value1()
        B = get_main_value2()

A: One way would be to make them global:
STREAM1_LAST_VALUE = None
def stream1():
    global STREAM1_LAST_VALUE
    while True:
         main_value1 = process()
         STREAM1_LAST_VALUE = main_value1

STREAM2_LAST_VALUE = None
def stream2():
    global STREAM2_LAST_VALUE
    while True:
        main_value2 = process2()
        STREAM2_LAST_VALUE = main_value2

def get_main_value1():
    return STREAM1_LAST_VALUE

def get main_value2():
    return STREAM2_LAST_VALUE

def main():
    threading.Thread(function=stream1,).start()
    threading.Thread(function=stream2).start()
    while True:
        time.sleep(random.randint(0,10))
        A = get_main_value1()
        B = get_main_value2()


text:
Q: Resolve all less file symlinks with nodejs I want to use gulp file with Magento instead of native grunt that Magento provides as a default build system for compilation of less files.Due to very slow nature of grunt, I decided to make own custom gulp workflow.
Gulp has many features and it is super fast then grunt.So far I have installed gulp, gulp-less and gulp-autoprefixer node plugins for ease of use.
This is the initial code for gulpfile.js in the root of the Magento application.
var fs = require('fs'),
    gulp = require('gulp'),
    less = require('gulp-less'),
    autoprefixer = require('gulp-autoprefixer'),
    sourcemaps = require('gulp-sourcemaps'),
    watch = require('gulp-watch'),
    livereload = require('gulp-livereload');

    //browserSync = require('browser-sync').create();

var themeconfig = {
    area: 'frontend',
    name: 'Magento/newtheme',
    locale: 'en_US',
}

var pubdir = 'pub/static/frontend/' + themeconfig.name + '/' + themeconfig.locale + '/**/*.less';
var cssdir = 'pub/static/frontend/' + themeconfig.name + '/' + themeconfig.locale + '/' + 'css/';

var filestowatch = [
        cssdir + 'styles-l.less',
        cssdir + 'styles-m.less',
        cssdir + 'custom.less',
];

var assetstowatch = fs.realpathSync(pubdir);

Now as per the code, I first import all the plugins and then made a custom config object for theme name and locale in Magento.
What I want to do is to resolve all the symlinks inside pub directory for gull watch so that when any of the file changes, I can automate the process and compile less files.
But as gulp not watches for symlinks, I decided to make it as a glob pattern and resolve these all files and tried to make array of those all resolved files so that afterwards I can simply put that array inside gulp.watch function like that.
But because pubdir variable is glob, node filesystem function realpathSync is not accepting it as an argument and throws the error about ** is not a directory.
How to accomplish this task for resolving all of the symlinks to array of actual paths? So that assetstowatch is an array of all the files that needed to be watched.
gulp.task('lesscss', async function(){

    gulp.src(filestowatch)
        .pipe(sourcemaps.init())
        .pipe(less())
        // .pipe(autoprefixer({
        //    cascade: false
        // }))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(cssdir))
        .pipe(livereload());
        //.pipe(browserSync.stream());
});

gulp.task('watch',function() {
    livereload.listen();
    gulp.watch(assetstowatch,gulp.series('lesscss'));
})

A: Finally, I succeeded in getting the array of all the paths relative to the project root in windows with this code in nodejs.
I put this code after the declaration of variable filestowatch.
var files = glob.sync(pubdir,{realpath:true});
var assetstowatch = [];
files.forEach(function(file,index){
    resolve = require('path').resolve;
    var actualwinpath = path.relative(process.cwd(),resolve(file));
    assetstowatch.push(actualwinpath.replace(/\\/g,"/"));
})

What it does is first creates files array with the help of glob.sync where we use a realpath to true to generate an actual path of all symlinks.
Then we initialize an empty array for assetstowatch which will be our files that needs to be watched.
But because these paths are absolute, we use a forEach loop to iterate through all of the paths and with the help of resolve and path.relative, we get the relative paths relative to our project root.
And due to the use of ugly backslashes in windows os for paths, we replaced them with forward slashes and pushes each entry to assetstowatch array to generate the files to watch.
And that's it. We have generated custom gulp workflow which can be run from the project root after publishing symlinks to the pub folder. Any changes in symlink will now be watched with gulp and thus cause the lesscss task to run.
What we just need to do is
gulp watch
Anyone can use this whole gulpfile.js in project root for gulp less compilation.
var fs = require('fs'),
    glob = require('glob'),
    path = require('path'),
    gulp = require('gulp'),
    less = require('gulp-less'),
    autoprefixer = require('gulp-autoprefixer'),
    sourcemaps = require('gulp-sourcemaps'),
    watch = require('gulp-watch'),
    livereload = require('gulp-livereload'),
    Glob = glob.Glob;

var themeconfig = {
    area: 'frontend',
    name: 'Magento/newtheme',
    locale: 'en_US',
}

var pubdir = 'pub/static/frontend/' + themeconfig.name + '/' + themeconfig.locale + '/**/*.less';
var cssdir = 'pub/static/frontend/' + themeconfig.name + '/' + themeconfig.locale + '/' + 'css/';

var filestowatch = [
        cssdir + 'styles-l.less',
        cssdir + 'styles-m.less',
        cssdir + 'custom.less',
];

var files = glob.sync(pubdir,{realpath:true});
var assetstowatch = [];
files.forEach(function(file,index){
    resolve = require('path').resolve;
    var actualwinpath = path.relative(process.cwd(),resolve(file));
    assetstowatch.push(actualwinpath.replace(/\\/g,"/"));
})

gulp.task('lesscss', async function(){
    gulp.src(filestowatch)
        .pipe(sourcemaps.init())
        .pipe(less())
        // .pipe(autoprefixer({
        //    cascade: false
        // }))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(cssdir))
        .pipe(livereload());
        //.pipe(browserSync.stream());
});

gulp.task('watch',function() {
    livereload.listen();
    gulp.watch(assetstowatch,gulp.series('lesscss'));
})


text:
Q: Is there any way to access the accelerometer from the Apple Watch? It doesn't look like WatchKit released today has such API included.

A: No. Direct access to the Apple Watch sensors (which include the accelerometer) is not possible.
As always, if this is something you'd like, please file a request for it at https://bugreport.apple.com.

A: Update for watchOS 4 & iOS 11: Gyroscope data (rotation rate) is now also available and all of the sensor data from the watch can be accessed via the updated CoreMotion interface.
More specifically CMDeviceMotion gets you:

*

*attitude & rotation rate

*gravity & user acceleration

*calibrated magnetic field

*...

Implementation of the accelerometer with CMDeviceMotion:
class InterfaceController: WKInterfaceController {

let motionManager = CMMotionManager()

override func awake(withContext context: Any?) {
    super.awake(withContext: context)
    motionManager.deviceMotionUpdateInterval = 0.1
}

override func willActivate() {
    super.willActivate()
    if motionManager.isDeviceMotionAvailable {
        let coreMotionHandler : CMDeviceMotionHandler = {(data: CMDeviceMotion?, error: Error?) -> Void in
            // do something with data!.userAcceleration
            // data!. can be used to access all the other properties mentioned above. Have a look in Xcode for the suggested variables or follow the link to CMDeviceMotion I have provided
        }
        motionManager.startDeviceMotionUpdates(to: OperationQueue.current!, withHandler: coreMotionHandler)
    } else {
        //notify user that no data is available
    }
}

override func didDeactivate() {
    super.didDeactivate()
    motionManager.stopDeviceMotionUpdates()
}
}

Notes on the implementation above:
While this method will get you from A to B in terms of getting some real time data from the Apple Watch, a much nicer and definitely more production ready version awaits in this official Apple tutorial, which explains how to separate the sensor logic from the InterfaceController in a separate model etc. - extremely useful, in my opinion.

A: Sensor Data information is now available in Watchkit for watchOS 2.0.
You could check this information in the following session which is total 30 minutes presentation.If you do not want to watch entire session, then you directly jump to the CoreMotion and HealthKit features which is in between 22-28 min:
WatchKit for watchOS 2.0 Session in WWDC 2015
Heart Rate Implementation
https://developer.apple.com/documentation/healthkit/hkworkout
Accelerometer Implementation
Here is the implementation of accelerometer in WatchKit Extension, Here is the reference:
import WatchKit
import Foundation
import CoreMotion

class InterfaceController: WKInterfaceController {

    @IBOutlet weak var labelX: WKInterfaceLabel!
    @IBOutlet weak var labelY: WKInterfaceLabel!
    @IBOutlet weak var labelZ: WKInterfaceLabel!
    let motionManager = CMMotionManager()

    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)

        motionManager.accelerometerUpdateInterval = 0.1
    }

    override func willActivate() {
        super.willActivate()

        if (motionManager.accelerometerAvailable == true) {
            let handler:CMAccelerometerHandler = {(data: CMAccelerometerData?, error: NSError?) -> Void in
                self.labelX.setText(String(format: "%.2f", data!.acceleration.x))
                self.labelY.setText(String(format: "%.2f", data!.acceleration.y))
                self.labelZ.setText(String(format: "%.2f", data!.acceleration.z))
            }
            motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: handler)
        }
        else {
            self.labelX.setText("not available")
            self.labelY.setText("not available")
            self.labelZ.setText("not available")
        }
    }

    override func didDeactivate() {
        super.didDeactivate()

        motionManager.stopAccelerometerUpdates()
    }
}

Code for WatchOS 7.x
import WatchKit
import Foundation
import CoreMotion

class InterfaceController: WKInterfaceController {

    @IBOutlet weak var labelX: WKInterfaceLabel!
    @IBOutlet weak var labelY: WKInterfaceLabel!
    @IBOutlet weak var labelZ: WKInterfaceLabel!

    let motionManager = CMMotionManager()

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)
        motionManager.accelerometerUpdateInterval = 0.1
    }

    override func willActivate() {
        super.willActivate()

        if (motionManager.isAccelerometerAvailable == true) {
            let handler:CMAccelerometerHandler = {data,error in
                self.labelX.setText(String(format: "%.2f", data!.acceleration.x))
                self.labelY.setText(String(format: "%.2f", data!.acceleration.y))
                self.labelZ.setText(String(format: "%.2f", data!.acceleration.z))
            }
            motionManager.startAccelerometerUpdates(to: OperationQueue.current!, withHandler: handler)
        }
        else {
            self.labelX.setText("not available")
            self.labelY.setText("not available")
            self.labelZ.setText("not available")
        }
    }

    override func didDeactivate() {
        super.didDeactivate()
        motionManager.stopAccelerometerUpdates()
    }

}

A: We will get it most likely next year, when Apple will allow us to build full applications. Until now it's only UI, Glances and Notifications.
Update: Apple has provided developer APIs for it now. Check casillas's answer.


text:
Q: How to make a angular service listen to an event without injecting it? I have a login module , on login I will Fire event
$rootScope.$broadcast('onlogin');
I have another service timerService, which will listen to the onLogin event , after that it will start a timer to validate the session.
Since timerService has not been injected , it is not created and will not listen to event .
how to overcome this problem? I don't want to inject the timerService.


text:
Q: How to get the returned value of the event listener keyboardframechanged in Appcelerator Titanium? In this link Titanium.App-event-keyboardframechanged it says that : " The event returns the dictionary containing keyboardFrame.x", I am new in programming so I want to know how to get keyboardFrame.width from this event, here is the code:
Ti.App.addEventListener("keyboardframechanged",function(e){alert("keyboard changed");});

Thanks

A: As far as I know JS, you can't return values for handler/callback functions. However, they usually provide the values via the event object, which would be e inside the function. Try inspecting what e contains.
Ti.App.addEventListener("keyboardframechanged",function(e){
  //something like e.keyboardFrame.x
});

A: Like this:
Ti.App.addEventListener("keyboardframechanged",function(e){
    alert( e.width );
    alert( e.keyboardFrame.width );
});

One of the 2 alerts must work
Cheers


text:
Q: Removing the first date and timestamp in each line of a log file using Python I have a series of log files in text file format.
The document format is this:
[2021-12-11T10:21:30.370Z]  Branch indexing
[2021-12-11T10:21:30.374Z]  Starting the program with default pipeID
[2021-12-11T10:21:30.374Z]  Running with durable level: max_survivbility will make this program crash if left running for 20 minutes
[2021-12-11T10:21:30.374Z]  Starting the program with default pipeID

Each line in the document starts with:[2021-12-11T10:21:30.370Z]
I want to remove the first set of characters that represent date and timestamp and have a result something like this:
Branch indexing
Starting the program with default pipeID
Running with durable level: max_survivbility will make this program crash if left running for 20 minutes
Starting the program with default pipeID

Can anyone please help me explain how I can do this?
I tried to use this method but it doesn't work since I have '[]' in the date stamp.
import re
text = "[2021-12-11T10:21:30.370Z]  Branch indexing"
re.sub("[.*?]", "", text)

This doesn't work for me.
If I try the same method on a text like text = "<2021-12-11T10:21:30.370Z>  Branch indexing".
import re
text = "<2021-12-11T10:21:30.370Z>  Branch indexing"
re.sub("<.*?>", "", text)

It removes <2021-12-11T10:21:30.370Z>. Why does this not work with [2021-12-11T10:21:30.370Z]?
I need help removing every instance of this format "[2021-12-11T10:21:30.370Z]"  in all the log files.
Thank you so much.

A: Your current regex pattern is off because square brackets are regex metacharacters which need to be escaped.  Also, you should be running the regex in multiline mode.  And the timestamp pattern should be more generic.
text = re.sub(r'^\[.*?\]\s+', '', text, flags=re.M)

A: I'd rather go with a simple solution for this case, pal. Split the string where the ] ends, then trim the second element of the resulting list, to remove all those extra spaces and then print it, bud. Hope this helps, cheers!
import re
text = "[2021-12-11T10:21:30.370Z]  Branch indexing"
print(re.split("]", text)[1].strip())


text:
Q: Proper spacing with ellipsis and xspace Really a simple enough question, but I haven't found an answer, so … is there any straightforward way of making the spacing adjustments of ellipsis.sty work with xspace? The package itself has an xspace option, which adds the command to all occurrences of dots, but this seems to come in the way of the spacing, so one needs to use \dots\␣ anyway. I'm not committed to using ellipsis.sty – what I'd like is just proper spacing (for some definition of proper ;)), along with xspace, or some similar mechanism.
Added example
Here's a minimal example to illustrate the behavior:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[xspace]{ellipsis}
\begin{document}
\noindent
x \dots x\\
x … x\\
x \dots\ x\\
x …\ x
\end{document}

This also includes Unicode ellipses, which are part of my motivation – the ability to typeset externally generated text directly, without inserting explicit spacing commands.
Here's how it looks:

Here's how it looks without the xspace option:

And here, without ellipsis.sty altogether:

The spacing I want is the one I get with both ellipsis.sty and the explicit \␣. But I'd like to get it automatically – at least for the Unicode ellipsis character. It's less crucial that I make it happen for the \dots command.
I guess maybe I shouldn't rely on xspace. Is there any "obviously correct" way to get the proper(?) spacing after the Unicode ellipsis character, though?


text:
Q: How to capture FastForward media keys on audio/video element Thanks to media key support in Browsers (like chrome), it is possible to play/pause an  element using the media keys on your keyboard (or mobile OS).
How do sites like YouTube react to the fastforward/backward keys?
I have not been able to find any documentation on detecting/reacting to those buttons. But it has to be possible, because YouTube (and I think other sites) do it too. Trying to read the JS there is undoable, unfortunately.
Example:

*

*Open any PlayList on YouTube (example: https://www.youtube.com/watch?v=abX559xa9gA&list=PLZhjR9_8QJZs5QA8qi5f2YcYcpl0rgWvd )

*Start the video.

*Press play/pause media key on your keyboard. -> The video reacts.

*Press fastfoward media key on your keyboard. -> The next video plays. How is YouTube doing this?

Answer has been given, although I recommend setting all 4, because on mobile devices "seek" works, on desktop only "next" works.
https://developer.mozilla.org/en-US/docs/Web/API/Media_Session_API
navigator.mediaSession.setActionHandler('seekbackward', function() { /* Code excerpted. */ });
navigator.mediaSession.setActionHandler('seekforward', function() { /* Code excerpted. */ });
navigator.mediaSession.setActionHandler('previoustrack', function() { /* Code excerpted. */ });
navigator.mediaSession.setActionHandler('nexttrack', function() { /* Code excerpted. */ });

A: It can be achieved through Media Session API.
navigator.mediaSession.setActionHandler('seekbackward', function() { /* Code excerpted. */ });
navigator.mediaSession.setActionHandler('seekforward', function() { /* Code excerpted. */ });


text: Q: artificial-intelligence Artificial intelligence (AI) is the branch of computer science and technology that studies the development of machines able to simulate aspects of human intelligence. This tag may also refer to the part of a computer game application that controls the behavior of the virtual characters with which the player may interact during the game.


text:
Q: Back shared element transition between activities I use native Android Transition API to animate transition between activities. Here's the source I use to launch activity:
        Intent intent = new Intent(MainActivity.this, DetailActivity.class);
        Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this, imageView, imageView.getTransitionName()).toBundle();

        MainActivity.this.startActivity(intent, bundle);

When I tap on hardware back button it returns to previous activity with expected reversed transition animation, but when I tap on "Up" button in Toolbar it returns to previous activity with default animation:

A: Add following code to the activity, that is being finished:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            supportFinishAfterTransition();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

Source


text:
Q: Python Image classification trouble shooting Hi guys sorry this might be a dumb question but i've been looking where's this variable came from
def predict(file):

as you can see on 'predict' there a parameter called 'file'
i was wondering where's does the data on 'file' came from
thank you!
here's the full code
import os
import numpy as np
from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array
from keras.models import Sequential, load_model
import time

start = time.time()

# Define Path
# model_path = './models/model.h5'
# model_weights_path = './models/weights.h5'
test_path = 'data/test_image'

# Load the pre-trained models
# model = load_model(model_path)
# model.load_weights(model_weights_path)

# Define image parameters
img_width, img_height = 150, 150

# Prediction Function

def predict(file):
    model_path = './models/model.h5'
    model_weights_path = './models/weights.h5'
    model = load_model(model_path)
    model.load_weights(model_weights_path)
    x = load_img(file, target_size=(img_width, img_height))
    x = img_to_array(x)
    x = np.expand_dims(x, axis=0)
    array = model.predict(x)
    result = array[0]
    # print(result)
    answer = np.argmax(result)
    if answer == 0:
        print("Predicted: Drusen")
    elif answer == 1:
        print("Predicted: Normal")

    return answer

# Walk the directory for every image
for i, ret in enumerate(os.walk(test_path)):
    for i, filename in enumerate(ret[2]):
        if filename.startswith("."):
            continue

        print(ret[0] + '/' + filename)
        result = predict(ret[0] + '/' + filename)
        print(" ")

# Calculate execution time
end = time.time()
dur = end-start

if dur < 60:
    print("Execution Time:", dur, "seconds")
elif dur > 60 and dur < 3600:
    dur = dur/60
    print("Execution Time:", dur, "minutes")
else:
    dur = dur/(60*60)
    print("Execution Time:", dur, "hours")

A: The call of predict(file) is as follows:
result = predict(ret[0] + '/' + filename)

So it takes as input a filename. Inside the function, this part
x = load_img(file, target_size=(img_width, img_height))

Uses the load_img function, from the keras.preprocessing.image module. So the file parameter takes a filename, and transforms it into an image there:
x = img_to_array(x)
x = np.expand_dims(x, axis=0)
array = model.predict(x)

It's being added a channel dimension, after being turned into a NumPy array. At the end, its label is predicted.


text:
Q: botocore.excceptions.ClientError: An error occurred (InvalidTextEncoding) when calling the SelectObjectContent operation while executing below code through python
response= S3.select_object_content(Bucket=S3_bucket_name,Key=S3_file_Key,ExpressionType='SQL', Expression="select count(*) from s3object", InputSerialization={'CSV': {"FileHeaderInfo": header_usage},'CompressionType':compressformat}, OutputSerialization={'CSV': {}},)

I am getting error like
Traceback (most recent call last):
  File OutputSerialization={'CSV': {}},)
  File "/usr/local/lib/python2.7/site-packages/botocore/client.py", line 320, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/usr/local/lib/python2.7/site-packages/botocore/client.py", line 623, in _make_api_call
    raise error_class(parsed_response, operation_name)

**ClientError: An error occurred (InvalidTextEncoding) when calling the SelectObjectContent operation: UTF-8 encoding is required. The text encoding error was found near byte 49,152.**

I searched for Invalid text Encoding in boto3 but couldn't found.
Can you please help me to check this?
Thanks in advance

A: The data you wish you receive has the wrong Output serialization. The output serialization Describes the format of the data that you want Amazon S3 to return in response, and you are asking it to return a format that has the wrong encoding. I cannot test your code myself because I only have small bits of it, but you need to encode your serialized output to utf-8 format, otherwise the Amazon S3 storage service can't serialize your response. Probably you need to expand OutputSerialization={'CSV': {}} to make sure that your respone is coded in UTF-8 format.
Maybe these resources can help you:
Select object content parameter guide
select Object Content description

A: Sadly "UTF-8 encoding is required." means that object is not matching required format.
Reference: https://docs.aws.amazon.com/AmazonS3/latest/API/API_SelectObjectContent.html
UTF-8 - UTF-8 is the only encoding type Amazon S3 Select supports.


text:
Q: How to sort with dynamic column and dynamic sort direction in pl/sql How to write a pl/sql with dynamic column and dynamic sort direction for example:-
select * from table order by "dynamic column" "dynamic sort order";

A: You basically need to construct your sql command as a string and then execute it dynamically.
DECLARE
  TYPE EmpCurTyp  IS REF CURSOR;
  v_emp_cursor    EmpCurTyp;
  emp_record      employees%ROWTYPE;
  v_stmt_str      VARCHAR2(200);
  v_order         VARCHAR2(30);
  v_e_job         employees.job%TYPE;
BEGIN
  -- Dynamic SQL statement with placeholder:
  v_order := 'emplid DESC';
  v_stmt_str := 'SELECT * FROM employees WHERE job_id = :j ORDER BY ' || v_order;

  -- Open cursor & specify bind argument in USING clause:
  OPEN v_emp_cursor FOR v_stmt_str USING 'MANAGER';

  -- Fetch rows from result set one at a time:
  LOOP
    FETCH v_emp_cursor INTO emp_record;
    EXIT WHEN v_emp_cursor%NOTFOUND;
  END LOOP;

  -- Close cursor:
  CLOSE v_emp_cursor;
END;
/

A: You can use dynamic SQL & REF CURSORS to build queries dynamically
DECLARE
    TYPE cur_typ IS ref CURSOR;
    emp_rec_cursor CUR_TYP;
    v_query_str    VARCHAR2(2000);
    v_sort_order   VARCHAR2(10) := 'DESC';
    v_column       VARCHAR2(20) := 'NAME';
    v_empid        emp.empid%TYPE;
    v_name         emp.name%TYPE;
    v_salary       emp.salary%TYPE;
BEGIN
    query_str := 'SELECT empid, name, salary FROM emp order by '
                 || v_column   -- reassign v_column as needed
                 || '  '
                 || v_sort_order; -- reassign v_sort_order as needed

    OPEN emp_rec_cursor FOR query_str;

    LOOP
        FETCH emp_rec_cursor INTO v_empid, v_name, v_salary;

        EXIT WHEN emp_rec_cursor %NOTFOUND;
    -- process row here
    END LOOP;

    CLOSE emp_rec_cursor;
END;


text:
Q: How to call Await functions inside Realm.open function? i was trying to integrate Realm db to my project
Model File :

export const CHAT_LIST_SCHEMA = {
  name: 'ImList',
  properties: {
    name: 'string',
    rid: 'string',
    lastMessage: 'string',
    time: 'string',
  },
};

Code :

init = async () => {
    try {
      Realm.open({ schema: CHAT_LIST_SCHEMA }).then((realm) => {
        let cachedData = realm.objects('ImList');
        console.log('Cached Data', cachedData);
        if (cachedData === '') {
          console.log('called123');
          this.setState({ data: cachedData });
        } else {
          console.log('called');
        const result = await RocketChat.getIMlist(); // API Call
        const data = await RocketChat.getRoomsList(result); // Filtering
          realm.write(() => {
            data.map((items) => {
              realm.create('ImList', {
                name: items.name,
                rid: items.rid,
                lastMessage: items.lastMessage,
                time: items.time,
              });
            });
          });
        }
      });
    } catch (error) {
      console.log(error);
    }
  };

But it shows I cant call await outside an async function, but I only need to get data from the API, if the DB is empty. What to do?

A: You have put async on the wrong function. The one waiting for async methods is arrow function inside .then statement, so it should look like:
init = () => {
    try {
      Realm.open({ schema: CHAT_LIST_SCHEMA }).then(async (realm) => {
        let cachedData = realm.objects('ImList');
        console.log('Cached Data', cachedData);
        if (cachedData === '') {
          console.log('called123');
          this.setState({ data: cachedData });
        } else {
          console.log('called');
        const result = await RocketChat.getIMlist(); // API Call
        const data = await RocketChat.getRoomsList(result); // Filtering
          realm.write(() => {
            data.map((items) => {
              realm.create('ImList', {
                name: items.name,
                rid: items.rid,
                lastMessage: items.lastMessage,
                time: items.time,
              });
            });
          });
        }
      });
    } catch (error) {
      console.log(error);
    }
  };

btw. you can also await the Realm.open function -> less nesting :)


text:
Q: Trying to install bosh lite, not able to set the target bosh target 192.168.50.4 lite
Usage: target [] [] [--ca-cert FILE]
$ bosh status
Config
             /Users/laled/.bosh_config
Director
  not set
Deployment
  not set

A: Strange, the command you entered should work.
bosh target IP <alias>

Perhaps update to latest BOSH CLI version and try again.


text:
Q: How to add Custom attribute on minicart? I need to display custom product attribute in mini cart for each product in the cart. How to get attribute value. please see below screenshot.
https://prnt.sc/-99NK5eeFgAZ
Thanks,
Kiran

A:
app/code/Dotsquares/CustomAttribute/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            'Magento_Checkout/template/minicart/item/default.html': 'Dotsquares_SellerLocator/template/minicart/item/default.html'
        }
    }
};

app/code/Dotsquares/CustomAttribute/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\CustomerData\DefaultItem">
        <plugin name="AddAttPlug" type="Dotsquares\CustomAttribute\Plugin\DefaultItem" />
    </type>
</config>

app/code/Dotsquares/CustomAttribute/Plugin/DefaultItem.php

<?php

namespace Dotsquares\SellerLocator\Plugin;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Quote\Model\Quote\Item;

class DefaultItem
{
    protected $_productloader;

    public function __construct(
        \Magento\Catalog\Model\ProductFactory $_productloader
    )
    {
        $this->_productloader = $_productloader;
    }

    public function aroundGetItemData($subject, \Closure $proceed, Item $item)
    {
        $data = $proceed($item);

        /** @var Product $product */
        $product = $this->_productloader->create()->load($item->getProduct()->getId());

        $atts = [
            "custom_value" => $product->getCustomValue()
        ];

        return array_merge($data, $atts);
    }
}

app/code/Dotsquares/CustomAttribute/view/frontend/web/template/minicart/item/default.html

                    <input data-bind="attr: {
                           id: 'cart-item-'+item_id+'-qty',
                           'data-cart-item': item_id,
                           'data-item-qty': qty,
                           'data-cart-item-id': product_sku
                           }, value: qty"
                           type="number"
                           size="4"
                           class="item-qty cart-item-qty"/>
                <button data-bind="attr: {
                           id: 'update-cart-item-'+item_id,
                           'data-cart-item': item_id,
                           title: $t('Update')
                           }"
                            class="update-cart-item"
                            style="display: none">

                    </button>

A: How can we add the validations like,
if(attribute1 == "Some Text"){
 Then show Attribute2;

}
How can we achieve it in Default.html ?
How to add the condition in html for the custom attribute. @Dotsquares


text:
Q: Invalid object name "CAccounts" I keep getting this error:

Invalid object name "CAccounts".

and the code I have is:
System.Threading.Thread thread = new System.Threading.Thread(() =>
{
    // Set ConnectionString.
    String sConSg =
    "CONNSTRING HERE";

    using (SqlConnection connection = new SqlConnection(sConSg))
    {
        try
        {
            connection.Open();
        }
        catch (Exception exception)
        {
            MessageBox.Show(stat.Text = exception.Message);
        }

        try
        {
            SqlDataReader slrr = null;
            SqlCommand command = new SqlCommand("SELECT ActivationCode FROM CAccounts WHERE ActivationCode = " +
                "'" + _activationcode.Text + "'", connection);
            slrr = command.ExecuteReader();

            while (slrr.Read())
            {
                if (slrr["ActivationCode"].ToString() == _activationcode.Text)
                {
                    MessageBox.Show(slrr["ActivationCode"].ToString(), "AutoOptimise");

                }
                else
                {
                }
            }
        }
        catch (Exception exception)
        {
            MessageBox.Show(stat.Text = exception.Message);
        }
    }

});
thread.Start();

Can somebody please shed some light?

A: The table CAccounts you're referencing in your select clause probably doesn't exist in the database. Check that.
See a list of possibilities here:
http://web.archive.org/web/20150519073601/http://sqlserver2000.databases.aspfaq.com:80/why-do-i-get-object-could-not-be-found-or-invalid-object-name.html

A: I'd suggest these things:

*

*check which schema the object CAccounts is under. Is it dbo or other? Does the user have permissions on that schema?

*login to SQL Server via Management Studio. Use the credentials in the connection string that the code is using. Paste & run the SQL statement above.

*use SQL Profiler to capture/verify ensure the SQL statement as it crosses to your SQL Server. Run THAT as an adhoc query against that SQL Server.

*are there any funny DNS issues? Hosts files? Does this happen during debugging or on the app server?

*is the database server name correct? i.e. localhost versus a named server. Try addressing by the IP address that you expect it to be run at, just for fun, both in your connection string, and via SSMS.

A: Instead of CAccounts, I had to label it DATABASENAME.dbo.CAccounts.
So it would be something like:
"SELECT * FROM DATABASENAME.db.CAccounts"

A: This might work:
SqlConnection con = new SqlConnection("Data Source=192.168.1.12;Initial Catalog=Ibrahim;User ID=sa;Password=1412;");
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into Ibrahim.EVC_Activation_Val (Date,Dealer,Transaction_ID,Invoice_ID,Mobile_Num,Quantity_LE) values('" + DateTimePicker1.Value.ToString("yyyy/mm/dd") + "','" + Txtbx1.Text + "','" + Txtbx2.Text + "','" + Txtbx3.Text + "','" + Txtbx4.Text + "','" + Txtbx5.Text  + "')",con);
            cmd.ExecuteNonQuery();
            MessageBox.Show("Saved");
            con.Close();


text:
Q: paradox with periodic measurements under broadband noise Let's say I'm trying to measure a quantity which varies in time as:
$$f(t) = (\text{unknown constant } Q) + (\text{broadband noise})$$
where "broadband noise" has a known power spectrum with a finite bandwidth.
I want to measure the constant $Q$, so I repeatedly take measurements $f(0), f(1), f(2), \ldots$ to formulate a guess:
$$Q_N = (f(0) + f(1) + \cdots + f(N-1))/N$$
Obviously, if I take enough measurements, I'll get the right answer, i.e. $\lim_{N\rightarrow \infty} Q_N = Q$.
My question is: As $N \rightarrow \infty$, does $\langle |Q_N - Q|\rangle \propto N^{-1/2}$ or $\propto N^{-1}$? Paradoxically, I have seemingly-convincing arguments for both.
Case for $N^{-1}$:
If you break down the vibration into sinusoids, each gives an error contribution that looks like something proportional to $\frac1N(\cos(\phi) + \cos(\phi + ω) + \cos(\phi + 2ω) + \cdots)$. Although the term in parentheses looks kinda like a random walk, it's actually bounded, so the error goes as 1/N. (Unless ω is 2π times an integer, which is vanishingly unlikely; anyway you can assume the noise is at ω < 0.1.) Well, if that's true for a sinusoid, it should be true for broadband noise which is just a sum of sinusoids. So we conclude that the error goes as $N^{-1}$.
Case for $N^{-1/2}$:
When you approximate $Q$ with $f(t)$, there is obviously an error in this approximation. The error depends on the instantaneous noise environment. Beyond the correlation time of the noise, the errors are all uncorrelated with each other. When you add up uncorrelated errors, it's a random walk, so the error goes as $N^{-1/2}$.
At least one of these two arguments must be wrong! Thanks in advance!!

A: If I understand your question correctly, notice that while the vibration has bounded error, it still fluctuates, something like $\cos(N\omega)$, in a similar fashion to a random walk. In particular, $\cos(\phi+\omega n)$ will tend to stick near $\pm 1$, due to the weird properties of $\cos(U)$ where $U$ is uniformly random and hence be similar to a standard random walk. These fluctuations will cause the increase of error from $1/N$ to $1/\sqrt{N}$.
Let $X_n=\cos(\phi+\omega n)$. Then you're looking at $\frac{1}{N}\sum_{n=1}^N{X_n}$. Now I'm just computing in an adhoc way the variance which for each term would be $E[X_n^2]-E[X_n]^2=E[X_n^2]=\cos^2(\phi+n\omega)\approx 1$. You can make these arguments rigorous by treating $X_i$ as a random variable $X_i=\cos(U_i)$ where $U_i$ is uniform random on $[0,\pi]$.
Thus the average variance of the error contribution would be something like:
$\frac{1}{N^2}\sum_{k=1}^N \mbox{Var}(X_k)=\frac{1}{N},$
which will look like an error of $N^{-1/2}$.

A: I figured it out eventually.
If you look at the PSD of the noise, you get $N^{-1/2}$ to the extent that the PSD is nonzero at $\omega,2\omega,\ldots$. You get $N^{-1}$ from the noise power at every other frequency away from the integer multiples of $\omega$.
If you assume (as I did in the question) that the noise bandwidth is strictly limited to frequencies away from integer multiples of $\omega$, then that's a very restrictive assumption about the time-domain profile. It mandates relationships between points that are arbitrarily far apart in time. So that undermines the "Case for $N^{-1/2}$" that I wrote down. The answer in this case is $N^{-1}$.


text:
Q: How to remove a non-empty directory with OCaml? I tried to remove a directory using Sys.remove "mydir", but this results in an exception: Exception: Sys_error u"mydir: Is a directory"..
Next I looked at Unix.rmdir "mydir", but that did not work because the directory is not empty (it resulted in Exception: Unix.Unix_error (27, "rmdir", "mydir").
So I guess the only way to delete a non-empty directory is to get the list of files in the directory using Sys.readdir "mydir", then delete its contents recursively before finally deleting the empty directory using Unix.rmdir.
What is the idiomatic way of removing a non-empty directory using OCaml?

A: You have to recursively remove its contents first, using Sys.remove and Sys.readdir, and, once it is empty, remove the directory itself, e.g.,
let rec rmrf path = match Sys.is_directory path with
  | true ->
    Sys.readdir path |>
    Array.iter (fun name -> rmrf (Filename.concat path name));
    Unix.rmdir path
  | false -> Sys.remove path

Alternatively, you can use the OCaml Fileutils library, which provides POSIX compliant file utilities, namely the rm function, that could recursively (and portably) delete the whole directory, e.g.,
 FileUtil.rm ~recurse:true [dir]


text:
Q: CSS How to position select box options grid to left? My code belove
https://jeremi.w3spaces.com/button_css.html
Problem is if I add padding to select box making select box blue and touch friendly the options listbox is not aligned properly. Listbox maintains relative position to the select box without padding. I want to move the listbox to left 20px so that it's postion is aligned with padding.
Edit code to expand and make button colorfull:
select {
  #display: none; /*hide original SELECT element:*/
  padding: 15px 5px 15px 15px;
  border: none;
  font-family: Verdana;
  font-weight: bold;
  background-color: DodgerBlue;
  color: white;
  outline: none;
  min-width: 150px;
  #border-color: DodgerBlue;
  /*Muokataan nuoli kaikissa selaimissa*/
  #appearance: none;
  #-moz-appearance: none;
  #-webkit-appearance: none;
  #&::-ms-expand { display: none };
 }

A: I was able to fix this. I move padding off from div and to select box native define so it resized selectbox natively acording with padding.


text:
Q: Securing Spring (4.2.8.RELEASE) Http Remote methods is causing Error creating bean / No matching factory method found: factory bean Example is now in: https://github.com/theodorebmiller/springSecurityRemoteIssue
I am attempting to secure a method published using HttpInvokerServiceExporter.  When I add @Secured to the method in class being published, I get Error creating bean with name '/DocSaveServiceHttpFacade' defined in class path resource [com/ttiinc/docSaveExample/web/remoteService/docSave/DocSaveServiceHttpRemoteImpl.class]: No matching factory method found: factory bean 'docSaveServiceHttpRemoteFacade'; factory method 'DocSaveServiceHttpRemoteFacade()'. Check that a method with the specified name exists and that it is non-static.
The application already has Spring Security (4.2.8.RELEASE). working at the method level.  I have tested that it works with @Secured commented, but fails when @Secured is present.
I have tried it on more than service, with the same outcomes.
Placing @Secured on a method that is not being exported, everything is just fine.
I have googled the heck out of this, but cannot seem to find anything.
Here is how I have coded it, and the stack trace I am getting.

@Component(value = "docSaveServiceHttpRemoteFacade")
    @Conditional(RemoteBeanPublishingValidator.class)
    public class DocSaveServiceHttpRemoteImpl
                  extends DocSaveServiceRemoteBase {
. . .
@Bean(name = "/DocSaveServiceHttpFacade")
    public HttpInvokerServiceExporter DocSaveServiceHttpRemoteFacade() {
        HttpInvokerServiceExporter exporter =
               new HttpInvokerServiceExporter();
        exporter.setService(this);
        exporter.setServiceInterface(DocSaveService.class);
        return exporter;    }
     ...
@Override  @Secured("InternetUsers")
     public ExpressDocumentBase saveExpressDocument(ExpressDocumentBase doc,
                               InputStream source) {
        return docSaveService.saveExpressDocument(doc, source);
     }

I expected it to work just as it does on non-exported methods.
What I am getting is this:
2019-09-12 11:20:07,550 WARN  org.springframework.web.context.support.AnnotationConfigWebApplicationContext ==> Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '/DocSaveServiceHttpFacade' defined in class path resource [com/ttiinc/docSaveExample/web/remoteService/docSave/DocSaveServiceHttpRemoteImpl.class]: No matching factory method found: factory bean 'docSaveServiceHttpRemoteFacade'; factory method 'DocSaveServiceHttpRemoteFacade()'. Check that a method with the specified name exists and that it is non-static.
2019-09-12 11:20:07,551 ERROR org.springframework.web.context.ContextLoader ==> Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '/DocSaveServiceHttpFacade' defined in class path resource [com/ttiinc/docSaveExample/web/remoteService/docSave/DocSaveServiceHttpRemoteImpl.class]: No matching factory method found: factory bean 'docSaveServiceHttpRemoteFacade'; factory method 'DocSaveServiceHttpRemoteFacade()'. Check that a method with the specified name exists and that it is non-static.
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:549)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1178)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1072)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:187)
    at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:216)
    at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:185)
    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:250)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:96)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:78)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1985)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1487)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1378)
    at java.lang.Thread.run(Thread.java:748)
    at org.jboss.threads.JBossThread.run(JBossThread.java:485)
2019-09-12 11:20:07,557 ERROR org.jboss.msc.service.fail ==> MSC000001: Failed to start service jboss.deployment.subunit."DocSaveExampleEar-tbm_work-SNAPSHOT.ear"."DocSaveExampleWar-tbm_work-SNAPSHOT.war".undertow-deployment: org.jboss.msc.service.StartException in service jboss.deployment.subunit."DocSaveExampleEar-tbm_work-SNAPSHOT.ear"."DocSaveExampleWar-tbm_work-SNAPSHOT.war".undertow-deployment: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '/DocSaveServiceHttpFacade' defined in class path resource [com/ttiinc/docSaveExample/web/remoteService/docSave/DocSaveServiceHttpRemoteImpl.class]: No matching factory method found: factory bean 'docSaveServiceHttpRemoteFacade'; factory method 'DocSaveServiceHttpRemoteFacade()'. Check that a method with the specified name exists and that it is non-static.
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:81)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1985)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1487)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1378)
    at java.lang.Thread.run(Thread.java:748)
    at org.jboss.threads.JBossThread.run(JBossThread.java:485)
Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '/DocSaveServiceHttpFacade' defined in class path resource [com/ttiinc/docSaveExample/web/remoteService/docSave/DocSaveServiceHttpRemoteImpl.class]: No matching factory method found: factory bean 'docSaveServiceHttpRemoteFacade'; factory method 'DocSaveServiceHttpRemoteFacade()'. Check that a method with the specified name exists and that it is non-static.
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:252)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:96)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:78)
    ... 8 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '/DocSaveServiceHttpFacade' defined in class path resource [com/ttiinc/docSaveExample/web/remoteService/docSave/DocSaveServiceHttpRemoteImpl.class]: No matching factory method found: factory bean 'docSaveServiceHttpRemoteFacade'; factory method 'DocSaveServiceHttpRemoteFacade()'. Check that a method with the specified name exists and that it is non-static.
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:549)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1178)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1072)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:187)
    at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:216)
    at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:185)
    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:250)
    ... 10 more
2019-09-12 11:20:07,564 ERROR org.jboss.as.controller.management-operation ==> WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "DocSaveExampleEar-tbm_work-SNAPSHOT.ear")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.subunit.\"DocSaveExampleEar-tbm_work-SNAPSHOT.ear\".\"DocSaveExampleWar-tbm_work-SNAPSHOT.war\".undertow-deployment" => "java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '/DocSaveServiceHttpFacade' defined in class path resource [com/ttiinc/docSaveExample/web/remoteService/docSave/DocSaveServiceHttpRemoteImpl.class]: No matching factory method found: factory bean 'docSaveServiceHttpRemoteFacade'; factory method 'DocSaveServiceHttpRemoteFacade()'. Check that a method with the specified name exists and that it is non-static.
    Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '/DocSaveServiceHttpFacade' defined in class path resource [com/ttiinc/docSaveExample/web/remoteService/docSave/DocSaveServiceHttpRemoteImpl.class]: No matching factory method found: factory bean 'docSaveServiceHttpRemoteFacade'; factory method 'DocSaveServiceHttpRemoteFacade()'. Check that a method with the specified name exists and that it is non-static.
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '/DocSaveServiceHttpFacade' defined in class path resource [com/ttiinc/docSaveExample/web/remoteService/docSave/DocSaveServiceHttpRemoteImpl.class]: No matching factory method found: factory bean 'docSaveServiceHttpRemoteFacade'; factory method 'DocSaveServiceHttpRemoteFacade()'. Check that a method with the specified name exists and that it is non-static."}}


text:
Q: How to pick the right blocks in array matlab? I have some code written in Matlab, I have A 5x5 matrix, where block (1,1), (2,2), (3,3), (4,4), and (5,5) = 1 . I set those blocks to 1 only as a border to separate upper right region and bottom left region of the matrix. My question is how to pick values only from the upper right region, where the value of A > threshold, without the border values of 1?
This is the example, where Threshold 0.43, and the yellow blocks is the border value 1, the green blocks are the result that I want.

I already implemented, but still can't pick the right block that I want. Please Help Thankyou.
nb :
Threshold = 0.43

A = [1 0.03 0.45 0.25 0.046; 0.03 1 0.32 0.11 0.36; 0.45 0.32 1 0.68 0.42; 0.25 0.11 0.68 1 0.55; 0.046 0.36 0.42 0.55 1]

A:  A(triu(A,1)>Threshold)

compare the uppertriangular part of the matrix w/ the threshold to get indices, then use indices to pull from original matrix A


text:
Q: c++ 2d array of class pointers i am trying to create a 2d array holding pointers of my class. first, i'd like to assign all of them NULL:
Timetable::Timetable(int hours) : TimetableBase(hours){
    scheduledLectures = new Lecture**[5];
    for (int i = 0; i < 5; i++) {
        scheduledLectures[i] = new Lecture*[hours];
        for (int j = 0; j < hours; j++)
            scheduledLectures[i][j] = NULL;
    };
}

this is for a timetable generator application. i have a function to set these pointers to a specific object.
void Timetable::setLecture(Lecture& lecture){
    while ((lecture.getDuration()) -1 > 0){
        scheduledLectures[lecture.getDayScheduled()][(lecture.getHourScheduled())+1] = &lecture;
    }
}

the compiler returns no errors for this, but when its running, it seems that the pointers remain NULLs.
i am sure the error is inside the setter function (and almost sure that its a grammar mistake) but i cannot find the solution for that.
whats wrong in here?
thank you

A: Use a vector (or std::array) of pointers or shared_ptrs (or unique_ptrs depending on how your lifetimes are arranged) instead of a 2D array of pointers that you manage yourself.  Save yourself the trouble of managing the memory and lifetimes of your objects manually.
class TimeTable {
    vector<vector<shared_ptr<Lecture>>> scheduledLectures;
};

Timetable::Timetable(int hours)
        : TimetableBase(hours),
        scheduledLectures(5, vector<shared_ptr<Lecture>>(5)) {}

void Timetable::setLecture(std::shared_ptr<Lecture> lecture){
    while ((lecture->getDuration()) -1 > 0) { // not sure what this does
        scheduledLectures[lecture->getDayScheduled()][(lecture->getHourScheduled())+1] = lecture;
    }
}

You can test whether a shared_ptr is null like follows
auto s_ptr = std::shared_ptr<int>{}; // null
// either assign it to a value or keep it null
if (s_ptr) {
    // not null
}

If you are managing the memory of the Lecture objects elsewhere then just use a 2D vector of pointers and trust your code
class TimeTable {
    vector<vector<Lecture*>> scheduledLectures;
};

Timetable::Timetable(int hours)
        : TimetableBase(hours),
        scheduledLectures(5, vector<Lecture*>(5)) {}

void Timetable::setLecture(Lecture& lecture){
    while ((lecture.getDuration()) -1 > 0) { // not sure what this does
        scheduledLectures[lecture.getDayScheduled()][(lecture.getHourScheduled())+1] = &lecture;
    }
}


text:
Q: Jenkins pipeline NoSuchMethodError after upgrade After upgrade the jenkins and plugins I have a problem with pipeline script.
I get an error when I'm trying to run "hello world" script.
Started by user unknown or anonymous
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] End of Pipeline
java.lang.NoSuchMethodError: org.jenkinsci.plugins.workflow.steps.EnvironmentExpander.getSensitiveVariables()Ljava/util/Set;
    at org.jenkinsci.plugins.workflow.cps.DSL.invokeStep(DSL.java:264)
    at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:196)
    at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:124)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:47)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.methodCall(DefaultInvoker.java:20)
    at org.jenkinsci.plugins.pipeline.modeldefinition.agent.impl.LabelScript.run(LabelScript.groovy:42)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.inDeclarativeAgent(ModelInterpreter.groovy:589)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.call(ModelInterpreter.groovy:76)
    at WorkflowScript.run(WorkflowScript:1)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:86)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:113)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
    at sun.reflect.GeneratedMethodAccessor138.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ClosureBlock.eval(ClosureBlock.java:46)
    at com.cloudbees.groovy.cps.Next.step(Next.java:83)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
    at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:136)
    at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:275)
    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:187)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:420)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$400(CpsThreadGroup.java:95)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:330)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:294)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:67)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:139)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:68)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Finished: FAILURE

I have:
workflow-step-api    Pipeline: Step API    625.vd896b_f445a_f8

This plugin has a getSensitiveVariables. I have no idea why I am getting this exception.

A: In the /var/lib/jenkins/plugins were old .hpi and new .jpi files. After deleting .hpi files the problem was sloved.


text:
Q: Connect Two Async Calls The below JavaScript adds a item to a list and a file to a picture library, both in SharePoint. The add function calls the upload function but I don't want the add function to complete until the upload function is complete. Naturally the upload function takes longer most of the time. What is the best way to do this?
Add item to list:
function addNewPunchlistItem() {

var endpointUrl = myURL + "PunchlistTracking/_api/web/lists/getbytitle('Punchlist Items')/items";

if ($('#getFile').val()) {
    uploadFile(myFormDigest, '#getFile', $('#itemNumber').val() + "_image.png");
}

call;

var call = $.ajax({
    url: endpointUrl,
    type: "POST",
    data: JSON.stringify({
        "__metadata": { type: "SP.Data.Punchlist_x0020_ItemsListItem" },
        Title: $('#itemShortDesc').val(),
        FSEId: $('#itemFSE').val(),
        PunchlistNumber: $('#itemNumber').val(),
        Open: $('#itemOpenDate').val(),
        Type: $('#itemType').val(),
        ResponsibleId: $('#itemResponsible').val(),
        LongDescription: $('#itemLongDesc').val(),
        ItemImage: { Description: "", Url: myURL + "PunchlistTracking/Lists/PicturesList/" + $('#itemNumber').val() + "_image.png" }
    }),
    headers: {
        Accept: "application/json;odata=verbose",
        "Content-Type": "application/json;odata=verbose",
        "X-RequestDigest": myFormDigest
    }
});

call.done(function (data, textStatus, jqXHR) {
    alert('Punchlist item ' + $('#itemNumber').val() + " added successfully.");
    init();
});

call.fail(function (jqXHR, textStatus, errorThrown) {
    alert('fail');
    var response = JSON.parse(jqXHR.responseText);
    var message = response ? response.error.message.value : textStatus;
    console.log(message);
});
}

Upload file:
function uploadFile(FormDigest, FileInput, fileName) {

var serverRelativeUrlToFolder = 'Lists/Pictures';
var fileInput = jQuery(FileInput);

var serverUrl = myURL + "PunchlistTracking";

var getFile = getFileBuffer();

getFile.done(function (arrayBuffer) {

    var addFile = addFileToFolder(arrayBuffer);
    addFile.fail(onError);
});

getFile.fail(onError);

function getFileBuffer() {
    var deferred = jQuery.Deferred();
    var reader = new FileReader();
    reader.onloadend = function (e) {
        deferred.resolve(e.target.result);
    }
    reader.onerror = function (e) {
        deferred.reject(e.target.error);
    }
    reader.readAsArrayBuffer(fileInput[0].files[0]);
    return deferred.promise();
}   //  getFileBuffer

function addFileToFolder(arrayBuffer) {

    var fileCollectionEndpoint = String.format(
            "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
            "/add(overwrite=true, url='{2}')",
            serverUrl, serverRelativeUrlToFolder, fileName);

    return jQuery.ajax({
        url: fileCollectionEndpoint,
        type: "POST",
        data: arrayBuffer,
        processData: false,
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": FormDigest,
            "content-length": arrayBuffer.byteLength
        }
    });
}   //  addFileToFolder

function onError(error) {
    alert(error.responseText);
}   //  onError

}   //  uploadFile

A: The best way to do this is with Promises, like you are already doing.  Get your uploadFile function to return a promise, and in the "then" or "done" of that promise, then make the second call.  Exactly as you are doing with the getFileBuffer call and the addFileToFolder call


text:
Q: Virtual meeting vs teleconference How did the word "virtual" come to mean "Operating by computer or in cyberspace; not physically present"?
Virtual, to me, means "not real", but when we're working form home, having "virtual meetings" or when we have a video call with our doctor for a "virtual check-up", it's still a meeting, it's still a check-up. What would make it virtual?
I think it would be more accurately termed a "teleconference", "telemedicine", or just "telepresence", much like our old familiar friends, telephone, television, telescope, telegraph, teletype, etc, and common sci-fi and fantasy tropes such as teleportation, telekinesis, and telepathy.
If we were all in VR Chat with our 3D headsets and motion capture suits like in Ready Player One, with simulated AI meeting participants and some fictional agenda, I might feel more comfortable calling it a "virtual meeting" but let's be serious, it's a teleconference, it's telecommunication. It's real, not virtual.

A: I work in SaaS, and the term "Virtualisation" came up yesterday! As in, "we recently virtualised the production and pre-production environments." I looked it up in order to be able to explain to clients, and it turns out virtualisation is technology that allows multiple simulated environments using resources that are traditionally bound to hardware.
To extrapolate that into the human work force, you can see how working virtually means working without a physical presence.
I think you could look at teleconferencing as how you connect to your virtual team, so a teleconference is the form of communication. An important distinction because you're not always working on a call/meeting when you're working remotely.


text:
Q: Conflict between Windows and Android? Please help me solve this file path conflict:
As you know, many HTML pages use relative paths starting with a "/" for the href attribute of link tags. For example: link href="/links/style.css".
In my code, I'm using loadDataWithBaseURL for a WebView to set a relative path name. If I give like this:
String webContent=//whole html page;
mWebView.loadDataWithBaseURL("file:///sdcard/mibook/pg90/",new String(webContent), "text/html", "UTF-8","" );

Result: No effect in WebView because (I felt) it takes two '/' while appending to pathname.
If I edit my HTML page by removing the first "/" from the href tag, then the WebView renders properly.
But my problem is that I don't want to edit HTML content as above. Any solution?

A: Javadoc of loadDataWithBaseURL states:
Note for post 1.0. Due to the change in the WebKit, the access to asset files through
"file:///android_asset/" for the sub resources is more restricted. If you provide null
or empty string as baseUrl, you won't be able to access asset files. If the baseUrl is
anything other than http(s)/ftp(s)/about/javascript as scheme, you can access asset
files for sub resources

So basically only allowed URL for file:/// scheme is file:///android_asset/ where files are in your asset folder.


text:
Q: ADF testing and ARDL model cointegration i am studying the impact of trade openness on manufacturing growth from 1967 to 2013 in Tunisia. My variables are Manufacturing value added(MVA), openness(OPEN), GFCF and manufacturing labor force (MLAB)
1/ MVA (lag1) and MLAB (lag4) are I (0) no constant , no trend
MVA, OPEN and GFCF are stationary at first difference and satisfy the 3 equations of ADF test, but MLAB at first difference is only stationary when I include constant and trend. can I claim that MLAB is stationary at first difference (I mean is not I (2))?
Can I run ARDL model in this case?
2/I include trend and intercept in my ARDL model but their coefficients are not significant, what should I do?
Can I delete them and estimate again my model? In this case what critical value I should consider for my ARDL model? Unrestricted intercept and unrestricted trend //or no intercept and no trend because their coefficient are not significant. What is best software I can use?

A: 1/ MLAB is stationnary at first difference, so according to sattionnarity'order of the others variables, you can model ARDL.
2/ There are 5 cases of ARDL'specification. To compute and take a decision on the existence of a long run relationship, you have to compare the F-stat to the critical values established by Pesarn, Shin and Smith.
Check here http://onlinelibrary.wiley.com/doi/10.1002/jae.616/pdf


text:
Q: UICollectionView rotation animation I have two different UIViewControllers, and both of them have UiCollectionView.
Problems appears when I try rotate iPad.
Next I have in portrait position

When I rotate to landscape I reload my collectionView, so in lanscape mode I need have 3 columns
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [self.collectionView reloadData];
}

In first viewController all good, and when collectionView begin rotate controller still have 3 columns

But when I try do it in another controller, I get bad situation

It is looks like in one moment two collectionView in my view, and then one of them is disappearing.
I use standart UICollectionViewFlowLayout and have same methods for buils layout

A: Have you tried invoking the view..

*

*(void)invalidateLayout

You can call this method at any time to update the layout information. This method invalidates the layout of the collection view itself and returns right away. Thus, you can call this method multiple times from the same block of code without triggering multiple layout updates. The actual layout update occurs during the next view layout update cycle.

A: I think I have solution, try this which understands when animating the rotation;

*

*(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(    NSTimeInterval)duration {
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
[self.collectionView reloadData];
}

A: Have you also tried this?

*

*(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
[self.collectionView reloadData];
}


text:
Q: Traceback not shown when using runpy in Python 3.4 Running a Python module via runpy will sometimes not show any traceback.
For example, if the module raises an AttributeError, then the result would be this;
$ echo 'import random; random.dsgjdgj' > hello/__init__.py
$ python -m hello
/bin/python: Error while finding spec for 'hello.__main__'
(<class 'AttributeError'>: 'module' object has no attribute 'dsgjdgj');
'hello' is a package and cannot be directly executed

However if you cause an NameError, the traceback will show correctly;
$ echo 'lalalalal' > hello/__init__.py
$ python -m hello
Traceback (most recent call last):
  File "/usr/lib/python3.4/runpy.py", line 151, in _run_module_as_main
    mod_name, mod_spec, code = _get_module_details(mod_name)
  File "/usr/lib/python3.4/runpy.py", line 118, in _get_module_details
    return _get_module_details(pkg_main_name)
  File "/usr/lib/python3.4/runpy.py", line 104, in _get_module_details
    spec = importlib.util.find_spec(mod_name)
  File "/usr/lib/python3.4/importlib/util.py", line 86, in find_spec
    parent = __import__(parent_name, fromlist=['__path__'])
  File "/vagrant/server/hello/__init__.py", line 1, in <module>
    lalalalal
NameError: name 'lalalalal' is not defined

I'd like to show a full traceback, regardless of what the error is. I've tried several CLI options, including -v -d with no impact.
It seems to be related to this cpython/Lib/runpy.py:
try:
    spec = importlib.util.find_spec(mod_name)
except (ImportError, AttributeError, TypeError, ValueError) as ex:
    # This hack fixes an impedance mismatch between pkgutil and
    # importlib, where the latter raises other errors for cases where
    # pkgutil previously raised ImportError
    msg = "Error while finding spec for {!r} ({}: {})"
    raise ImportError(msg.format(mod_name, type(ex), ex)) from ex

From what I can tell, from ex should ensure that the original traceback is kept in tact and printed via stdout at some stage.
It would appear the source of the problem is;
except ImportError as exc:
    # Try to provide a good error message
    # for directories, zip files and the -m switch
    if alter_argv:
        # For -m switch, just display the exception
        info = str(exc)

Any ideas?

A: This is a potential bug within Python, and has been raised here.


text:
Q: why the event of asp:button does not fire although all inputs are valid? I have an aspx page with some asp:textBox.
every TextBox has some validator controls.
I use bootstrap glyphicons for notifying the user about the validation of the input.
for example:
aspx:

your id

        <asp:TextBox ID="txtId" CssClass="form-control" runat="server" MaxLength="9" TabIndex="4" EnableViewState="false" ValidationGroup="idValidation" onchange="validateWithFeedback('idValidation','txtId');" CausesValidation="true"></asp:TextBox>

    <asp:RequiredFieldValidator ID="RequiredFieldValidatorId" CssClass="validation" Visible="false" ControlToValidate="txtId" ValidationGroup="idValidation" runat="server" ErrorMessage="*" Display="Dynamic"></asp:RequiredFieldValidator>
    <asp:RegularExpressionValidator ID="RegularExpressionValidator3" CssClass="validation" ControlToValidate="txtId" ValidationGroup="idValidation" runat="server" ValidateEmptyText="true" ErrorMessage="*" ValidationExpression="\d{1,9}" Display="Dynamic"></asp:RegularExpressionValidator>
    <asp:CustomValidator ID="CustomValidator3" runat="server" CssClass="validation" ErrorMessage="*" ControlToValidate="txtId" ValidationGroup="idValidation" ValidateEmptyText="true" ClientValidationFunction="ValidateID" Display="Dynamic"></asp:CustomValidator>

javascript:
function validateWithFeedback(group,id) {
    if (Page_ClientValidate(group)) {
        $("#" + id).parent('div').removeClass('has-error');
        $("#" + id).parent('div').addClass('has-success');
        $("#" + id).parent('div').children('span').removeClass('glyphicon-remove');
        $("#" + id).parent('div').children('span').addClass('glyphicon-ok');
    }
    else {
        $("#" + id).parent('div').addClass('has-error');
        $("#" + id).parent('div').removeClass('has-success');
        $("#" + id).parent('div').children('span').addClass('glyphicon-remove');
        $("#" + id).parent('div').children('span').removeClass('glyphicon-ok');
        Page_IsValid = false;
    }
    var required = false;
    var validators = $(Page_Validators);
    if ($("#" + id).val() == "" && $("#" + id).text() == "") {
       // debugger;
        for (var i = 0; i < validators.length; i++) {
            if (Page_Validators[i].controltovalidate==id && $(Page_Validators[i]).attr('data-val-evaluationfunction') == "CustomValidatorEvaluateIsValid")
                required = true;
        }
        if (!required) {
            $("#" + id).parent('div').removeClass('has-error');
            $("#" + id).parent('div').removeClass('has-success');
            $("#" + id).parent('div').children('span').removeClass('glyphicon-remove');
            $("#" + id).parent('div').children('span').removeClass('glyphicon-ok');
        }
    }
}

submit button:
<asp:Button runat="server" ID="btnSubmit" CssClass="btn-sm btn-info" Text='submit' TabIndex="19" CausesValidation="true" OnClientClick="return Validate();" OnClick="btnSubmit_Click" UseSubmitBehavior="false"></asp:Button>

javascript:
function validateWithFeedback(group,id) {
    if (Page_ClientValidate(group)) {
        $("#" + id).parent('div').removeClass('has-error');
        $("#" + id).parent('div').addClass('has-success');
        $("#" + id).parent('div').children('span').removeClass('glyphicon-remove');
        $("#" + id).parent('div').children('span').addClass('glyphicon-ok');
    }
    else {
        $("#" + id).parent('div').addClass('has-error');
        $("#" + id).parent('div').removeClass('has-success');
        $("#" + id).parent('div').children('span').addClass('glyphicon-remove');
        $("#" + id).parent('div').children('span').removeClass('glyphicon-ok');
        Page_IsValid = false;
    }
    var required = false;
    var validators = $(Page_Validators);
    if ($("#" + id).val() == "" && $("#" + id).text() == "") {
       // debugger;
        for (var i = 0; i < validators.length; i++) {
            if (Page_Validators[i].controltovalidate==id && $(Page_Validators[i]).attr('data-val-evaluationfunction') == "CustomValidatorEvaluateIsValid")
                required = true;
        }
        if (!required) {
            $("#" + id).parent('div').removeClass('has-error');
            $("#" + id).parent('div').removeClass('has-success');
            $("#" + id).parent('div').children('span').removeClass('glyphicon-remove');
            $("#" + id).parent('div').children('span').removeClass('glyphicon-ok');
        }
    }
}

javascript:
function Validate() {

    validateWithFeedback('idValidation', 'txtId');

    var isValid = true;

    isValid = isValid && Page_ClientValidate('idValidation');

    return isValid;
}

everything is perfect, except of fact that when I click on btnSubmit the event in server side doesn't fire although all inputs are valid.
what can be the problem?


text:
Q: Summing/Counting equal values/rows of a data frame I have a dataframe that contains a bunch of individual trip data, with a start and end station ID for each trip.
I'm trying to make a second dataframe that is all the info rearranged for each station. So for example, if there are 50 trips with start_station_id == 12 in the first dataframe, then the second dataframe under station_id 12 would have its "starts" column equal to 50
Currently I figured a for loop would be the best method for this, but I cant seem to crack it
for(i in range(station_ids)){
   stationData$starts[i] <- sum(data$start_station_id[i] == station_ids[i])
}

This produces the following error:
Error in `$<-.data.frame`(`*tmp*`, starts, value = c(0, 0, 0, 0, 0, 0,  :
  replacement has 370 rows, data has 369

station_id's is a variable that contains each unique station id #, stationData$starts is where I want the number of starts stored. Data is the original data I am trying to run the for loop over.
Is there an easier way to complete this operation or am I just writing the for loop wrong? Any tips would be super helpful

A: From what I have understood from your question you're trying to count the occurences of each station_id this can be easily achieved by the table function which returns a table object ie a named vector containing the count and station_id as the names.
base R
table(data$start_station_id)
data.frame(table(data$start_station_id)) #if you prefer the data.frame look

If you want to have the number of occurence merged into your old data.frame can inner join the two data.frames using the merge function
tbl.df <-data.frame(table(data$start_station_id))
colnames(tbl.df)[1] <- "start_station_id"
data <- merge(data, tbl.df)

data.table
data.table::setDT(data)
data[, `Number of rows` := .N, by = start_station_id]

the := is a data.table function that creates new columns, the .N give the count of the rows for the current group, the by specifies by which column to group. this automatically adds the column Number of rows to the data.table.
for an introduction on the data.table package check the vignette.
this implementation is the fastest.

A: The approach is feasible but you should not use a data.frame to put your fresh data in as you don't know the row counts, yet. Just use a list and convert it to data.frame in the end:
stationData = list("station" = unique(c(data$start_station_id, data$end_station_id)), ##  Create a list of all stations
                   "starts" = c(),

for(i in i:length(stationData$station)){
   s = stationData$station[i]
   stationData$starts[i] <- sum(data$start_station_id == s)
}
stationData = as.data.frame(stationData)

At the end of the for-loop the length of both columns will be identical and there will be no problem to create this data.
A much easier way, though, would be to use the table() function, which computes the number of starting stations automatically and was already proposed by Abdessabour Mtk.


text:
Q: The joined is located outside of the base path component Good Morning Everyone,
I developed an app in Django (latest version). On local server it is working well. But for deployment when I run command for collect static then the error occurred
The joined path (C:\Users\Galaxy\PycharmProjects\plugins\js_composer\assets\images\icons\address-book.png) is located
 outside of the base path component (C:\Users\Galaxy\PycharmProjects\medical_store\staticfiles).

I'm using HTML and Bootstrap for front-end but this path error occurred.
It's my terminal showing
  return safe_join(self.location, name)
  File "C:\Users\Galaxy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\_os.py", line 29, in safe_join
    raise SuspiciousFileOperation(
django.core.exceptions.SuspiciousFileOperation: The joined path (C:\Users\Galaxy\PycharmProjects\plugins\js_composer\assets\images\icons\address-book.png) is located
 outside of the base path component (C:\Users\Galaxy\PycharmProjects\medical_store\staticfiles)

I tried to replace the url that was first looking as
{background-image:url(../../../plugins/js_composer/assets/images/icons/address-book.png)}

then I replace it by
{background-image:url(../../../medical_store/static/img/address-book.png)}

But same error found.
I don't know how to remove this error. Have you any idea what I have to do exactly?
Here is my settings for staticfiles.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'


text:
Q: Chess engine with FPGA I am brainstorming about creating a chess engine with an FPGA. What would be your dos and don'ts?
First of all you can separate engine easily to two parts, move generator and board evaluator, what will be benefits of doing these two in FPGA or one in cpu and one in fpga.
I am assuming programming an FPGA requires more hardwork since it is not so obvious to optimize and you can always find better and faster approaches as long as you take your time. (This may occur to me so because I am newbie in FPGA programming)
Another thing is cost, how much would an FPGA cost which can win against a 1000$ CPU? I know this is nearly impossible to answer but I wonder if 500$ is a good estimate?
Do you think this FPGA approach will yield better results or should I put my work into standart cpu chess engines. I am not sure how much space there is for evolution and new approaches in standart engines.

A: I suggest you have a look at the hydra project, as they have done a chess cluster that uses processors and FPGAs as coprocessors. My first impression of your idea was, however, the same as Bo's: my guess is that a chess computer will be heavily based on DB lookups and giant tree lookups, both of which require an extreme memory bandwith. So if you are not going for something like the nallatech accellerators (and they are really expensive ~20k$), or you have a completely new approach, don't do it ;-)

A: The biggest "don't" with FPGAs:
Don't use one unless you can demonstrate that it is necessary, for reasons of

*

*cost

*size

*power

*performance

In particular don't fall into the trap of assuming that using an FPGA will necessarily produce  the highest-performance system.
Work out your problem solution (at least on paper) first.  Figure out your goals in terms of the above parameters.  Only then find a suitable implementation solution which meets the goals.