text:
Q: Technologies for making a web service that interacts with a REST API? My Google-foo is failing me here... most likely a terminology thing.
Basically, I'm making a desktop (and likely mobile) application that connects to a REST API that returns JSON. I've created a C# class library that handles the the data querying in my local project however this would expose my API key if I were to publish it.
I would like to know what are the appropriate options for simply running a small service in Azure that takes a web request, queries the API and passes the JSON response back. Something lightweight, decently scalable.
Is this something a web role or worker role is good for? Is this something I really should learn Node.js for?

A: I asked a similar question a few years back: Keeping a secret key secret with Amazon Web Services
One reasonable solution is to build a simple service that returns the headers and url to use when communicating with the authenticated service. Your API key remains secret because it only lives in your service, but the clients can leverage the API key by getting the encrypted request from your service and then making the request for the actual work.
I haven't personally looked into the Azure API App Service, but a brief browse of the main website suggests that it, too, may be relevant to your interests. :)

A: Check out Azure Mobile Apps.  Azure Mobile Apps is a "backend as a service" platform.  With Mobile Apps you can easily store information into a SQL Database and expose custom API methods.  It is a great place to start and has SDKs for connecting iOS, Andriod, Xamarin, and HTML apps.
As for security, the Mobile service has options to protect the data from allow anonymous access to requiring each user to authenticate.


text:
Q: Parallelizing google cloudbuild steps without mangling the build logs Following guidance here: https://cloud.google.com/cloud-build/docs/configuring-builds/configure-build-step-order
We have split up our build into a multilayer docker image where layers are

*

*Install OS and third party deps

*Install our sources and build (in debug or release depending on docker ARG)

*Run ci / code coverage

We have tagged the steps in cloudbuild.yaml with docker id's and are using waitfor to try to make it so that the debug and release versions can run in parallel.
However, when we do this, the build log is mixed up -- the build logs for release and debug are are jumbled together making it much harder to read. e.g.
Step #2 - "build-debug": �[0m�[91m  Downloaded colored v1.7.0
Step #5 - "build-release": �[0m�[91merror: couldn't read /tmp/mobilenode/src/attest/src/ias/../data/AttestationReportSigningCACert.pem: No such file or directory (os error 2)
Step #5 - "build-release":   --> /tmp/mobilenode/src/attest/src/ias/verify.rs:35:7
Step #5 - "build-release":    |
Step #5 - "build-release": 35 |     &[include_str!("../data/AttestationReportSigningCACert.pem")];
Step #5 - "build-release":    |       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Step #5 - "build-release":
Step #2 - "build-debug": �[0m�[91m  Downloaded toml v0.4.10

[0m�[91m  Downloaded safemem v0.3.0
Step #2 - "build-debug": �[0m�[91m  Downloaded crunchy v0.1.6
Step #2 - "build-debug": �[0m�[91m  Downloaded grpcio-sys v0.4.4
Step #5 - "build-release": �[0m�[91merror: aborting due to previous error
Step #5 - "build-release":
Step #5 - "build-release": �[0m�[91merror: Could not compile `attest`.
Step #5 - "build-release": warning: build failed, waiting for other jobs to finish...
Step #5 - "build-release": �[0m�[91merror: build failed
Step #5 - "build-release": �[0m�[91mmake: *** [src/enclave/target/release/libenclave.so] Error 101
Step #5 - "build-release": �[0mMakefile:90: recipe for target 'src/enclave/target/release/libenclave.so' failed
Step #2 - "build-debug": �[0m�[91m  Downloaded term v0.5.1
Step #2 - "build-debug": �[0m�[91m  Downloaded tiny_http v0.6.2
Step #2 - "build-debug": �[0m�[91m  Downloaded regex v0.1.80

Is there a way to configure cloudbuild so that there is a separate log file for each build step? Is the best answer to use a different cloudbuild.yaml for the parallel steps, and skip all this wait_for stuff?

A: I was having this same issue, but then I discovered that viewing a build via the History under Cloud Build in the Console will let you view each step individually, or view the entire job, like you're currently seeing (click Build Summary, the top entry in the sidebar).
Click on the name of the step in sidebar, each step should be comprised of a number followed by a colon and then the name of the step. The number appears to be based upon the order in which the job appears in your cloudbuild.yaml
What you're seeing is a result of the parallelization of your build, as each step that is marked as being able to run concurrently is at a different step in its execution.

You can read more about viewing the Build History using the console here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: bootstrap website slider to work movie in background i am looking for some kind of slider for my website like skype.com or other websites which shows movies effect.
any one knows how to make banners like that in responsive website?
Thanks

A: That's all fine and dandy, but the video is disabled on skype.com for mobile devices and only an image is shown. Whereas for bigger screens it shows the video tag which plays in the background.
Why not inspect the website with developer tools and see how they have done it. Seems simple to me, it's all about the structure of the elements and the classes applied.


text:
Q: Python/Pandas: Sort dataframe columns based on a column name I have a dataframe containing several columns labelled x1, x2, x3, and x4.
Depending on the analysis, I would need to assign one of the four columns to be the first column when ordering the four columns in the dataframe from left-to-right.
For instance, if I want column 'x2' to be the first I assign it to 'sorter'.
sorter = x2

Now my question: how I sort the dataframes in the column so that the column assigned to 'sorter' is located in the first column?
EDIT: The order of the rest of the columns should remain unchanged.

A: You can change order of columns like:
data = {'X1':  ['11', '12'],
        'X2': ['21', '22'],
        'X3': ['31', '32']
        }

df = pd.DataFrame(data)
df
    X1  X2  X3
0   11  21  31
1   12  22  32

df = df.reindex(['X3','X1','X2'], axis=1)
df

    X3  X1  X2
0   31  11  21
1   32  12  22

Note : You need to provide desired order.
You can create a function to change order by given column:
def sorter(desired, df):
    columns = df.columns.tolist()
    columns.remove(desired)
    columns.insert(0,desired)
    return df.reindex(columns, axis=1)

sorter('X2',df)

    X2  X1  X3
0   21  11  31
1   22  12  32


text:
Q: How do I delete certain html on media queries?(on iphone it won't be there) I know how to edit css on media queries, but how do I make it so that when the screen is less than 500px, certain html tags aren't even there? Thanks

A: You can't. They will always be part of the DOM (at least until you start adding JavaScript into the mix).
The closest you can come would be to write a style that sets them to display: none so they won't be rendered.

A: Below 500px screen size, you can hide the html tags you want.
@media screen and (max-width: 500px) {
    p {
        display:none;
    }
}


text:
Q: Buck-boost INPUT voltage regulation stability (MPPT) I am designing buck-boost converter with Maximum Power Point Tracker. The idea is to build feedback loop that regulates input voltage by changing output current. Output will be connected to Li-Ion battery. Constant voltage output and MCU driven MPPT algorithm will be implemented in the future, the main objective now is to build constant INPUT voltage converter.
I am doing simulations in LTspice but all designs that I try are unstable. I attach one of the designs which after some fluctuations starts to regulate input voltage but there are only few degrees of phase margin.
Could someone suggest the right feedback loop design that would be more stable than that? Would it be enough just to add Type III compensation network instead of Type I or maybe there is completely smarter way to do the feedback loop?
In the end, after designing stable input voltage regulation loop, the idea is to multiply input voltage and current with MCU and with perturb and observe method find the MPP. MCU will regulate input voltage by changing resistance in digital potentiometer which will be connected instead of bottom resistor in voltage divider of the feedback loop.

A: This is a slightly unusual use of this device according to the data sheet but, I can see it operating with a little more care in component selection. See figure 9 in the data sheet for the loop compensation network applied across what is R3 in your diagram. I suggest that you do use the type II compensation scheme because of the addition of the op-amp in the feedback path.
I would also suggest that you use the run pin so that the initial starting transient is also avoided. You could use a capacitor on this pin to create a soft starting circuit.

A: What for do you need the analog feedback loop?
As far as I understand from your question, you plan to use MCU to control the device anyway. It is much more feasible to implement the whole control in MCU rather than to combine analog and digital controls.
I would suggest the following design:

*

*generate control sequence for your converter either by MCU or by some simple logic, if MCU is not fast enough;

*your power stage (switches and inductor) form "DC-DC transformer" with voltage ratio defined by the duty factor of control signal;

*this design is inherently stable as it does not need feedback loop;

*then you vary the duty factor to find maximum power point.


text:
Q: Combinatorics exercises So this is the question :
"Frogs and storks are grazing on the edge of a pond. The following happens every minute.
In the first half of the minute every frog that was there at the beginning of this minute attracts
three new frogs and one new stork. In the second half of the minute every stork eats one frog.
At the beginning there were two frogs and one stork on the edge of a pond. How many frogs
and storks are there after twenty minutes?"
I have the "formulas" for both parts of the minute:
First 30s : F = 4*F and S = F + S
Second 30s : F = F - S and S = S
I just can't seem to generelize this. Also when I did the calculation for every 30s The number of frogs that I start the previous minute is the same with the one of storks the current minute.
Thanks in prior.

A: You should define $F(n)$ as the number of frogs at the start of the $n^{th}$ minute and $S(n)$ as the number of storks at the start of the $n^{th}$ minute.  We are given $F(0)=2,S(0)=1$.  Now write a recurrence for $F(n+1)$ in terms of $F(n),S(n)$ and similarly for $S(n+1)$.  You have $S(n+1)=S(n)+F(n)$. What is $F(n+1)?$

A: $$F_{k+\frac12}=4F_k, S_{k+\frac12}=F_k+S_k$$
$$F_{k+1}=F_{k+\frac12}-S_{k+\frac12}, S_{k+1}=S_{k+\frac12}$$
Hence,
\begin{align}
F_{k+1} &=4F_k - (F_k+S_k) \\
&= 3F_k - S_k\\
S_{k+1}&=F_k + S_k
\end{align}
Hence it is just a linear recurerrence problem.
$$\begin{bmatrix} F_{k+1} \\ S_{k+1} \end{bmatrix} = \begin{bmatrix} 3 & -1\\ 1 & 1 \end{bmatrix}\begin{bmatrix} F_{k} \\ S_{k} \end{bmatrix}$$


text:
Q: Error: TodoList has not been deployed to detected network (network/artifact mismatch) truffle(development)> TodoList = await TodoList.deployed()
Uncaught:
Error: TodoList has not been deployed to detected network (network/artifact mismatch)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-contract/lib/contract/constructorMethods.js:113:1

A: Please follow the steps:

*

*Create another file named 2_anyname.js(make sure it doesn't
start with 1 and you can name it anything) in migration folder.

*Paste this content in file
var contract_name = artifacts.require('contract_name');

module.exports = function (deployer) {
deployer.deploy(contract_name); };

*run commands in this order : truffle compile ->
truffle migrate --reset or truffle deploy --reset -> truffle console

*you are good to go !!


text:
Q: How to generate a random quaternion quickly? I searched around and it turns out the answer to this is surprising hard to find. Theres algorithm out there that can generate a random orientation in quaternion form but they involve sqrt and trig functions. I dont really need a uniformly distributed orientation. I just need to generate (many) quaternions such that their randomness in orientation is "good enough." I cant specify what is "good enough" except that I need to be able to do the generation quickly.

A: From Choosing a Point from the Surface of a Sphere by George Marsaglia:

*

*Generate independent x, y uniformly in (-1..1) until z = x²+y² < 1.

*Generate independent u, v uniformly in (-1..1) until w = u²+v² < 1.

*Compute s = √((1-z) / w).

*Return the quaternion (x, y, su, sv). It's already normalized.

This will generate a uniform random rotation because 4D spheres, unit quaternions and 3D rotations have equivalent measures.
The algorithm uses one square root, one division, and 16/π ≈ 5.09 random numbers on average. C++ code:
Quaternion random_quaternion() {
  double x,y,z, u,v,w, s;
  do { x = random(-1,1); y = random(-1,1); z = x*x + y*y; } while (z > 1);
  do { u = random(-1,1); v = random(-1,1); w = u*u + v*v; } while (w > 1);
  s = sqrt((1-z) / w);
  return Quaternion(x, y, s*u, s*v);
}

A: Quoted from http://planning.cs.uiuc.edu/node198.html:

Choose three points u, v, w ∈ [0,1] uniformly at random. A uniform, random quaternion is given by the simple expression:
 h = ( sqrt(1-u) sin(2πv), sqrt(1-u) cos(2πv), sqrt(u) sin(2πw), sqrt(u) cos(2πw))

A: Simplest way to generate it, just generate 4 random float and normalize it if required. If you want to produce rotation matrices later , than normalization can be skipped and convertion procedure should note nonunit quaternions.


text:
Q: simple C code to either read a file or stdin Absolutely new to C. I am trying to write a program to either read integers contained in a file (passed as arg) or from stdin. First number read is supposed to indicate the array size.
I have something but it throws segmentation fault. Please help.
#include<stdio.h>
#include<stdlib.h>

int main(int argc, char* argv[]) {

    FILE *f;
    int n, numbers[n], firstNum;

    if (argc != 0)
    {

        f = fopen(argv[1], "r");

        fscanf(f, "%d", & firstNum);

        int numbersArray[firstNum];

        for (int i = 0; i < firstNum; i++)
        {
            fscanf(f, "%d", &numbersArray[i]);
        }

        for (int i = firstNum; 0 <= i; i--)
        {
            printf("Numbers: %d\n\n", numbersArray[i]);
        }
        fclose(f);
    }
    else
        scanf("%d", &n);

    for (int i = 0; i < n; i++)
    {
        fscanf(stdin, "%d", &numbers[i]);
        printf("%d\n", i, numbers[i]);
    }

    return 0;
}

A: First off always initialize your variables like kaylum and myself mentioned in the comments.
Unlike some other programming languages C doesn't initialize your variables for you.
Now for the question you posted, you got the idea mostly correct but there are things that i suggest you change:
int n, numbers[n], firstNum;

to
int n = 0, numbers[1000], firstNum = 0;

If you're not happy with that you could move the numbers[n] lower when n is initialized but i wouldn't advise that.
Instead of that, since you're learning C have a look at dynamically allocated arrays using pointers.
Some links to help you understand pointers:
https://www.cprogramming.com/tutorial/c/lesson6.html
https://www.tutorialspoint.com/cprogramming/c_pointers.htm
Next have a look at your fopen  it has a return value that tells you if it succeeded to open the file you requested.
So you can add:
    f = fopen(argv[1], "r");

    if (f == NULL)
    {
        printf("File Not Found!");
        return -1;
    }

Modify the condition to suite the way you want to handle that error.
When you're reading the file the user specifies the size of the array you're reading but you should consider the fact that the file may not contain the exact amount of elements.
The function that you are using fscanf has a way to tell you that and that's it's return value.
It will return EOF which is a special value that translates to End Of File.
Consider modifying your fscanf to this:
    if (fscanf(f, "%d", &firstNum) == EOF)
    {
        printf("ERROR");
    }

Or if you're in a for loop put break
The last thing is that you don't have to explicitly use fscanf for stdin, the user has specified that he will input it through stdin so you can just as well use scanf.
Hope this helps and good luck with your future C endeavors.


text:
Q: Website flickers on scroll - iOS mobile. How do I fix this? My website flickers out of control when scrolling on iOS mobile. Have't run into any issues on Android at all.
https://s3-us-west-1.amazonaws.com/stage.coefficientlabs.com/index.html
I've read through some similar forums discussing
-webkit-overflow-scrolling: touch;
-webkit-transform:translate3d(0,0,0);
-webkit-backface-visibility: hidden;

But none of my attempts seem to have worked. I think part of it is because I can't tell which specific element is causing the flicker. It just appears to me like the entire website is flickering.
I've used
-webkit-overflow-scrolling: touch;

in the past before, but now when I inspect the code, it says it has an invalid property value. Some others are experiencing the same thing; I think the feature got discontinued or something.
I just want simple, normal mobile scrolling that we're all used to expecting.
Thanks so much in advance!
EDIT
I've found out that once I click the "Click to get started" button, and close the popup, the flicker stops. This doesnt happen with any other buttons, just this one. I've been working on integrating this popup with the rest of the website, so it looks like this is the culprit.
Still dont have any strong leads to pursue...not sure why opening and closing this popup causes the website to respond properly.
EDIT 2
Okay so I removed one CSS sheet and now the scroll works. Trying to isolate what in this CSS file is causing this scrolling issue. Here is the link. Any idea whats going on here?

A: Okay turns out that the popup wrapper's css property "display: none" was interfering with some of the other css properties(?). I changed this to "display:block" and just coded another way to hide the popup wrapper with z-index. No more flicker!


text:
Q: Insert TornadoFx in Kotlin project I'm having some trouble on putting tornadoFx in my project. I'm using the last version of IntellIj, Kotlin and I'm also downloading tornadoFx from here:
TornadoFxGitLink
I added the pom file to Maven and I already tried to change a few things that Readme of tornado recommended to me like use 1.1 kotlin version or updating IDE.
The thing is that when I create a TornadoFx file in the project and I try to build, these error appears:
import tornado.fx is apparently an unresolved reference

Can someone explain why is this happening or why these errors normally appear?
Thanks in advance, I'm open to all questions due to my bad english.

A: That import is not needed or at all pointing to anything TornadoFX related. The only import you need for the most part is import tornadofx.*.
Install the TornadoFX IDEA plugin, and it will add the import for you. You should also start be reading the guide.
You should not be downloading TornadoFX manually, use Maven or Gradle to import the dependencies.
I recommend trying out TornadoFX in a simple standalone project first, for example by creating a template project using the TornadoFX IDEA Plugin. After you understand the basics you can revisit integrating it into an existing application.


text:
Q: Can I namespace the ostream << operator? As has been answered before, namespacing operator overloads is considered good practice, so that's what I want to do.
Problem: It only compiles if I don't. Am I just doing it wrong, or have I found an exception where it is not possible?
Here is a single translation unit for easy repro:
// lib/halfseconds.h:
#include <chrono>

namespace lib {
    using halfseconds = std::chrono::duration<intmax_t, std::ratio<1, 2> >;
}

// lib/debug.h:
#include <ostream>

namespace lib {
    std::ostream& operator<<(std::ostream& o, lib::halfseconds halves)
    {
        double seconds = halves.count();
        seconds /= lib::halfseconds::period::den;
        o << seconds << 's';
        return o;
    }
}

// demo/main.cpp:
#include <iostream>

int main()
{
    lib::halfseconds threeHalvseconds(3);
    std::cout << threeHalvseconds << '\n'; // 1.5s
}

What does the compiler say? G++ version 8.2.1 says «no match for operator<<» and spews one daunting list (208 lines) of candidates. I suppose none of those are relevant, as I wouldn't get this error if the relevant one wasn't missing.

A: The problem here is that once you have put operator<< in a namespace, you should explicitly tell the compiler you would like to use the namespace, otherwise it's hidden.
Either:

*

*using lib::operator<< inside the main

*lib::operator<<(std::cout, threeHalvseconds) << '\n';

A: The principle you're trying to use is called Argument Dependent Lookup. If I have a function and a type declared in the same namespace, I can use them together outside of the namespace without having to specify which namespace the function is from:
//In MyClass.h
namespace foo {
    class MyClass { /* stuff */ };
}
//In doStuff.h
namespace foo {
    void doStuff(MyClass c) { /* stuff */ }
}

//in main.cc
int main() {
    foo::MyClass tom; //I'm bad with names
    doStuff(tom); //Here, we don't have to specify the namespace
}

This is almost what's happening in your example. The difference is that halfseconds isn't actually declared in namespace lib. Because halfseconds is an alias, it's actually declared in std::chrono, and when you put the operator<< overload in namespace lib, the compiler doesn't check for it.
How to fix this
The simplest way to fix this is to declare a new type in namespace lib:
// lib/halfseconds.h:
#include <chrono>

namespace lib {
    class halfseconds
        : public std::chrono::duration<intmax_t, std::ratio<1, 2>>
    {
       public:
        using Base = std::chrono::duration<intmax_t, std::ratio<1, 2>>;
        using Base::Base; //Use the constructor
    };
}

// lib/debug.h:
#include <ostream>

namespace lib {
    std::ostream& operator<<(std::ostream& o, lib::halfseconds halves)
    {
        double seconds = halves.count();
        seconds /= lib::halfseconds::period::den;
        o << seconds << 's';
        return o;
    }
}

// demo/main.cpp:
#include <iostream>

int main()
{
    lib::halfseconds threeHalvseconds(3);
    std::cout << threeHalvseconds << '\n'; // 1.5s
}

You can use it anywhere you'd use std::chrono::duration, it has all the same functionality, and because it's defined in the lib namespace it can be used with any other functions in the lib namespace without having to prefix lib!


text:
Q: How to Display Skip Button to close the MPmoviePlayerViewController at 10 Secs of playing Video In my app Im playing an video using MPmoviePlayerViewController.
actually some videos are too long to watch around 3-5 mins.
I want to allow user to SKIP the video after 10 seconds if he wants.
My requirement is
I need to display the count down 10, 9, 8 -- 0 after 10th secod of the the video we display a skip button.
_moviePlayerViewController = [[MPMoviePlayerViewController alloc] init ];
    [_moviePlayerViewController.view setFrame:self.view.frame];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackDidFinish:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:_moviePlayerViewController.moviePlayer];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(MPMoviePlayerPlaybackStateDidChange:)
                                                 name:MPMoviePlayerPlaybackStateDidChangeNotification
                                               object:nil];

    _moviePlayerViewController.moviePlayer.shouldAutoplay = YES;
    [_moviePlayerViewController.moviePlayer setFullscreen:YES];
    _moviePlayerViewController.moviePlayer.repeatMode = MPMovieRepeatModeNone;
    _moviePlayerViewController.moviePlayer.controlStyle = MPMovieControlStyleNone;
    _moviePlayerViewController.moviePlayer.scalingMode = MPMovieScalingModeNone;
    _moviePlayerViewController.moviePlayer.contentURL =[NSURL fileURLWithPath:videoPath];

in this application we have play back option,
ie if the user quit the application he can resume the video from the point of going background.
in both the case (resume after come foreground, and just now started video)
the user should see a skip button when the video play time is 10 seconds.

Can any one help please

A: What the problem? Use dispatch_after for 5 seconds pause then inside dispatch block run one second timer to count seconds remaining
EDIT
Oh I'm sorry, you need just one NSTimer and seconds counter ivar to track how many seconds passed from the video start

A: For playback option you can use [_moviePlayerViewController.moviePlayer pause]; when going in background and can again resume play from where it was when again come to foreground.
In case if user quit application you can provide playback option also. You can manage a counter variable separately, which count for how seconds the video is playing. Store the value of this counter when user quit application, in short store the value when player stops playing. Now when you again come back to this view you can check the actual length of video and compare with the duration for which it has already played and play back.This can be tricky but the pause thing mentioned above did work.
EDIT: For hiding and displaying skip button after 10sec the counter solution is perfect.


text:
Q: Good jQuery popup dialog plugins Do you know some good jQuery popup dialog plugins? Thanks.

A: I like the one built into jQuery UI built in dialog the best. Very customizable, theme integration, overload confirms and alerts.
http://docs.jquery.com/UI/Dialog.

A: My personal favorite is Colorbox. It's extremely easy to use and looks great! Check out their 5 different pages of examples for a quick how-to.
It also automatically detects the size of the content being loaded so you don't have to specify a width and height.
alt text http://img502.imageshack.us/img502/4859/colorbox.png

A: I am using FaceBox in a project I am working on right now. I like it. Does not require jQueryUI.

A: Fancybox looks awesome and is really versatile. Used it in a couple of projects and my clients are really happy with it.

A: Here's my custom jquery dialog: https://jsfiddle.net/mm7b7t5t/
Still trying to add new features and improve it ^^
var example = new popup([{text: "Close}], "Title", "
Hello World
");
example.open();


text:
Q: videoview for large video VideoView vv = (VideoView)this.findViewById(R.id.screen_video);
Uri uri = Uri.parse(URL);
vv.setVideoURI(uri);
vv.start();

I use above code to play video file.
I play a small video successly.
But when I try to play a large video.
It was Failure.
The file is can be play by my phone.
How to play a large video file with videoview?
Or what limitation of videoview has?
I didn't see any error in logcat.
But it also didn't show the buffering percentage.

A: I don't know (and I could not find) clear specifications for videoview to play a video of a certain size.
But to me it depends on the device and on the codecs used.
For instance my device plays video encoded with MPEG4 (ASP) successfully whatever the size of the video is but if the video is encoded with H264 (MPEG4 AVC) that does not work if the video is larger than the size of the screen.
I hope it helps!


text:
Q: pmset standby is missing I have two Macbook Pros (10.7.2) and both are missing the standby option in pmset:
$ pmset -g
Active Profiles:
Battery Power       -1
AC Power        -1*
Currently in use:
 womp       1
 halfdim    1
 sms        1
 panicrestart   157680000
 gpuswitch  2
 hibernatefile  /var/vm/sleepimage
 networkoversleep   0
 disksleep  10
 sleep      180
 hibernatemode  3
 ttyskeepawake  1
 displaysleep   10
 acwake     0
 lidwake    1

$ pmset -g cap
Capabilities for AC Power:
 displaysleep
 disksleep
 sleep
 womp
 acwake
 lidwake
 halfdim
 sms
 gpuswitch

I've seen this guy has this option:lion pmset standby
Any ideas?

A: From the pmset man page:

STANDBY ARGUMENTS
standby causes kernel power management to automatically hibernate a
  machine after it has slept for a specified time period. This saves power
  while asleep. This setting defaults to ON for supported hardware. The
  setting standby will be visible in pmset -g if the feature is supported
  on this machine.
standby only works if hibernation is turned on to hibernatemode 3 or 25.
standbydelay specifies the delay, in seconds, before writing the hiberna-
  tion image to disk and powering off memory for Standby."

The bold text is my highlight.  This would indicate that the two Macbook Pros you're using do not support the standby arguments.
For a list of machines that support standby mode, see HT4392.
I hope this is helpful.


text:
Q: Create a function and use a loop to calculate the cumulative date and id I have an coding exercise: create a "function", then use "for" to calculate the cumulative by id and date. I can only use cumsum() and for, all packages are not allowed.
For instance, I create a data frame below
df=data.frame("date"=c("1/1/2020","1/1/2020","1/1/2020","2/1/2020","2/1/2020","2/1/2020","3/1/2020","3/1/2020","3/1/2020"), "id"=c("A","B","C","A","B","C","A","B","C"),"val"=c(5,6,7,8,4,5,6,3,4))

A: I voted your question down as SO is not a free coding service. Nevertheless, your problem is simple and there are many ways to resolve this. I had to make some fixes to your DF:
df = data.frame(
  "date" = as.Date(c(
    "1/1/2020",
    "1/1/2020",
    "1/1/2020",
    "2/1/2020",
    "2/1/2020",
    "2/1/2020",
    "3/1/2020",
    "3/1/2020",
    "3/1/2020"
  ), format = "%d/%m/%Y"),
  "id" = c("A", "B", "C", "A", "B", "C", "A", "B", "C"),
  "val" = c(5, 6, 7, 8, 4, 5, 6, 3, 4),
  stringsAsFactors = FALSE
)

Followed by (a dplyr example, just one of many ways):
library(dplyr)
summary_df <- df %>%
  group_by(date, id) %>%
  summarise(sum = cumsum(val))

Resulting in:
> summary_df
# A tibble: 9 x 3
# Groups:   date [3]
  date       id      sum
  <date>     <chr> <dbl>
1 2020-01-01 A         5
2 2020-01-01 B         6
3 2020-01-01 C         7
4 2020-01-02 A         8
5 2020-01-02 B         4
6 2020-01-02 C         5
7 2020-01-03 A         6
8 2020-01-03 B         3
9 2020-01-03 C         4


text:
Q: publishing asp.net mvc using azure Edit:
I am deploying my ASP.NET MVC entity framework using azure, but faced with a problem. I have two projects to publish, one of them is a class library, but seems class library is not published.
Reading this post,
Deploying web site to Azure as well as class library, I found that it is related to the model DLL files. Should the model file be located in the Web Application project's bin folder? or the class library's bin folder? What is potentially causing the issue?

A: Add a reference to you class library from the MVC web application. So when you build .dll of your class library will be copied to /bin folder of the web application.


text:
Q: Root Directory in Debian (Raspberry pi) On Windows 10 I do not have an error while running AdminLTE.
But when I run AdminLTE in Debian an error occurs.

Invalid Configuration - yii\base\InvalidConfigException
The directory is not writable by the web process: /var/www/html/pa2/web/assets

The error is in the picture.
I hope I get a solution of this problem.

A: I've found the answer, we just fix the permission.
chmod -R a+rwX directory/
as root
References


text:
Q: use lodash to find substring from array and to push them to another and then to compare result with the 3rd table I have array:
all [a,b,ac,d, A]

and I want to find in this all elements which include substring "a" ("A") using filter from lodash and push them to another - to the filterTab
   const item = "a"

I try sth like this:
import { some, method, differenceWith, isEquel } from 'lodash';
const filterTab = [];

filterTab.push (some(all, method('match',/item/i)));

But it does not work.
The next step if it works- it will be something like this:
var dif = differenceWith(filterTab, array3, _.isEqual);

And I have no idea why it does not work...

A: If you want to put every value that matches item from all into filterTab and then get the difference between filterTab and array3, use this example:
import { filter, difference, method } from 'lodash';

const all = ['a','b','ac','d', 'A'];

const filterTab = [];
const item = 'a';

filterTab.push(...filter(all, method('match', new RegExp(item, 'i'))));

const diff = difference(array3, filterTab);


text:
Q: Escopo de um service Estou com um problema em um service do AngularJS, após uma consulta REST usando RestAngular com retorno 401, preciso conseguir chamar um método do serviço no qual ele está inserido. O problema é que ao chamar o mesmo recebo a mensagem:

this.retrieveToken is not a function.

Aparentemente o escopo do error handling não é o mesmo do service, e por isso não reconhece o método. Existe um meio de se fazer isso? Meu código atualmente está assim:
util.service('Util',[dependencies... {

  this.buscar = function (addr,options) {
    Restangular.setFullResponse(true);
    var result = Restangular.all(addr).getList(options);
    result.then(function(response){ //success },
    function(error){

      //O PROBLEMA ACONTECE AQUI
      this.retrieveToken();

    });
  };
  this.retrieveToken = function (){ //code... };
}]);

A: O problema aí é o escopo.
O this dentro do then não se refere ao mesmo this que você criou a função, remova-os ou atribua this a alguma variável para referenciar o escopo externo.
Veja um exemplo:

angular.module('app', []);
angular.module('app').controller('mainController', function($http) {
  var controller = this;

  $http.get('http://www.google.com').then(function(){
  }, function() {
    controller.teste(); // Chamei aqui porque vai dar erro na requisição
  });

  this.teste = function(){
    console.log('ahoy');
  }
});

A: No javascript, quando queremos fazer referência ao própio objeto (this) em qualquer profundidade, usamos uma variável local para guardar a referência para o this. Ex:
var self = this;

ficando:
util.service('Util',[dependencies... {

    var self = this; // visível apenas no escopo do objeto como uma variável local

    this.buscar = function(addr, options) {

        Restangular.setFullResponse(true);

        var result = Restangular.all(addr).getList(options);

        result.then(function(response){ ... }, function(error) {

            //O PROBLEMA ACONTECE AQUI (não acontece mais)
            self.retrieveToken();

        });
    };

    this.retrieveToken = function() {
        //code...
    };

}]);


text:
Q: How can i check for text identical in textBox while typing inside the textBox? I have this Form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GatherLinks
{
    public partial class ChangeLink : Form
    {

        public ChangeLink()
        {
            InitializeComponent();

        }

        public string getText()
        {
            return textBox1.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox1.Text))
            {
                DialogResult = DialogResult.OK;
            }
            else
            {

            }

        }

        private void ChangeLink_Load(object sender, EventArgs e)
        {
            this.AcceptButton = button1;
        }

    }
}

And this code in Form1:
public void KeysValuesUpdate()
        {
            DialogResult dr = DialogResult.None;
            using (var w = new StreamWriter(keywords_path_file))
            {

                crawlLocaly1 = new CrawlLocaly(this);
                crawlLocaly1.StartPosition = FormStartPosition.CenterParent;
                if (FormIsClosing != true)
                {
                    dr = crawlLocaly1.ShowDialog(this);
                }
                if (dr == DialogResult.OK)
                {
                    if (LocalyKeyWords.ContainsKey(mainUrl))
                    {
                        LocalyKeyWords[mainUrl].Clear();
                        LocalyKeyWords[mainUrl].Add(crawlLocaly1.getText());
                    }
                    else
                    {
                        LocalyKeyWords[mainUrl] = new List<string>();
                        LocalyKeyWords[mainUrl].Add(crawlLocaly1.getText());
                    }
                    Write(w);
                    ClearListBox();
                }
                if (dr == DialogResult.Cancel)
                {
                    Write(w);
                }
                if (dr == DialogResult.None)
                {
                    Write(w);
                }
            }
        }

This KeysValuesUpdate() function is called here:
private void button2_Click(object sender, EventArgs e)
        {
            cl = new ChangeLink();
            cl.StartPosition = FormStartPosition.CenterParent;
            DialogResult dr = cl.ShowDialog(this);
            if (dr == DialogResult.Cancel)
            {
                cl.Close();
            }
            else if (dr == DialogResult.OK)
            {
                label4.Text = cl.getText();
                mainUrl = cl.getText();
                if (!LocalyKeyWords.ContainsKey(mainUrl))
                {
                    newUrl = true;
                    KeysValuesUpdate();
                }
                else
                {
                    newUrl = false;
                    KeysValuesUpdate();
                }
                OptionsDB.set_changeWebSite(cl.getText());
                cl.Close();
                listBox1.SelectedIndex = listBox1.Items.Count - 1;
            }
        }

When I click the button2 it's opening the new Form with a textbox and then inside I can type text.
Then I checking if the text inside already exist then newUrl is false or true.
Then when I click OK the OK button in the new Form then it's checking if the text I typed Contain/exist already or not.
I want that when the user type something in the textbox while he is typing if it's Contain/Exist the key then color the text in the textbox in Red one the user is keep typing and the text is not Contain/EXist color it back to Black but each time if the text in the textbox Contain/Exist already color it in Red and only if it's match case not if the text is inside other text:
This is in black:
For example : Danny hello all
But if I type in the textbox only: hello
Then the word hello will be in Red then if I kept typing after the hello then all the text in the textbox is Black if I delete the text and kept only the word hello then it will be Red again.
And that should be according to the code above and in realtime when im typing text in the textbox.
The new Form again with updated code with the textBox1 text changed event:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GatherLinks
{
    public partial class ChangeLink : Form
    {
        Form1 f1;

        public ChangeLink(Form1 f)
        {
            InitializeComponent();

            f1 = f;
        }

        public string getText()
        {
            return textBox1.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox1.Text))
            {
                DialogResult = DialogResult.OK;
            }
            else
            {

            }

        }

        private void ChangeLink_Load(object sender, EventArgs e)
        {
            this.AcceptButton = button1;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (f1.mainUrl.Contains(textBox1.Text))
            {
                textBox1.ForeColor = Color.Red;
            }
            else
                textBox1.ForeColor = Color.Black;
        }

    }
}

A: private void textBox_TextChanged(object sender, EventArgs e)
        {
            if (Regex.IsMatch(yourtext, @"\b" + textBox.Text + @"\b"))
            {
                textBox.ForeColor = Color.Red;
            }
            else
                textBox.ForeColor = Color.Black;
        }

Place your data containing variable name at the place of yourtext.
I have edited the answer. It is perfectly matching the whole words as you asked to do. To use Regex class, include System.Text.RegularExpressions namesapce.

A: You can implement textBox1 TextChanged event handler simply by defining a method
private void textBox1_TextChanged(object sender, EventArgs e)
{
    var textBox = sender as TextBox;
    String text = textBox.Text;
    if (SomeCheck(text))
    {
        textBox.ForeColor = Color.Red;
    }
    else
    {
        textBox.ForeColor = Color.Black;
    }
}

and assigning method textBox1_TextChanged to OnTextChanged property of textBox


text:
Q: For a directory, rename a file in a sub-directory with the sub-directory name+old filename into a new directory I have a folder with multiple sub-folders each with a file inside. I'm working in python and would like to rename the file with the associated sub-folder name plus the old file name to become new filename.
I've been able to get a list of the sub-folder and file names with os.walk() but I'm having problems changing the filename.
def list_files(dir):
    r = []
    for root, dirs, files in os.walk(dir):
        for name in files:
            r.append(os.path.join(root, name))
            os.rename(name, r)

I get the error:

TypeError: rename: dst should be string, bytes or os.PathLike, not
  list

When I return r I get the root and file name but am not able to change the filename. Appreciate any help.

A: import os
def list_files(dir):
    sub_folders = os.listdir(dir)
    for sub_folder in sub_folders:
        sub_folder_path = os.path.join(dir,sub_folder)
        for root, dirs, files in os.walk(sub_folder_path):
            for file in files:
                new_filename = root.replace(dir, "").replace(os.path.sep,"_").strip("_")+"_" + file
                os.rename(os.path.join(root, file), os.path.join(root, new_filename))
input_dir = ""
assert os.path.isdir(input_dir),"Enter a valid directory path which consists of sub-directories"
list_files(input_dir)

This will do the job for multiple sub-directories not nested directories. If you want to change how the name of the file should be, change the line new_filename = sub_folder+ "" + file.

A: Here's a similar answer to @VkreddyKomatireddy's, but it uses listdir() at both levels, and it checks for and ignores more deeply nested directories in the first level of subdirectories.
Here's my code, well annotated:
import os

def collapse_dirs(dir):

    # get a list of elements in the target directory
    elems = os.listdir(dir)

    # iterate over each element
    for elem in elems:

        # compute the path to the element
        path = os.path.join(dir, elem)

        # is it a directory?  If so, process it...
        if os.path.isdir(path):

            # get all of the elements in the subdirectory
            subelems = os.listdir(path)

            # process each entry in this subdirectory...
            for subelem in subelems:

                # compute the full path to the element
                filepath = os.path.join(path, subelem)

                # we only want to proceed if the element is a file.  If so...
                if os.path.isfile(filepath):

                    # compute the new path for the file - I chose to separate the names with an underscore,
                    # but this line can easily be changed to use whatever separator you want (or none)
                    newpath = os.path.join(path, elem + '_' + subelem)

                    # rename the file
                    os.rename(filepath, newpath)

def main():
    collapse_dirs('/tmp/filerename2')

main()

Here's my target directory before running the code:
filerename2
├── a
│   └── xxx.txt
├── b
│   ├── xxx.txt
│   └── yyyy
│       └── zzzz
├── c
│   └── xxx.txt
└── xxxx

and here it is after:
filerename2
├── a
│   └── a_xxx.txt
├── b
│   ├── b_xxx.txt
│   └── yyyy
│       └── zzzz
├── c
│   └── c_xxx.txt
└── xxxx


text:
Q: How does CosmosDB distribute throughput when provisioned per database (shared RUs) I have a problem understading how distribution of provisioned throughput works if I set up Cosmos DB to use shared RUs - setting RUs at database level.
I know when set on container (collection) level that throughput is divided between logical partitions e.g. if collection has provisioned throughput 400 RU/s and 10 logical partitions then throughput for each partition is 400/10 = 40 RU/s.
But what about when throughput is set per database?
Only documentation I found is https://learn.microsoft.com/en-us/azure/cosmos-db/set-throughput#set-throughput-on-a-database
As far as I can tell difference is that physical partitions are not dedicated to single container but can host logical partitions from different containers  - does this mean that throughput is divided between all logical partitions of all collections/containers?
For example: I have database with throughput 1000 RU/s and 2 collections, one with 3 logical partitions and second with 7 logical partitions, so is throughput divided 1000 / (3 + 7) = 100 RU/s for each logical partition?
OR
Is throughput reserved for all collections/partitions in sum? e.g. there is database with 1000 RU/s and one logical partitions use 800RU/s and other use 200RU/s (no matter what collection) then is it ok as long as they in sum dont exceed 1000 RU/s ?
Maybe question is short - is shared throughput distributed evenly between logical partitions (same as when set on collection level) or is not (somehow different)?

A: Thanks for your feedback. If you are configuring the throughput at database level. You cannot guarantee the throughput for each containers in it, unless you configure the throughput for containers as well.
All containers created inside a database with provisioned throughput must be created with a partition key. At any given point of time, the throughput allocated to a container within a database is distributed across all the logical partitions of that container. When you have containers that share provisioned throughput configured on a database, you can't selectively apply the throughput to a specific container or a logical partition.
You can follow this URL for understading the effect of setting throughput at database and containers level.
Set throughput on a database and a container
Hope it helps.

A:
Maybe question is short - is shared throughput distributed evenly between logical partitions (same as when set on collection level) or is not (somehow different)?

The answer is 'it is not'
This answer you're looking for is in the same page you have been looking at (I have also confirmed with with MS Support).
In this section
https://learn.microsoft.com/en-us/azure/cosmos-db/set-throughput#comparison-of-models

RUs assigned or available to a specific container (with database level provisioned throughput, manual or autoscaled):
No guarantees. RUs assigned to a given container depend on the properties. Properties can be the choice of partition keys of
containers that share the throughput, the distribution of the
workload, and the number of containers.

Basically Cosmos has an algorithm that works out how to allocate the provisioned database level throughput across the containers in the database.
I would expect there is some performance costs to the algorithm similar to standard autoscaling where if there was a burst of RU demand, the autoscaling won't scale up unless it is sustained for a certain period.
There is an exception if you do the database and container throughput provisioning where 1 or more containers has a fixed provisioned throughput. They would just be separate to the other containers that would share the database throughput. These containers would behave as you mentioned on how a standard container level throughput do e.g. divided among the partitions


text:
Q: Adding prebuilt native libraries to Android Studio project I am currently working on a wearOS app written in Kotlin that needs to consume a native library.
I have cloned the library from github and built it. The output consists of a libs folder with 4 different subfolders containing .so files for the different ABIs and a java folder with two java classes to interact with the library.
I have been reading the android docs but I still can't figure out how I need to import these files in my project to actually use the library. I don't have a lot of experience in android development, could anybody explain to me wat to do or just point me to the right docs/integration guide?


text:
Q: GCC_VERSION gcc-6.2.0 is given error: enable_if is not a class template but same code is working with gcc-4.3.0 Getting following error with GCC_VERSION gcc-6.2.0 but same code is working with gcc-4.3.0 :

char_traits.h:27:8: error: enable_if
  is not a class template

struct enable_if<true, T> { typedef T type;};

char_traits.h:27:25: error: redeclared with 1 template parameter

struct enable_if<true, T> { typedef T type; };

char_traits.h:24:8: note: previous
  declaration template struct enable_if used 2
  template parameters  struct enable_if {};
char_traits.h:32:22: error: expected nested-name-specifier before enable_if
       typedef typename enable_if<sizeof (T) == sizeof (char)>::type eif;

template<bool B, class T = void>
struct enable_if {};

template<class T>
struct enable_if<true, T> { typedef T type; };

template<typename T>
struct is_char
{
    typedef typename enable_if<sizeof (T) == sizeof (char)>::type eif;
};

could you please help to resolve these errors ?

A: These errors are most likely because you have a using namespace std; at file scope.
The template enable_if in the code is conflicting with the std::enable_if pulled in because of the using declaration.
This conflict  occurs only with GCC 6.2.0 because this version supports C++11 which was when std::enable_if was added to the language.
This conflict does not occur with GCC 4.3.0 because this version does not support C++11 and does not have the implementation of std::enable_if.
So get rid of the file scope and global using declarations and this will compile with GCC 6.2.0 as well.


text:
Q: How to concatenate multiple rows to single row without messing up the data? I am new to sql server and found a problem in using the FOR XML code.
My report builder is using sql server 2014.
I have the table like:

Field
Accessory

1.I
AA

1.I
BB

1.I
CC

1.II
AA

1.III
AA

1.III
BB

1.IV
AA

1.IV
BB

1.V
AA

And the result requires to be:

Field
Accessory

1.I
AA,BB,CC

1.II
AA

1.III
AA,BB

1.IV
AA,BB

1.V
AA

But instead, I've got this:

Field
Accessory

1.I
AA,BB,CC,AA,AA,BB,AA,BB,AA

1.II
AA,BB,CC,AA,AA,BB,AA,BB,AA

1.III
AA,BB,CC,AA,AA,BB,AA,BB,AA

1.IV
AA,BB,CC,AA,AA,BB,AA,BB,AA

1.V
AA,BB,CC,AA,AA,BB,AA,BB,AA

Is it appropriate to use FOR XML path for this kind of table grouping?
Thanks!
The query is :
SELECT
       Radi.Field,
       (SELECT
               Acce.AccessoryId+','
        FROM
               FieldAcce
               INNER JOIN Radi ON FieldAcce.RadiSer = Radi.RadiSer
               INNER JOIN Acce ON FieldAcce.AcceSer = Acce.AcceSer
        WHERE
               Radi.Id LIKE UPPER (@RNO)
               AND Radi.CourseID LIKE @CourseID
               AND Radi.PhaseId LIKE @PhaseID
        ORDER BY
               Radi.Field
        FOR XML PATH('')) AS [Accessory]
FROM
        FieldAcce
        INNER JOIN Radi ON FieldAcce.RadiSer = Radi.RadiSer
        INNER JOIN Acce ON FieldAcce.AcceSer = Acce.AcceSer
WHERE
        Radi.Id LIKE UPPER (@RNO)
        AND Radi.CourseID LIKE @CourseID
        AND Radi.PhaseId LIKE @PhaseID
GROUP BY
        Radi.Field
        Acce.AccessoryId
ORDER BY
        Radi.Field

The new query is as followed (It works when the STUFF() part have not added):
SELECT
    r.Field,
    STUFF(
        (SELECT
            ', ' + Acce.AccessoryId
         FROM
            Radi
            INNER JOIN FieldAcce ON Radi.RadiSer = FieldAcce.RadiSer
            LEFT OUTER JOIN Acce ON FieldAcce.AcceSer = Acce.AcceSer
         WHERE
            Radi.Id LIKE UPPER (@RNO)
            AND Radi.CourseId LIKE @CourseID
            AND LEFT (Radi.PlanSetupId,1) LIKE @PhaseID
            AND r.Field = Radi.Field
         ORDER BY
            Radi.Field
         FOR XML PATH(''))
          ), 1, 1, '') AS [Accessory]
FROM
    Radi r
    INNER JOIN FieldAcce ON r.RadiSer = FieldAcce.RadiSer
    LEFT OUTER JOIN Acce ON FieldAcce.AcceSer = Acce.AcceSer
WHERE
    Radi.Id LIKE UPPER (@RNO)
    AND Radi.CourseId LIKE @CourseID
    AND LEFT (Radi.PlanSetupId,1) LIKE @PhaseID
    AND EXISTS
        (SELECT
            r.Field
         FROM
            Radi cry
         WHERE
            r.Field = cry.Field
            AND cry.Field NOT LIKE N'APER%')
GROUP BY
    r.Field
ORDER BY
    r.Field

Sample data for Accessory is

Accessory

EDW45IN

A10

A06

EDW60IN

EDW45OUT

NDS

A084

A: The sub-query should reference the main query Field and AccessoryId
SELECT
       Radi.Field,
       (SELECT
               a.AccessoryId+','
        FROM
               FieldAcce fa
               INNER JOIN Radi r ON fa.RadiSer = r.RadiSer
               INNER JOIN Acce a ON fa.AcceSer = a.AcceSer
        WHERE
               r.Id LIKE UPPER (@RNO)
               AND r.CourseID LIKE @CourseID
               AND r.PhaseId LIKE @PhaseID
               -- add the following 2 lines
               AND r.Field = Radi.Field
               AND a.AccessoryId = Acce.AccessoryId
        ORDER BY
               r.Field
        FOR XML PATH('')) AS [Accessory]
FROM
        FieldAcce
        INNER JOIN Radi ON FieldAcce.RadiSer = Radi.RadiSer
        INNER JOIN Acce ON FieldAcce.AcceSer = Acce.AcceSer
WHERE
        Radi.Id LIKE UPPER (@RNO)
        AND Radi.CourseID LIKE @CourseID
        AND Radi.PhaseId LIKE @PhaseID
GROUP BY
        Radi.Field,
        Acce.AccessoryId
ORDER BY
        Radi.Field


text:
Q: yii2 how to use search with sqldataProvider for my requirement I need to use SqlDataProvider instead of ActiveDataProvider.
but if I enable search I am getting the error like:
Calling unknown method: yii\data\SqlDataProvider::isAttributeRequired()

my searchModel - `userProfileSearch looks like this:
public function search($params)
    {
     //   $query = UserProfile::find()->where($cond);

     $query = new Query;
        $query->select('*')->from('user_profile');

        // add conditions that should always apply here

        $dataProvider = new SqlDataProvider([
           // 'query' => $query,
           'sql' => $query->createCommand()->sql,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this['id'],
            'user_id' => $this['user_id'],
            'pincode' => $this['pincode'],
        ]);

        $query->andFilterWhere(['like', 'first_name', $this['first_name']])

            ->andFilterWhere(['like', 'last_name', $this->last_name])
            ->andFilterWhere(['like', 'phone', $this->phone])
            ->andFilterWhere(['like', 'email', $this->email])
            ->andFilterWhere(['like', 'gender', $this->gender])
            ->andFilterWhere(['like', 'skill_level', $this->skill_level])
            ->andFilterWhere(['like', 'play_type', $this->play_type])
            ->andFilterWhere(['like', 'address1', $this->address1])
            ->andFilterWhere(['like', 'address2', $this->address2])
            ->andFilterWhere(['like', 'city', $this->city])
            ->andFilterWhere(['like', 'state', $this->state])

            ->andFilterWhere(['like', 'Country', $this->country]);

        return $dataProvider;
    }

and in my controller it looks like this:
public function actionIndex()
    {
        $count = Yii::$app->db->createCommand('SELECT COUNT(*) FROM user_profile')->queryScalar();

    $sql= "$sql= "Select user_profile.id as id,
    user_profile.user_id as user_id,
    user_profile.first_name as first_name,
    user_profile.last_name as last_name,
    user_profile.city as city,
    user_profile.pincode as pincode,
    user_profile.profile_image as profile_image,
    user_profile.gender as gender,
    user_profile.play_type as play_type,
    user_profile.skill_level as skill_level,
    ( 3959 * acos
    (cos ( radians($latitude))
    * cos( radians( latitude ))
    * cos( radians( longitude) - radians($longitude))
     + sin ( radians($latitude) )
    * sin( radians( latitude))))
    AS distance
    FROM user_profile
    HAVING distance < 20";";

    $searchModel = new UserProfileSearch();
    $sqlProvider = new SqlDataProvider(['sql'=> $sql]);
    $searchModel = $searchModel->search(Yii::$app->request->queryParams,$sql);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $sqlProvider,
    ]);
}

How I can make the search work?

A: I think it's because you are rewriting your $searchModel variable with return of search() method which returns SqlDataProvider.
Try to change your controller to this:
$searchModel = new UserProfileSearch();
$sqlProvider = $searchModel->search(Yii::$app->request->queryParams,$sql);

return $this->render('index', [
    'searchModel' => $searchModel,
    'dataProvider' => $sqlProvider,
]);

A: Though I couldn't resolve it using SqlDataProvider and certainly like to know how to implement using SqlDataProvider.
Keeping everything intact from Gii generated code I modified the query in UserProfileSearch.php
like below:
public function search($params)
    {
        $user = UserProfile::findOne(['user_id'=>Yii::$app->user->identity->id]);

        $latitude = $user->latitude;
        $longitude = $user->longitude;
        $query = UserProfile::find()->select(['id','user_id','first_name','last_name','phone','email','pincode','skill_level','play_type',
        'profile_image','latitude','longitude','gender','city',"( 3959 * acos
        (cos ( radians($latitude))
        * cos(radians(latitude))
        * cos( radians(longitude) - radians($longitude))
         + sin (radians($latitude) )
        * sin(radians(latitude)))) as distance"]);
        $query->having(['<','distance', 12.4274]);

        $dataProvider = new ActiveDataProvider([
        'query'=>$query

        ]);

with this my pre-filter for 20Km is working fine as well as the search.


text:
Q: Modifying the contents of a HTML webpage on the fly in PHP I would like to load a HTML document and modify it's text in PHP. For example, if I have a document like this:

<title>Test - Example.com</title>

Link number 1: Example.com

Link number 2: Example.com - some random text

I would like to add an active link () to the second paragraph. But I don't want to touch other places where the Example.com string occurs, like the first paragraph or the title of the document. So I cannot use regular expressions for this, as I need to take into account the structure of the document. Any ideas as to how to tackle this problem? Also the HTML documents I will be receiving might be live webpages, so they might contain errors, JavaScript code, etc.

A: The "proper" way to do it would be via PHP's DOM object, which can import HTML, after which you can use XPath to dig down to the exact link you want. Of course, DOM is highly picky about invalid markup and can barf on quite simple errors that browsers handle nicely. You may have to massage the input to fix up the worst of the errors before you can round-trip the content through DOM.
The worst stop-dead-in-DOM's-tracks error I've found is having multiple html and/or body blocks (e.g. a stupid server inserting a self-contained  block before the actual page contents).


text:
Q: write a file from a docker container in google-cloud-composer Some context:
I'm using composer-1.3.0-airflow-1.10.0
Installed PyPi package docker===2.7.0
For a while I tried to use the DockerOperator, but I need to pull images from a private gcr.io registry located in another gcp-project, and that is a mess.
I won't go into the details of why I gave up on this.. I switched to a simple PythonOperator used to pull and run the docker image. Here how the Operator goes:
def runImage(**kwargs):
    workingDir = "/app"
    imageName = "eu.gcr.io/private-registry/image"
    volume = {"/home/airflow/gcs/data/": {"bind": "/out/", "mode": "rw"}}
    userUid = os.getuid()
    command = getContainerCommand()
    client = getClient()
    print("pulling image")
    image = pullDockerImage(client, imageName)
    print("image pulled. %s", image.id)
    output = client.containers.run(
        image=imageName,
        command=command,
        volumes=volume,
        privileged=True,
        working_dir=workingDir,
        remove=True,
        read_only=False,
        user=userUid)
    print output
    return True

task = PythonOperator(
    task_id="test_pull_docker_image",
    python_callable=runImage,
    dag=dag
)

Image is well pulled. And it run (which was already a victory).
The container write some files to /out/, which I mounted as a volume to /home/airflow/gcs/data with rw rights.
The working_dir, user, privileged, read_only options were added for test, but I don't think they're relevent.
The files are not created.
writing a file directly in pyhton to /home/airflow/gcs/data works just fine.
The container itself is a complied C#.
Locally if the container fails to write the files I get an error (like Unhandled Exception: System.UnauthorizedAccessException: Access to the path '/out/file.txt' is denied. ---> System.IO.IOException: Permission denied)
But when I run the DAG inside airlfow composer everything looks just fine, container output is as expected, no error raised.
Maybe the Dockerfile could be usefull:
FROM microsoft/dotnet:2.1-sdk AS build-env
WORKDIR /app

# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore

# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out

# Build runtime image
FROM microsoft/dotnet:2.1-sdk
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "programm.dll"]

So the question is,
Why does it not write the files? And how to allow the container to write files to /home/airflow/gcs/data?

A: So I resolved this issue thanks to my other question
The answer here is in two parts:
/home/airflow/gcs is a gcsfuse volume. Using this directory for the DockerVolume just doesn't work (may work by adding a plugin, I lost the link for this :/ )
We want to add a volume inside the airflow-workers, we can do so by updating the kubectl config :
see this question for the how to update the config.
We want to add a hostPath:
containers:
  ...
  securityContext:
    privileged: true
    runAsUser: 0
    capabilities:
      add:
      - SYS_ADMIN
  ...
  volumeMounts:
  - mountPath: /etc/airflow/airflow_cfg
    name: airflow-config
  - mountPath: /home/airflow/gcs
    name: gcsdir
  - mountPath: /var/run/docker.sock
    name: docker-host
  - mountPath: /bin/docker
    name: docker-app
  - mountPath: /path/you/want/as/volume
    name: mountname
  ...
  volumes:
  - configMap:
    defaultMode: 420
    name: airflow-configmap
  name: airflow-config
  - emptyDir: {}
    name: gcsdir
  - hostPath:
      path: /path/you/want/as/volume
      type: DirectoryOrCreate
    name: mountname
  - hostPath:
      path: /var/run/docker.sock
      type: ""
    name: docker-host
  - hostPath:
      path: /usr/bin/docker
      type: ""
    name: docker-app

And now in the DAG definition we can use
volume = {"/path/you/want/as/volume": {"bind": "/out/", "mode": "rw"}}
File will exists inside the POD, and you can use another task to upload them in a gcs bucket or so.
Hope it can help somewhat :)


text:
Q: Creating a new array combining two existing objects through iteration with condition in jQuery I have a main object consisting of two main properties, data which contains messages and included which contains the senders of the messages. I want to create a new Array called messages which will contain all the values of both objects but in a way that every object inside this array will consist of the data values adding the correct sender as property to each of them.
I am able to separate the main object to two different ones, one containing the data and the other containing the senders.
if (jsonAPI.data) {
    $.each(jsonAPI.data, function(index, value) {
        dataObj[index] = value;
    });
}

if (jsonAPI.included) {
    $.each(jsonAPI.included, function(index, value) {
        senders[value.id] = value;
    });
}

I guess I have to make an iteration for every value of the dataObj and check if the relationships.sender.data.id is equal to senders.id then add the new property to dataObj, but I don't know how to write it.
What I say can be more clear in this fiddle https://jsfiddle.net/mosmic/f2dzduse/

A: Working jsfiddle: https://jsfiddle.net/f2dzduse/5/
var jsonAPI = {<snip>};

var dataObj = {};

if (jsonAPI.data) {
    $.each(jsonAPI.data, function(index, value) {
        dataObj[index] = value;
    });
}

$.each(dataObj, function(index, value) {
    //Prevent error if there is no sender data in included
    if(jsonAPI.included.length - 1 >= index) {
        //check if ids are equal
        if(value.relationships.sender.data.id == jsonAPI.included[index].id) {
            value.sender = jsonAPI.included[index];
        }
    }
});

console.log(dataObj);

This code assumes that jsonAPI.data.relationships.sender.data.id and jsonAPI.included.id are both in the same order!
If this is not always the case let me know and I'll rewrite the code to loop trough each jsonAPI.data and then loop trough jsonAPI.include to check for an equal id. This code will be slower since it will loop a total of jsonAPI.data.length X jsonAPI.include times.
Here's the updated code: https://jsfiddle.net/f2dzduse/6/
var jsonAPI = {<snip>};

var dataObj = [];

$.each(jsonAPI.data, function(x, data) {
    dataObj[x] = data;
    $.each(jsonAPI.included, function(y, included) {
        if(data.relationships.sender.data.id == included.id) {
            dataObj[x].sender = included;
        }
    });
});

console.log(dataObj);


text:
Q: Using New Relic end-user monitoring with a Sencha Ext JS 4 application I'm planning on building my first application with Ext JS 4 and I'm curious if the New Relic application performance monitoring tool would be useful for end-user browser performance monitoring? My only experience with New Relic was building an application with the CodeIgniter PHP framework and HTML views.
Does anyone have any experience trying this?

A: I work at New Relic on the engineering team.
Of course, it depends on what you want to measure. New Relic is good if you want the actual times experienced by your users. It also now captures samples of poorly performing requests.
We use it every day at New Relic. And a large portion of our 14,000 customers do as well. But it does depend on your needs.
For example: do you want to monitor server time too? (New Relic does that) Do you want more customization? (New Relic isn't infinitely customizable -- the aim is to give you a curated useful experience, not just throw data at you). There are other tools out there that have a different focus, but I'd encourage you to give it a try. It doesn't take more than a few minutes to install, so try it and let us know what you think!


text:
Q: Visual Studios Remote Build Fails Error Code 2 Trying to output IPA File, and each attempt I'm getting this.
I have created the xcode8.js, setup the Config with the Before_Compile. But it still says Command Not Found.
Why? Any Help.
Executing script found in hooks directory for hook "before_compile": hooks/before_compile/xcode8.js
Running command: /Users/rblake/.taco_home/remote-builds/taco-remote/builds/3584/cordovaApp/hooks/before_compile/xcode8.js /Users/rblake/.taco_home/remote-builds/taco-remote/builds/3584/cordovaApp
/Users/rblake/.taco_home/remote-builds/taco-remote/builds/3584/cordovaApp/hooks/before_compile/xcode8.js: line 1: use strict: command not found
/Users/rblake/.taco_home/remote-builds/taco-remote/builds/3584/cordovaApp/hooks/before_compile/xcode8.js: line 1:
: command not found
/Users/rblake/.taco_home/remote-builds/taco-remote/builds/3584/cordovaApp/hooks/before_compile/xcode8.js: line 2:
: command not found
/Users/rblake/.taco_home/remote-builds/taco-remote/builds/3584/cordovaApp/hooks/before_compile/xcode8.js: line 3: syntax error near unexpected token `('
/Users/rblake/.taco_home/remote-builds/taco-remote/builds/3584/cordovaApp/hooks/before_compile/xcode8.js: line 3: `var fs    = require('fs');


text:
Q: failed to manipulate my Arraylist I need help ,  I have an arrayList of objects . This object contains multiple fields I'm interested in this question by two date fields (date_panne date_mise and running) and two other time fields (heure_panne and time start),
And  I would like to obtain the sum of the difference between (date_panne, heure_panne) and (date_mise_en_marche; heure_mise_en_marche) to give the total time of failure.
if someone can help me please I will be gratful this is my function :
public String disponibile() throws Exception {

    int nbreArrets = 0;
    List<Intervention> allInterventions = interventionDAO.fetchAllIntervention();
    List<Intervention> listInterventions = new ArrayList<Intervention>();

    for (Intervention currentIntervention : allInterventions) {
        if (currentIntervention.getId_machine() == this.intervention.getId_machine()
            && currentIntervention.getDate_panne().compareTo(getProductionStartDate()) >= 0
            && currentIntervention.getDate_panne().compareTo(getProductionEndDate()) <= 0) {

            listInterventions.add(currentIntervention);
        }
    }
    savedInterventionList = listInterventions;

    return "successView" ;
}

A: Assuming the the dates are truncated to the day and are of type java.util.Date, and that the times only contain hours, minutes, seconds and milliseconds and are also of type Date, start by creating a method like
private Date combine(Date dateOnly, Date timeOnly) {
    Calendar dateCalendar = Calendar.getInstance();
    dateCalendar.setTime(dateOnly);
    Calendar timeCalendar = Calendar.getInstance();
    timeCalendar.setTime(timeOnly);

    dateCalendar.add(Calendar.HOUR_OF_DAY, timeCalendar.get(Calendar.HOUR_OF_DAY));
    dateCalendar.add(Calendar.MINUTE, timeCalendar.get(Calendar.MINUTE));
    dateCalendar.add(Calendar.SECOND, timeCalendar.get(Calendar.SECOND));
    dateCalendar.add(Calendar.MILLISECOND, timeCalendar.get(Calendar.MILLISECOND));

    return dateCalendar.getTime();
}

Now, it's simply a matter of looping through the interventions you want to sum, computing the difference between the dates as milliseconds, and add them:
long totalMillis = 0L;
for (Intervention intervention : interventions) {
    Date marche = combine(intervention.getDateMiseEnMarche(), intervention.getTimeMiseEnMarche());
    Date panne = combine(intervention.getDatePanne(), intervention.getTimePanne());
    long differenceInMillis = marche.getTime() - panne.getTime();
    totalMillis += differenceInMillis;
}


text:
Q: Condition Vairable and notify_all In the following code (taken from cpp reference with an extra cout added) why don't we see ...finished waiting.  after the first cv.notify_all?
#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>

std::condition_variable cv;
std::mutex cv_m; // This mutex is used for three purposes:
                 // 1) to synchronize accesses to i
                 // 2) to synchronize accesses to std::cerr
                 // 3) for the condition variable cv
int i = 0;

void waits()
{
    std::unique_lock<std::mutex> lk(cv_m);
    std::cerr << "Waiting... \n";
    cv.wait(lk, []{return i == 1;});
    std::cerr << "...finished waiting. i == 1\n";
}

void signals()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    {
        std::lock_guard<std::mutex> lk(cv_m);
        std::cerr << "Notifying...\n";
    }
    cv.notify_all();

    std::cerr << "I should see i here...\n";

    std::this_thread::sleep_for(std::chrono::seconds(1));

    {
        std::lock_guard<std::mutex> lk(cv_m);
        i = 1;
        std::cerr << "Notifying again...\n";
    }
    cv.notify_all();
}

int main()
{
    std::thread t1(waits), t2(waits), t3(waits), t4(signals);
    t1.join();
    t2.join();
    t3.join();
    t4.join();
}

Output:
Waiting...
Waiting...
Waiting...
Notifying...
I should see i here...
Notifying again...
...finished waiting. i == 1
...finished waiting. i == 1
...finished waiting. i == 1

A: Because this line:
cv.wait(lk, []{return i == 1;});

you passed a predicate, thus it will wake up only if the predicate returns true. After first notify_all(), the predicate is not satisfied.

A: Because it hasn't finished waiting.
You told it to wait until i is 1, but it is still 0. So it will keep waiting.
This is the case even though you "notified" it — you notified it that a change happened, but actually a change didn't happen, so it went back to waiting.
notify() is not ignore_the_predicate_i_gave_you_and_stop_waiting().


text:
Q: HTML5 IndexedDB - How to merge all records into one My idea is download chunks a huge file from server.

*

*Chunks stored into an IndexedDB.

*After download all chunks, merge all records into one (as SQL SELECT * FROM XXX ...).

*Save into disk "saveAs()" or create URL to IndexedDB...

(Or any idea?)
I do not know how to do step 2. and 3.
(Below is an example of storing 10,000 records in the DB and the expected output after step 2. should be SusanSusanSusanSusanSusan...)
if (transaction) {
    transaction.oncomplete = function () {
    }
    transaction.onabort = function () {
        writeToConsoleScreen("transaction aborted.");
        localDatabase.db.close();
    }
    transaction.ontimeout = function () {
        writeToConsoleScreen("transaction timeout.");
        localDatabase.db.close();
    }
    var store = transaction.objectStore(osTableName);
    if (store) {
        var req;
        var customer = {};
       // create ten thousand records
       for (var loop = 0; loop < 10000; loop++) {
            customer = {};
            customer.fname = 'Susan';
            req = store.add(customer);
            req.onsuccess = function (ev) {
            }
            req.onerror = function (ev) {
                writeToConsoleScreen("Failed to add record." + "  Error: " + ev.message);
            }
        }
    }
}

A: <!DOCTYPE html>
<script>
var open = indexedDB.open('chunks-example');
open.onupgradeneeded = function() {
  // Create schema if necessary
  var db = open.result;
  db.createObjectStore('chunks');
};

// 1. Chunks stored into an IndexedDB.
open.onsuccess = function() {
  var db = open.result;
  var tx = db.transaction('chunks', 'readwrite');
  var store = tx.objectStore('chunks');
  for (var i = 0; i < 10; ++i) {
    // For realz, this would be via
    // XMLHttpRequest.response and async.
    var chunk = new Blob(['chunk ' + i + '\n'],
      {type: 'application/octet-stream'});
    store.put(chunk, i);
  }
  tx.oncomplete = function() { merge(db); };
};

// 2. After "download" all chunks, merge all records into one
function merge(db) {
  var tx = db.transaction('chunks');
  var store = tx.objectStore('chunks');
  var chunks = [];
  var request = store.openCursor();
  request.onsuccess = function() {
    var cursor = request.result;
    if (cursor) {
      chunks.push(cursor.value);
      cursor.continue();
    } else {
      saveAs('myfile', new Blob(chunks,
        {type: 'application/octet-stream'}));
    }
  };
}

// 3. Save into disk "saveAs()"
function saveAs(filename, blob) {
  var a = document.documentElement.appendChild(document.createElement('a'));
  a.href = URL.createObjectURL(blob);
  a.download = filename;
  a.click();
  a.parentElement.remove(a);
}
</script>


text:
Q: Is ConTeXt a good choice for creating a nice large catalog? I only know a little of ConTeXt but I was wondering if it would be a good idea to use ConTeXt for creating a large catalog containing hundreds of books with a three column layout inside. I was thinking that context would be easier to add products and remove products and their positions on each page would be handled automatically based on my settings. This would be better than using InDesign, Scribus, or Office Publisher, etc. and having to manually create each page and insert and space out each product, while trying to fit as many on a page and later having to manually shift over books to add or the opposite to remove books. My fear is that ConTeXt is not capable of doing what I want or that it would take too much work to get it the way I want in order for it to be worth it.
Summary: using design software would require to much manual work to update and change the catalog. I'm curious if ConTeXt is worth using for such a project or if I should find something else.
Example: here's a picture inside the old catalog. I would like the new to look similar:

A: Absolutely. I have prepared couple of exhibition catalogues in ConTeXt and really enjoyed using it. It shouldn't be too difficult to define a float like the one in the image which could be used in conjunction with columns or columnsets. It looks like your data are coming from a database so perhaps it might be useful to output them in xml and feed it into ConTeXt.


text:
Q: How to generate configuration in java class from options definition I wonder if there is an nice java api to generate configuration from a description of options.
Instead of generate a pojo with getter and setters on your configuration options (we always code the same thing here). I would like to describe my configuration (options of configuration) in a metadata file and then find a way to generate a Configuration java file with all options inside it.

A: Yes you can use nuiton-config
 which offers an maven plugin to generate java configuration class.
There is an nice example explaining how to generate you configuration.
Example
Imagine you have a configuration with two options:
app.login
app.password

in a maven module
<groupId>org.nuiton.config</groupId>
<artifactId>example</artifactId>
<version>1.0</version>

You can describe with configuration in a file (src/main/config/MyConfig.ini):
description = Exemple de configuration
[option login]
description = User login
key = app.login
type = string
[option password]
description = User password
key = app.password
type = string

then invoke the nuiton-config mojo with adding this configuration in your pom:
<plugin>
  <groupId>org.nuiton</groupId>
  <artifactId>nuiton-config-maven-plugin</artifactId>
  <version>3.1.1</version>
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Do a mvn compile.
You can use use the generated configuration java file org.nuiton.config.ExampleConfig.


text:
Q: Why am I getting an error message when trying to plot an xts object in R? I am trying to plot an xts object in R. Below is the code I am running that gives me the error message.
outcomes_xts <- xts(true_outcomes, as.yearqtr(end_dates))

plot(as.zoo("outcomes_xts"),
     col = "purple",
     lwd = 4,
     ylab = "Quarterly Change in per-capita GDP (£)",
     main = paste0("ADL(1,1): Pseudo-Out-Of-Sample Forecasts of Differenced",
     " per-capita GDP, United Kingdom"),
     ylim = -200:200)

However this code gives me the following error message:
Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
2: In xy.coords(x, y) : NAs introduced by coercion

From what I gather, this can be caused by the data in the xts object being stored as character strings rather than numeric, but this isn't the case with this data. Neither is it caused by n/a's in the xts object - I have tried using na.omit() on the xts object but I still get the same error. Help would be appreciated, thank you.
Here is my result when I run dput(outcomes_xts[1:30])
structure(c(62, 48, 24, 30, 4, 12, 31, 58, 54, 70, 28, 13, 3,
33, 46, 20, 37, 15, 31, -52, -131, -169, -149, -37, -10, 8, 37,
69, 37, -6), class = c("xts", "zoo"), index = structure(c(1057017600,
1064966400, 1072915200, 1080777600, 1088640000, 1096588800, 1104537600,
1112313600, 1120176000, 1128124800, 1136073600, 1143849600, 1151712000,
1159660800, 1167609600, 1175385600, 1183248000, 1191196800, 1199145600,
1207008000, 1214870400, 1222819200, 1230768000, 1238544000, 1246406400,
1254355200, 1262304000, 1270080000, 1277942400, 1285891200), tzone = "UTC", tclass = "yearqtr"), .Dim = c(30L,
1L))


text:
Q: start of X series I would like to know how to set x axis to start drawing at the first point of data, instead of the first day of date-range?.
(too bad I can't post pictures because I don't have the 10 points)

A: From your question it seems that you want to set the x-range in a time-series (this is a guess - it would help if you wrote the gnuplot code that you are using).
You can do this like so:
set xdata time
set timefmt "%d/%m/%Y %H:%M:%S"
set xrange["26/10/2010 13:00:00":"26/10/2010 14:00:00"]

Notice that the xrange must be written in the same way as the timefmt.
See gnuplot v4.4: Problem plotting using timeseries x axis for more info.


text:
Q: Swift animate UIView with multiple options How does swift handle multiple options when animating UIView? I tried
UIView.animateWithDuration(0.2, delay: 0.0, options: .Repeat | .Autoreverse, animations: {self.alpha = 0.0}, completion: nil)

but seems to confuse the | with a bitwise operator:
Undefined symbols for architecture i386:
 "__TFSsoi1oUSs17_RawOptionSetType_USs21BitwiseOperationsTypeSs9Equatable__FTQ_Q__Q_", referenced from:
      __TFC17TextDrawing10cursorViewW8blinkingSb in cursorView.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I am using the latest Xcode version from the AppStore.

A: Swift 2:
UIView.animateWithDuration(0.2, delay: 0.0, options: [.Repeat, .Autoreverse], animations: {self.alpha = 0.0}, completion: nil)

Swift 3, 4, 5
UIView.animate(withDuration: 0.2, delay: 0.0, options: [.repeat, .autoreverse], animations: {self.alpha = 0.0}, completion: nil)

A: The preview answer won't work in nowdays swift. The good answer was given by @mxcl.
If despite all you want to use this form, you have to retrieve the rawValue and rebuild a new UIViewAnimationOptions with an inclusive OR mask.
UIViewAnimationOptions(rawValue:(UIViewAnimationOptions.Autoreverse.rawvalue | UIViewAnimationOptions.Repeat.rawValue))

A: Swift 3:
Tested and ok:
UIView.animate(withDuration: 0.2, delay: 0.0, options: [.repeat, .autoreverse], animations: {
            }, completion: nil)

A: From the docs it looks like what you are doing is correct?
Have you tried wrapping the options in parentheses?
Either that or put the options into a variable first and try that?

A: This is working code for me:
        UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.Autoreverse | UIViewAnimationOptions.Repeat, animations: { () -> Void in
            disc.layer.transform = CATransform3DMakeScale(1.0, 1.0, 1.0)
            }) { (success) -> Void in
        }


text:
Q: Scrapy FTP export not working I'm trying to upload the CSV containing all my scraped data on FTP, using
scrapy crawl spidername --set FEED_URI=ftp://user:pass@ftp.example.com/path/to/export.csv

The Terminal doesn't give any error and starts scraping, but when it finishes its work I can't see any file on my server.
Additional information:

*

*Scrapy version 1.0.3

*Operating System Mac OS X El Capitan

*List item

The spider works perfectly if I write to a local file (CSV or Json).
Help?
UPDATE
I didn't make anything new, nor changed anything in my code, but after many tries, it worked. The file is on the server. Unfortunately I can't say what made it work this time.

A: You're setting the global option of scrapy wrong. Help says it should be one of the following formats:
--set=NAME=VALUE, -s NAME=VALUE
So use the -s instead of --set.


text:
Q: Regular Expression to Anonymize Names I am using Notepad++ and the Find and Replace pattern with regular expressions to alter usernames such that only the first and last character of the screen name is shown, separated by exactly four asterisks (*). For example, "albobz" would become "a****z".
Usernames are listed directly after the cue "screen_name: " and I know I can find all the usernames using the regular expression:
screen_name:\s([^\s]+)
However, this expression won't store the first or last letter and I am not sure how to do it.
Here is a sample line:
February 3, 2018    screen_name: FR33Q  location: Europe    verified: false lang: en

A: Method 1
You have to work with \G meta-character. In N++ using \G is kinda tricky.
Regex to find:
(?>(screen_name:\s+\S)|\G(?!^))\S(?=\S)

Breakdown:

*

*(?> Construct a non-capturing group (atomic)

*

*( Beginning of first capturing group

*

*screen_name:\s\S Match up to first letter of name

*) End of first CG

*| Or

*\G(?!^) Continue from previous match

*) End of NCG

*\S Match a non-whitespace character

*(?=\S) Up to last but one character

Replace with:
\1*

Live demo
Method 2
Above solution substitutes each inner character with a * so length remains intact. If you want to put four number of *s without considering length you would search for:
(screen_name:\s+\S)(\S*)(\S)

and replace with: \1****\3
Live demo


text:
Q: v-select dropdown shows outside the v-dialog I am using vuetify 2.3.10. I have the following piece of code and the issue I am facing here is that the select dropdown for v-select appear on top of the page rather than in the dialog box attached to the v-select. I guess there is some issue with the position css property of the dropdown. How can I resolve this?
<template>
  <v-layout row wrap>
    <v-flex xs12 sm12 lg12>

        <v-dialog v-model='select_location' id="change-location-dialog" >
          <v-card>
            <v-card-text>

Select Location

              <v-select v-model="selectedLocation"
                        persistent
                        attach="#change-location-dialog"
                        placeholder="Select Location"
                        :items='locations'
                        item-text='name'
                        item-value='id'
                        max-width="250">
              </v-select>
            </v-card-text>
            <v-card-actions>
              <v-btn @click="picklocation">Ok</v-btn>
            </v-card-actions>
          </v-card>
        </v-dialog>

    </v-flex>
  </v-layout>
</template>

A: Remove the attach="#change-location-dialog on the <v-select/> and it should be fine. I guess what happens is that, it tries to attach the selection menu on the dialog, including its backdrop which covers the whole page so it appears on top. By removing the attach prop, it will be attached to the <v-select/> textfield by default.
Here's a demo:


text:
Q: Вычисление поэлементного произведения изображений через свертку в частотной области Есть теорема, которая говорит, что произведение двух функций в пространственной области есть их свертка в частотной (с коэффициентом 1/(2*PI)).
Для начала пытаюсь реализовать пример согласно этой теореме в Matlab`е следующим образом:
A=[1 2 5 3; 8 9 6 7; 5 0 2 4; 1 0 4 5];
B=[8 9 3 4; 9 8 2 0; 7 7 9 8; 1 2 8 2];
mult = A.*B;

Af = fft2(A);
Bf = fft2(B);

mult2 = conv2(Af*.Bf);

Собственно вопрос: размер mul2 больше чем размер матрицы mult, и значения не совпадают, в чем причина? И еще вопрос: в C++ я свертку вычисляю с помощью скользящего окна, т.е. между двумя изображениями матрица свертки будет размера (W1 - w2)x(H1 - H2), где W1, H1 - размеры первого изображения, а W2, H2 - соответственно второго. Так как же получить результат, размерность которого была бы такой же размерности как и результат поэлементного умножения двух двумерных массивов (в случае с массивами A и B 4x4).

A: Чтобы получить центральную часть свёртки нужно в функцию conv2 передать дополнительный аргумент 'same':
mult2 = conv2(Af, Bf, 'same')

Также после свёртки не забываем вернуться во временную область ifft2.


text:
Q: Question about surjective functions Let $S$ and $T$ be sets and let  $f : S \to T$ be a function. Prove the following:

If $R$ is a set and $h:R \rightarrow S$ is a function such that $f \circ h$ is surjetive then also $f$ is surjective

Approach: Following the advice of my previous thread, assume for some $r\in S$ and $p \in T$, $f(r)=p$. If we set $r=g(x)$ for some $x \in R$ then $f$ becomes surjective because $f \circ h $ is surjective. How does that look?

A: Think of S,R, T as set of cities in three countries of name SS, RR, TT.
Imagine f as a specification of direct flights, with just one flight from each city of SS to cities of TT  etc.
Surjectivity of f means our selection of cities have covered all the cities of TT.
Now given data means $f\circ h$ is surjective. That is flight from RR to TT with one stop in between at SS cover all the cities of TT.  This must be possible only if the second leg covers all cities.

A: Not quite right. See if you can follow this argument and how it differs from yours:
Assume that $f\circ h$ is onto and that $t\in T$. Then there exists $r\in R$ such that $(f\circ h)(r)=t$. But then $f(h(r))=t$ with $h(r)\in S$. Hence, $f$ is onto. $\blacksquare$


text:
Q: Error when uploading images using NSURLConnection I am attempting to upload images using NSURLConnection and the POST method here is what I have so far.
  NSData* imageData =UIImageJPEGRepresentation(_imageView.image, 90);
NSString  * urlString =@"mywebiste.myphpfile.php";
NSMutableURLRequest * request=[[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary=@"---------------------------14737809831466499882746641449";
NSString *contentType=[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary]dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData * returnData=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString=[[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(returnString);

here is the php file that I am calling
<?PHP

    $uploaddir = './';      //Uploading to same directory as PHP file
    $file = basename($_FILES['userfile']['name']);
    $uploadFile = $file;
    $randomNumber = rand(0, 99999);
    $newName = $uploadDir . $randomNumber . $uploadFile;

    if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
        echo "Temp file uploaded. \r\n";
    } else {
        echo "Temp file not uploaded. \r\n";
    }

    if ($_FILES['userfile']['size']> 300000) exit("Your file is too large.");
    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $newName)) {
        $postsize = ini_get('post_max_size');   //Not necessary, I was using these
        $canupload = ini_get('file_uploads');    //server variables to see what was
        $tempdir = ini_get('upload_tmp_dir');   //going wrong.
        $maxsize = ini_get('upload_max_filesize');
        echo "http://www.mywebsite.com/{$file}" . "\r\n" . $_FILES['userfile']['size'] . "\r\n" . $_FILES['userfile']['type'] ;
    }

?>

The error I get from this is a bit unspecific.
 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>500 Internal Server Error</title>

Internal Server Error

The server encountered an internal error or
misconfiguration and was unable to complete
your request.

Please contact the server administrator at
webmaster@mywebsite.com to inform them of the time this error occurred,
and the actions you performed just before this error.

More information about this error may be available
in the server error log.

Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.

has this ever happened to anyone before and is there any way to fix it?
I need to figure this out and I don't know where to go from here.
Thanks in advance!


text:
Q: Jmeter assertion result listener as variable My JMeter test plan looks like this:
HTTP Request
- Assertion
HTTP Request
- Assertion
HTTP Request
- Assertion
Assertion Result Listener

I'd like to define all assertion results from the listener as a variable and use that variable in a POST call to JIRA, so the description contains an overview of all assertions and failure and pass of each assertion.
Assertion Result Listener
I know I can save the assertion results to a file and upload that, but I need the assertion results as text in the JIRA. Any ideas how I can do that?
edit: this is for a functional test suite.

A: *

*Add JSR223 Listener to your Thread Group

*Put the following code into "Script" area
def result = vars.get('result')
StringBuilder builder = new StringBuilder()
if (result != null) {
    builder.append(result).append(System.getProperty('line.separator'))
}

prev.getAssertionResults().each { assertionResult ->
    builder.append(prev.getSampleLabel()).append(System.getProperty('line.separator'))
    if (assertionResult.isFailure()) {
        builder.append('\t').append(assertionResult.getFailureMessage()).append(System.getProperty('line.separator'))
    }
}
vars.put('result', builder.toString())
props.put('result', builder.toString())

*Add tearDown Thread Group to your Test Plan

*Refer the generated string holding the assertion results using __P() function as ${__P(result,)}
Demo:

See Apache Groovy - Why and How You Should Use It article for more information on Groovy scripting in JMeter.


text:
Q: Is it possible to put two INSERT statements in one SQL query I'm trying to get two INSERT statement into one SQL query. I tried several things but nothing seems to work. If I look on the internet it seems it has to work. But it doesn't work for me and I get an error. I'm using this code with PDO.
I tried multiple web browsers, multiple types of code and I tried the "BEGIN" and "COMMIT" statement.
$sql = "INSERT INTO gebruiker (email, wachtwoord, rol_id) VALUES (?, ?, 2); ".
"INSERT INTO huisarts (voornaam, achternaam, email, straatnaam, huisnummer, postcode, plaats, telefoonnummer, uid, rol_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, LAST_INSERT_ID(), 2);";
$pdostatement = $pdo->prepare($sql);

A: That silly concatenation mistake aside, it is technically possible to run two INSERT queries in one call, but there is not a single reason to do so.
Besides, you will need to configure PDO specifically to allow multiple queries which is not advised.
Therefore, just run these two queries as two separate prepared statements.
$sql = "INSERT INTO gebruiker (email, wachtwoord, rol_id) VALUES (?, ?, 2)";
$stmt = $pdo->prepare($sql);
$stmt->execute($first_query_data);
$sql = "INSERT INTO huisarts (voornaam, achternaam, email, straatnaam, huisnummer, postcode, plaats, telefoonnummer, uid, rol_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, LAST_INSERT_ID(), 2);";
$stmt = $pdo->prepare($sql);
$stmt->execute($second_query_data);


text:
Q: Oracle Case Statement when x is null then else returns null I have written a simple case statement as below:
case when col_name is null then 'NO' else 'YES' end as col_name

But I'm still getting (null) instead of a 'NO' ? Any ideas?
I have tried following still no luck:
case when isnull(col_name, 0) = 0 then 'NO' else 'YES' end as col_name

I have also tried this:
case when nvl(col_name, 0) = 0 then 'NO' else 'YES' end end as col_name

I know that NULL is never equal to NULL - NULL is the absence of a value. NULL is also never not equal to NULL.

Whole query looks something like this:
Select

t1.col_a,
t1.col_b,
t1.col_c,
.
.
t2.col_a
t2.col_b

from table_1 t1
 left join table_2 t2
  on t1.col_a = t2.col_a

 left join
 (select distinct

  case when t3.col_name is null then 'NO' else 'YES' end as col_name,
  t3.col_a,
  t3.col_b,
  t3.col_c) ABC

on abc.col_a = t2.col_a

A: The LEFT JOIN is returning NULL, not the CASE.  Return the column name and do the case logic in the outermost query:
select . . . ,
       (case when t2.column_name is null then 'NO' else 'YES' end)