text:
Q: Create JSONObject inside JSONObject to post the data I would like to create below JSON for the post in the body. I would like to build this JSON using the native class.
[
  {
    "message": {
      "data": "E-Stop Off"
    },
    "platform": "ros",
    "topic": "/android_app/nav_control",
    "type": "std_msgs/String",
    "expiration_secs": 1

  }
]

I am using this method more often with few changes that is why I pass the argument in the method. I am not able to add JSONObject inside JSONObject. Here is my effort.
 public String postCommandJSON(JSONObject jsonObject, String topic, String type) {

        JSONArray jsonArray = new JSONArray();
        try {
            JSONObject mainObject = new JSONObject();

            mainObject.put("platform", "ros");
            mainObject.put("topic", topic);
            mainObject.put("type", type);
            mainObject.put("expiration_secs", 1);

            mainObject.put(jsonObject);
            jsonArray.put(mainObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jsonArray.toString();
    }

I am not able to add JSONObject inside JSONObject in below line.

mainObject.put(jsonObject);

Thank you

A: Assuming that at mainObject.put(jsonObject); you attempt to crate something along
{
    "message": {
      "data": "E-Stop Off"
    }
    ...
}

then beside value (which will be JSON object) you also need to pass to put method a key via which we will later be able to access that value.
So you probably want to change that line into
mainObject.put("message", jsonObject);

and maybe even execute it before mainObject.put("platform", "ros"); if order of elements is important.


text:
Q: Can't run a python program in terminal? [Mac OSX] I'm trying to execute a python program from Terminal but it isn't working.
Something like:
x = 5

Then typing:
UserName:Documents UserName$ python simple.py

Outputs:
UserName:Documents UserName$

Without actually executing/opening the file.
But if I have a program like:
x = input('Something: ')

Then it shows up in terminal, such as:
UserName:Documents UserName$ python simple.py

Something:

Probably a silly question, but been trying to fix it for the last 1.5 hours and can't find a workable solution.

A: It looks like it is working exactly as written... but maybe not as intended... The input prompt asks you to enter a value...
maybe you want to add a print so that you get a feedback that your program does something:
x = input('Something: ')
print(x)

if you are using python 2.x:
x = raw_input('Something: ')
print x

Then, on the prompt, input a value and press enter

A: The short program
x = 5

gets run and then Python exits back to the command line. No problem there, it all works correctly. If you want to stay inside the interpreter, start your program with
python -i simple.py

When running that, you will get the usual interpreter prompt after it is finished:
>>>

and you can see it did run, because x got the expected value:
>>> x
5
>>> x*x*x*x/(x+x+x-x/x)-x/x-x/x
42

Also, from inside the interpreter, you can load-and-run your file again:
>>> execfile('simple.py')
>>> x
5

See Bojan Nikolic's Running Python Programs from the Command-line for a number of other startup options.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Type of enum values I can obtain a type representing the keys of an interface with:
interface I { a: string; b: string; }
const i: keyof I; // typeof i is "a" | "b"

Is there a way to similarly obtain a type representing the values of an enum?
enum E { A = "a", B = "b" }
const e: ?; // typeof e is "a" | "b"

A: The list of values of an enum can be infered as a type with some help of the template literal operator:
enum E { A = "a", B = "b" }

type EValue = `${E}`
// => type EValue = "a" | "b"

const value: EValue = "a" // => ✅ Valid
const valid: EValue = "b" // => ✅ Valid
const valid: EValue = "" // =>  Invalid

Reference article: Get the values of an enum dynamically
(disclaimer: author here)

A: enum E { A = "a", B = "b" }
const e: keyof typeof E;

Playground example

A: In fact, the name of the enum is, itself, an alias for the union of its values' types. The following code demonstrates:
enum WaterType {
    Lake  = 0,
    Ocean = 1,
    River = 2,
    Creek = 3,
};

let xxx: 0|1|2|3 = 2;
let yyy: WaterType = xxx; // OK
let zzz: 0|1|2|3 = yyy;   // OK

Enums are just a little confusing because the enum's name refers to the type (like 0|1|2|3) in some contexts, but in other contexts it refers to an object by the same name. The WaterType object is similar to this object:
const WaterTypeObject = {
    Lake  : 0 as 0,
    Ocean : 1 as 1,
    River : 2 as 2,
    Creek : 3 as 3,
};

And typeof WaterType is virtually the same as typeof WaterTypeObject:
let aaa: typeof WaterType       = WaterType;
let bbb: typeof WaterTypeObject = aaa; // OK
let ccc: typeof WaterType       = bbb; // OK

In contexts where a type is expected, WaterType means 0|1|2|3, but you can write typeof WaterType instead to get the type of the enum object:
// VS code reports: type WaterTypeString = "Lake" | "River" | "Ocean" | "Creek"
type WaterTypeString = keyof typeof WaterType;
// VS code reports:   type WaterTypeNumbers = WaterType
// which really means type WaterTypeNumbers = 0|1|2|3
type WaterTypeNumbers = (typeof WaterType)[WaterTypeString];

Just be sure not to write "keyof Enum", e.g. keyof WaterType is the same as keyof number, which is definitely not what you want.
Fun fact: keyof typeof WaterType is a lie. the keys of WaterType are actually "Lake"|"River"|"Ocean"|"Creek"|0|1|2|3 (e.g. WaterType["Creek"]==3 and WaterType[3]=="Creek".)


text:
Q: How can I catch errors in a JSON post in express.js I am creating an API in express.js where by the user posts JSON.
I've set the content type to application/json in the clients request. If I post valid JSON, all is well. However, posintg malformed JSON results in express throwing the following error...

string(370) "SyntaxError: Unexpected token }
      at Object.parse (native)
      at IncomingMessage. (/var/www/vhost/rest-v1/node/node_modules/express/node_modules/connect/lib/middleware/json.js:76:27)
      at IncomingMessage.EventEmitter.emit (events.js:92:17)
      at _stream_readable.js:910:16
      at process._tickCallback (node.js:415:13)"

How can I catch this error so that I can respond with a more meaningful error message to the user?

A: User Express's built in error handling middleware or override it with your own: http://expressjs.com/guide.html#error-handling


text:
Q: PuTTY PSFTP returning error: unknown command "´╗┐cd" HI I am running below command from my Windows server. I have got private key added so authentication wise it is fine. But when ever I am running the command getting a weird issue
psftp user@host -b FTPfile.txt

The file FTPfile.txt has only two lines.
cd /apps/scripts/batch/sln/input
put Test.txt

But I am getting error psftp: unknown command "´╗┐cd"

And I noticed any command given in the first line of the file returns a similar error.

A: The problem is that FTPfile.txt starts with a Unicode byte order mark (U+FEFF) encoded in UTF-8, which corresponds to the bytes 0xEF 0xBB 0xBF. psftp thinks those bytes are part of the command name. When it prints those bytes to the console as part of the error message, they're interpreted according to code page 850, which makes it look like ´╗┐.
To fix this, you need to get rid of the BOM. How did you create FTPfile.txt? Windows text editors usually have a setting to change the encoding of a file to "ANSI" (plain ASCII would also work).


text:
Q: How to configure a distributed hashtable on Kubernetes? My application is running in Kubernetes pods and I would like to use golang/groupcache to distribute key/value entities amongst instances of the app.
The groupcache library in each of my app instances is required to know the connection details (IP & port) of all the other app instances so it can distribute the key/value entities as it sees fit. How can I let groupcache know the connection details of the other running instances of my application? Would it be preferable/possible to use the Kubernetes Go Client Library?

A: Go Client Library is one of the options. Another (more simple) option is to setup a headless service for groupcache, so with a single DNS lookup you can get all IP addresses of all groupcache pods.


text:
Q: Process flow gets stuck on table creations I'm trying to understand the Enterprise Guide process flow. As I understand it, the process flow is supposed to make it easy to run related steps in the order they need to be run to make a dependent action able to run and be up to date somewhere later in the flow.
Given that understanding, I'm getting stuck trying to make the process flow work in cases where the temporary data is purged. I'm warned when closing Enterprise Guide that the project has references to temporary data which must be the tables I created. That should be fine, the data is on the SAS server and I wrote code to import that data into SAS.
I would expect that the data can be regenerated when I try run an analysis that depends on that data again later, but instead I'm getting an error indicating that the input data does not exist. If I then run the code to import the data and/or join tables in each necessary place, the process flow seems to work as expected.
See the flow that I'm working with below:

I'm sure I must be missing something. Imagine I want to rerun the rightmost linear regression. Is there a way to make the process flow import the data without doing so manually for each individual table creation the first time round?

A: The general answer to your question is probably that you can't really do what you're wanting directly, but you can do it indirectly.
A process flow (of which you can have many per project, don't forget) is a single set of programs/tasks/etc. that you intend to run as a group.  Typically, you will run whole process flows at once, rather than just individual pieces.  If you have a point that you want to pause, look at things, then continue, then you have a few choices.
One is to have a process flow that goes to that point, then a second process flow that starts from that point.  You can even take your 'import data' steps out of the process flow entirely, make an 'import data' process flow, always run that first, then run the other process flows individually as you need them.  In fact, if you use the AUTOEXEC process flow, you could have the import data steps run whenever you open the project, and imported data ready and waiting for you.
A second is to use the UI and control+click or drag a box to select on the process flow to select a group of programs to run; select the first five, say, then run them, then select 'run branch from program...' option to run from that point on.  You could also make separate 'branches' and run just the one branch at a time, making each branch dependent on the input streams.
A third option would be to have different starting points for different analysis tasks, and have the import data bit be after that starting point.  It could be common to the starting points, and use macro variables and conditional execution to go different directions.  For example, you could have a macro variable set in the first program that says which analysis program you're running, then the conditional from the last import step (which are in sequence, not in parallel like you have them) send you off to whatever analysis task the macro variable says. You could also have macro variables that indicate whether an import has been run once already in the current session that then would tell you not to rerun it via conditional steps.
Unfortunately, though, there's no direct way to run something and say 'run this and all of its dependencies', though.


text:
Q: How can I, in effect, call a controller from a controller in Rails? Ok, ok, on the surface this seems like a very bad idea, and most of the time it is.  It is not MVC, it creates potential weird dependencies, and it does not follow good logical separation of concerns.
Now let me explain the situation that has led me to ask this question.  We have a third party api.  We necessarily have to cache it for long periods of time for performance reasons.  Sometimes they change their data, and we need reflect it immediately.  We have given them an api endpoint to clear the cache (as we are not going to give them access to our internal cache, for a variety of reasons).  I need some way to rewarm the cache.  Rewarming their api call is easy.  However, we have view fragment caches that are dependent on that data, and I would like to rewarm those as well.
Basically I would like to cache everything that would normally be cached during a call on this second controller.  However, trying this results in timeouts on the second controller call.  Is there a way to accomplish this, or an alternate method that will result in all necessary elements (including view elements that use rails fragment caching) to be cached?

A: It seems like your real problem is busting the fragment caches. Why not just use a self busting cache key. If you're caching a piece of the view with cache 'key' do... that "key" string could be updated by a model or something such as the Post.count or something. For example, in an API controller caching a list of Posts as a JSON list:
# your api controller's index action
@post_json = Rails.cache.fetch "posts-#{Post.count}-#{Post.order(:updated_at).last.updated_at}" do
  Post.all.to_json
end

Now that you have a collection of posts cached and ready to be sent as an API response and you're using a self busting cache key you won't have to worry about manually "rewarming" your cache. Whenever a new Post is created or one is updated the cache key will be different because the count and updated_at (for the most recently updated post) will be different and cause the Rails.cache.fetch method to execute the block, rewarming your cache.
With this sort of dynamic cache key you can use any method to update it that doesn't require calling a controller (which is very hard and not recommended).

A: To get around the problem of Rails maintaining a single connection, you can use a multi-threaded approach:
Thread.new do
    # do stuff here
end


text:
Q: Responsive breakpoints not working for slick slider I have implemented slick slider which works fine without resizing the browser. But when I resize the browser to 1024 then the responsive breakpoint settings doesn't work.
jQuery:
$('.slider').slick({
  centerMode: true,
  slidesToShow: 1,
  slidesToScroll: 1,
  dots: true,
  infinite: true,
  cssEase: 'linear',
  variableWidth: true,
  variableHeight: true,
  mobileFirst: true,
  responsive: [{
    breakpoint: 1024,
    settings: {
      slidesToShow: 4,
      slidesToScroll: 1,
      centerMode: false
    }
  }]
});

Demo -- https://jsfiddle.net/squidraj/hn7xsa4y/4/

A: Add this settings to your code;
$(".slides").slick({
    autoplay:true,
    mobileFirst:true,//add this one
}

A: Add slidesToShow and slidesToScroll option in each breakpoint.
 {
  breakpoint: 786,
    settings: {
              slidesToShow: 3,
              slidesToScroll: 1,
              }
 },
 {
  breakpoint: 568,
    settings: {
              slidesToShow: 2,
              slidesToScroll: 1
            }
  }

A: First of all, "variableHeight" option does not exist in Slick Carousel.
To solve your issue, remove variableWidth: true, because this will make your slides take full with of the carousel.
And you can also not use "mobileFirst" option if your page is not using this methodology.
So finally your config should be like this, below
$('.slider').slick({
  centerMode: true,
  slidesToShow: 1,
  slidesToScroll: 1,
  dots: true,
  infinite: true,
  cssEase: 'linear',
  mobileFirst: true, //optional, to be used only if your page is mobile first
  responsive: [{
    breakpoint: 1024,
    settings: {
      slidesToShow: 4,
      slidesToScroll: 1,
      centerMode: false,
    }
  }]
});

Best Regards.

A: This did the trick for me.
    function resetSlick($slick_slider, settings) {
            $(window).on('resize', function() {
                if ($(window).width() < 320) {
                    if ($slick_slider.hasClass('slick-initialized')) {
                        $slick_slider.slick('unslick');
                    }
                    return
                }

                if (!$slick_slider.hasClass('slick-initialized')) {
                    return $slick_slider.slick(settings);
                }
            });
        }

 slick_slider = $('.client-logos');
    settings = {
        slidesToShow: 6,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 2000,
        prevArrow: '',
        nextArrow: '',
        pauseOnHover: true,

        responsive: [
            {
                breakpoint: 1024,
                settings: {
                    slidesToShow: 5,
                    slidesToScroll: 1,
                }
            },
            {
                breakpoint: 600,
                settings: {
                    slidesToShow: 3,
                    slidesToScroll: 1
                }
            },
            {
                breakpoint: 480,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 1
                }
            }
            // You can unslick at a given breakpoint now by adding:
            // settings: "unslick"
            // instead of a settings object
        ]

    };
     slick_slider = $('.container');
    settings = {
        slidesToShow: 6,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 2000,
        prevArrow: '',
        nextArrow: '',
        pauseOnHover: true,

        responsive: [
            {
                breakpoint: 1024,
                settings: {
                    slidesToShow: 5,
                    slidesToScroll: 1,
                }
            },
            {
                breakpoint: 600,
                settings: {
                    slidesToShow: 3,
                    slidesToScroll: 1
                }
            },
            {
                breakpoint: 480,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 1
                }
            }
            // You can unslick at a given breakpoint now by adding:
            // settings: "unslick"
            // instead of a settings object
        ]

    };
    slick_slider.slick(settings);
    resetSlick(slick_slider, settings);

Add this to your js and call the slider as shown.
and in your css make the slide display: inline-block; that's it. will work on all responsive screens.

A: tl;dr When multiple sliders on page changing $('.selector').slick({...}) order helped
I had similar issue. I don't understand why but slidesToShow: 2 didn't take effect on mobile device for me although if you resize it back and forth it took effect. mobileFirst:true helped but broke desktop. Adding both slidesToShow and slidesToScroll didn't help. But when I placed initialization of sliders in the same order as they appear on the page it worked. I don't understand why... I don't understand how to fix this if there're multiple pages with different slider locations...

A: First, you use old version of slick in your example. This verson doesn't support mobileFirst property.
Second, you must remove variableWidth if you want to use slidesToShow property.

A: I am not sure why your js template is failing with below:
 responsive: [{
    breakpoint: 1024,

I would follow up with their documentation, community, or file a bug.
In any case it is better practice to use CSS3 media queries for this. One approach; nest a div around the slider and position it relative, scale it and it's child elements with width: 100%; and declaring max and min width's within defined resolutions. This should start you in the right direction. Make sure to also make proper use of meta viewport.

A: mobileFirst:true,//add this to your JavaScript file and it should work :)


text:
Q: Exchange Server 2003 - delete meeting invitations (appointments) after deleting meeting I use the IndependentSoft Component and was wondering in what way (with this component or any other API) I could mimic what I can also do manually:
After creating a meeting request and invite some Account B, I delete the meeting created by me, which leaves the appointments of the invited intact. I can now (given high enough access level to calendar of other account, I think it's level 6) delete this appointment manually, and that's what the customer wants.
Now, I can't seem to use IndependentSoft component for this, as I would need a mailbox for getting the appointment, but I lack the mailbox rights to do so, and I don't see any other way to get the address of the appointment (?).

A: It is poor etiquette to cancel a meeting without notifying the users that were invited. You are better off following best practices and just sending a meeting cancellation notification.
View IndependentSoft documentation on how to cancel a meeting.

Since you do need to delete the appointment - you need an account that has been delegated to manipulate another users account to delete an appointment. I'd recommend you use the EWS Managed API and perform a delete appointment action.
Appointment appointment = Appointment.Bind(service, new ItemId("AAMkA="));
appointment.Delete(DeleteMode.MoveToDeletedItems);

A: I found the answer.. and it wasn't hard at all, I was just smitten with blindness.
So the IndependentSoft resource.GetAppointments has an overload which takes just an address, so you just take your mailbox.Calendar address (e.g. "http://sub.exchangedomain.com/emailalias/calendar"), switch out your emailalias with the one you want to access (e.g. "http://sub.exchangedomain.com/otheremailalias/calendar"), and that's it.. with standard security settings, you can now see calendar entries of this account on an exchange 2003 server. Now, if you want to delete an appointment, you just use resource.Delete(appointment) on any of the appointments you got. The account has to give you rights to do so, of course.
Sometimes it's that simple, you just don't see/ignore/misunderstand a simple signature.


text:
Q: object oriented matrix multiplication using multithreading I am in need of designing a multi-threaded matrix multiplication using OO principles. Below is the outline of the classes i came up with.
class matrix{

}

class matrixThread implements runnable{

}

the matrix class will hold the actual matrix. In this application there needs to be 3 matrices so i have to create three of them. And i need to multiply them using 4 threads.So i create 4 matrixThread  objects and invoke the .start method with the actual matrix multiplication code inside the run method.
Could someone please comment on my approach. Is there a better way of doing this ?

A: Your approach should be to copy a solution which works already. Matrix multiplication is a well understood problem and getting the best performance (which makes using multiple threads worth doing) is a bit tricky and you will save yourself some grief by just using an existing solution.  If you just try something which should work, you can find it is slower than using one thread if you do not test  carefully. (As you need to be careful as to the number of threads you create and how the caches are used)


text:
Q: How can I store an arraylist of custom objects? I have created an arraylist that is made up of custom objects. Basically the user will create a class and every time a class is created, a new Lecture (my custom object) is added to the arraylist. I need to save the generated arraylist so the user's classes will be saved even when the app is restarted.
From my understanding, I have to make my class serializable. But how exactly do I do that? And then once its serialized what do I do?
public class Lecture{

public String title;
public String startTime;
public String endTime;
public String day;
public boolean classEnabled;

public Lecture(String title, String startTime, String endTime, String day, boolean enable){
    this.title = title;
    this.startTime = startTime;
    this.endTime = endTime;
    this.day = day;
    this.classEnabled = enable;
}
//Getters and setters below

A: I use a class in a Weather app I'm developing...
public class RegionList extends ArrayList<Region> {} // Region implements Serializeable

To save I use code like this...
FileOutputStream outStream = new FileOutputStream(Weather.WeatherDir + "/RegionList.dat");
ObjectOutputStream objectOutStream = new ObjectOutputStream(outStream);
objectOutStream.writeInt(uk_weather_regions.size()); // Save size first
for(Region r:uk_weather_regions)
    objectOutStream.writeObject(r);
objectOutStream.close();

NOTE: Before I write the Region objects, I write an int to save the 'size' of the list.
When I read back I do this...
FileInputStream inStream = new FileInputStream(f);
ObjectInputStream objectInStream = new ObjectInputStream(inStream);
int count = objectInStream.readInt(); // Get the number of regions
RegionList rl = new RegionList();
for (int c=0; c < count; c++)
    rl.add((Region) objectInStream.readObject());
objectInStream.close();

A: You're in luck, all of your class' members are already serialzble so your first step is to say that Lecture is Serializable.
public class Lecture implements Serializable {

    public String title;
    public String startTime;
    public String endTime;
    public String day;
    public boolean classEnabled;

    public Lecture(String title, String startTime, String endTime, String day, boolean enable){
        this.title = title;
        this.startTime = startTime;
        this.endTime = endTime;
        this.day = day;
        this.classEnabled = enable;
    }

Next, you need to make a default constructor since serialization seems to require that. The last thing is you need to write your object out to a file. I usually use something like the following. Note this is for saving a game state so you might not want to use the cache directory.
private void saveState() {
    final File cache_dir = this.getCacheDir();
    final File suspend_f = new File(cache_dir.getAbsoluteFile() + File.separator + SUSPEND_FILE);

    FileOutputStream   fos  = null;
    ObjectOutputStream oos  = null;
    boolean            keep = true;

    try {
        fos = new FileOutputStream(suspend_f);
        oos = new ObjectOutputStream(fos);

        oos.writeObject(this.gameState);
    }
    catch (Exception e) {
        keep = false;
        Log.e("MyAppName", "failed to suspend", e);
    }
    finally {
        try {
            if (oos != null)   oos.close();
            if (fos != null)   fos.close();
            if (keep == false) suspend_f.delete();
        }
        catch (Exception e) { /* do nothing */ }
    }
}

Reading the data back is pretty symmetric to the write so I have left that out for this answer. Also, there are still a lot of caveats to Serialized objects so I suggest you do some Google searches and read up on Java serialization in general.

A: You can use:
System.Runtime.Serialization

You can see an example here:
Serialization in C#


text:
Q: How can I tidy the outcome of paste function? (R) I have list which have this structure
ex1.
[[1]]
[1]"blah blah~"

ex2.
[[1]]
[1]"blah blah~~~"
[2]"fmlafmlaf~~"

ex3.
[[1]]
[1]"blaaaa~"

When I use paste function, ex1, ex3 make the outcome tidy. like below.
[[1]]
[1]"~~~sth"

However, In example 2, it has 2 components in one big list and the outcome of paste function is sth like dirty. I mean
[[1]]
[1] "c(\ "blah blah~~~" ...

So suddenly "c(\ ..~ , \n" appears and make my outcome dirty.
Even more, sometimes the paste function didn't work and the components didn't mixed.
What should I do?

A: Don't use paste directly since you have a list use sapply
sapply(list_ex, paste0, collapse = "")

A: If the purpose is to paste all examples into a large string then you can use unlist:
ex1 <- "blah blah~"
ex2 <- c("blah blah~", "blah ~ .... ~~~~")
list_ex <- list(ex1,ex2)

paste0(unlist(list_ex), collapse = " ")
[1] "blah blah~ blah blah~ blah ~ .... ~~~~"

A: An option with map
library(stringr)
library(purrr)
map_chr(list_ex, str_c, collapse="")


text:
Q: Restarting Activity doesnt kill old activity entirely? Every time my app enters pAUSE stage and enters  onresumestage, i am  killing my current activity and start new Acitivy. And at the same time in onresume stage, i try to make some button visible. Some how the visibility function never gets updated. Always stays at defualt invisible stage...   any help highly appreciated. ..
// code in onresume stage that makes button ready visible and at the same time call refresh function
public void onResume() {
        super.onResume();
        refresh();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ImageButton ready = (ImageButton) findViewById(R.id.ready);
                    ready.setVisibility(View.VISIBLE);
                }
            });

      }

// thats where i am killing current activity and starting new activity
public void refresh() {

    Intent intent = getIntent();
    overridePendingTransition(0, 0);
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
   // MediaPresentationActivity.this.finish();

    finish();
    recreate();
    overridePendingTransition(0, 0);
    startActivity(intent);
}

// xml image button set default visibility to invisible
 <ImageButton
        android:id="@+id/ready"
        android:layout_width="90dp"
        android:layout_height="90dp"

        android:visibility="invisible"

         />

A: From the best of my knowledge , refreshing activity kill the current activity. Only issue could be onResume function. You should try java Synchronous function. Currently setvisbility for image button is executed before finishing the refresh function . Actually it does set image button to visible, but refresh function will delete it as both run at the same time. so you should try Synchronous function : which allow second function to call ,only after first function is executed completely.

A: what simply you can do is calling the same activity again like
Intent intent=new Intent(MainActivity.this,MainActivity.class);
startActivity(intent);
finish();

Note: Replace MainActivity with your own class name.


text:
Q: Angular override global ErrorHandler We use a global error handler in our project. The problem is that we got a special case now that we would like to handle separately but we cannot. The global error handler is basically provided in the app.module.ts:
{ provide: ErrorHandler, useClass: GlobalErrorHandler },

We divide between the errors and then handle them with a service.
  handleError(error: any): void {
    const errorService = this.injector.get(ErrorService);
    const notifier = this.injector.get(NotificationService);

    let message: string;

    if (error instanceof HttpErrorResponse) {
      message = errorService.getServerErrorMessage(error);
      notifier.showError(message);
    } else if (error === undefined) {
      message = errorService.getServerErrorMessage(error);
      notifier.showError(message);
    } else if (error instanceof Observable) {
      message = this.translate.instant('ERROR.SERVER_NOT_REACHABLE');
      notifier.showError(message);
    } else {
      message = errorService.getClientErrorMessage(error);
      notifier.showError(message);
    }

    this.logger.error(message, `\n - Stacktrace: \n${error.stack}`);
  }

The problem now is that we know for some application that if status code 406 is returned for that special call it means that AWS couldn't recognize a face. We would like to return this translated message and try to add an if-clause after the subscribe() of the function that calls the backend API.
  (err) => {
    if (err.statusCode == 406) {
      this.notifier.showError(
        this.translate.instant(
          'APPLICATIONS.FACE_DETECTION.NOTIFICATION.FACE_ERROR'
        )
      );
    }
  }

Instead of achieving anything like this we just get the error message of the backend (that's the right behaviour because we tell to do this in the ErrorHandlerService but how to override or to tell that it should not care for that special call?

A: Create a model for AWS response and in your first clause of your error handler check if that your http code is 406 and the http response has x props to make sure it's AWS response.
if (typeof e.error === 'object' && (e.error as
AWSError)?.errorCode) {
      const awsError = e.error as AWSError;
}
...
console.log(awsError.errorMessage)

A: Have you tried catching it in the pipe of the http request using catchError?
.pipe(
  catchError(err => {
     if (err instanceof HttpErrorResponse && err.status == 406) {
       // handle error
     }
  }).subscribe(res => ...)


text:
Q: variable is undefined, yet clearly defined in my constructor C++ I have a C++ assignment that requires me to create a class called Tips, that:

*

*has a single member variable, float taxRate

*has two constructors, a default that sets taxRate to .65, and a one parameter constructor, that sets taxRate to whatever float the user enters in my tipMain.cpp file.

*has only one function, computeTip, that accepts two arguments: totBill and tipRate, both floats that must calculate the before-tax meal cost, and return the tip based on that value and the desired tip rate.

My issue occurs when I attempt to use taxRate inside the computeTip function.
If I use taxRate, computeTip doesn't understand the value of taxRate, stating it is undefined, and even if I do specify tips::taxRate, before I even compile Visual Studio states

Error: a nonstatic member reference must be relative to a specific object.

I vaguely understand this error, but even if I declare taxRate to be static in my .h file, I get LNK2019 errors.
Tips.cpp
#include <iostream>
#include <float.h>
#include "Tips.h"

using namespace std;

Tips::Tips()
{
    taxRate = 0.65;
}

Tips::Tips(float a)
{
    taxRate = a;
}

float computeTip(float totBill, float tipRate)
{
    float mealOnly = 0;
    mealOnly = (totBill/taxRate);       //written both ways to show errors. taxRate undefined here.
    mealOnly = (totBill/Tips::taxRate); //Error: a nonstatic member reference must be relative to a specific object
    return (mealOnly * tipRate);

}

Tips.h
#ifndef Tips_H
#define Tips_H
#include <float.h>

using namespace std;

class Tips
{
public:
    Tips();
    Tips(float);
    float computeTip(float, float, float);
    float taxRate;
};
#endif

and my tipMain.cpp
#include "Tips.h"
#include <iostream>
#include <iomanip>

using namespace std;

float tax;
float meal;
float tip;
void tipProcessor();

int main()
{
    char entry;
    int toggle = 1;
    cout << "Welcome to the Gratuity Calculator!" << endl;
    cout << endl;
    while (toggle != 0)
    {
        cout << "Enter 1 to calculate tip." << endl;
        cout << endl;
        cout << "Enter 2 to exit." << endl;
        cout << endl;
        cout << "Entry: ";
        cin >> entry;
        switch (entry)
        {
        case '1':
            tipProcessor();
            break;
        case '2':
            toggle = 0;
            break;
        default:
            cout << "Enter 1 or 2." << endl;
            cout << endl;
            break;
        }
    }
    system("pause");
    return 0;
}
void tipProcessor()
{
    cout << "Enter bill total: ";
    cin >> meal;
    cout << endl;
    cout << "Enter tax rate: ";
    cin >> tax;
    cout << endl;
    Tips thisTip(tax);
    cout << "Enter tip percent: ";
    cin >> tip;
    cout << endl;
    cout << "Tip is $" << setprecision(4) << thisTip.computeTip(meal, tip, thisTip.taxRate) << "." << endl;
    cout << endl;
}

A: You use
float computeTip(float totBill, float tipRate)

But it should be:
float Tips::computeTip(float totBill, float tipRate)

in the implementation. Also you should hide your data members.

A: You are defining computeTip() as global function, therefore only public static member access is possible.  Define as float Tips::computeTip(float ...) and it should compile.

A: You've not specified that computeTip is a method of Tips. Change it to this:
float Tips::computeTip(float totBill, float tipRate)
{
    float mealOnly = 0;
    mealOnly = (totBill/taxRate);
    return (mealOnly * tipRate);
}

And all should be well.

A: Your method declaration and and method definition do not have the same signature. In your header file you indicate that computeTip should take 3 float arguments, but when you define it in the .cpp file, it only takes two arguments.
This is in addition to what other users suggest, prefixing your function with Tips:: to indicate that it is part of the Tips class and thus should be able to access member variables such as taxRate.
Thus your header declaration should look like:
float computeTips(float, float);

And your method definition should look like
float Tips::computeTip(float totBill, float tipRate)
{
...


text:
Q: List contents of tarball in tree format Per the answers here I'm able to list the contents of my tarball in ls format. However, I'd like to be able to list them in tree format, i.e. something like the latter instead of the former:
With tar:
$ tar -tf foo.tar
foo/
foo/baz/
foo/baz/qux/
foo/baz/qux/hisfile.txt
foo/bar/
foo/bar/myfile.txt
foo/bar/yourfile.txt

With tree:
$ tree foo
foo
├── bar
│   ├── myfile.txt
│   └── yourfile.txt
└── baz
    └── qux
        └── hisfile.txt

Is it possible to do this without extracting the tarball? I'd prefer to have to avoid extracting the tarball due to their size.

A: This is just an addendum to user1686's answer though I do not have enough reputation to comment. While his scripts certainly do the job well they need to be downloaded while tree can actually do this natively:
$ tar tf foo.tar | tree --fromfile .
.
└── foo
    ├── bar
    │   ├── myfile.txt
    │   └── yourfile.txt
    └── baz
        └── qux
            └── hisfile.txt

4 directories, 3 files

Note that unlike most tools tree uses a dot . and not a dash - to read input from stdin:
INPUT OPTIONS
    --fromfile
        Reads a directory listing from a file rather than the file-system.
        Paths provided on the command line are files to read from rather than directories to search.
        The dot (.) directory indicates that tree should read paths from standard input.

This allows one to use the typical tree functions like wildcards though sizes obviously cannot be shown and the level argument (-L) apparently also does not work...

A: Several scripts exist for converting a list of path names into tree form:

*

*my own treeify.pl

*treeify.rs by Loïc Damien

*treeify.py by Hakril

All these scripts work with tar -tf … output; for example:

$ tar -tf foo.tar | treeify
foo
 ├─bar
 │  ├─myfile.txt
 │  └─yourfile.txt
 └─baz
    └─qux
       └─hisfile.txt

Also:
$ bsdtar -tf foo.zip | treeify
$ find /dir -size +5 | treeify
$ git ls-files       | treeify
$ pacman -Qql foopkg | treeify
$ unrar vb foo.rar   | treeify
$ zipinfo -1 foo.zip | treeify
$ gsettings list-schemas   | treeify -s. -f
$ qdbus | sed -n "s/^ //p" | treeify -s. -f
$ ldns-walk netbsd.org | awk '{print $1}' | treeify -s. -f -R


text:
Q: TS configuration for safe array access In this code
const arr = ['hello', 'world'];
const x = arr[2];
const y = arr[0.5];

arr is a string[], and 10 and 0.5 are numbers, so TS implies that 10 and 0.5 can index arr, therefore inferring that x and y are strings too, while at runtime they'll be undefined.
Is there a configuration option I can write in my tsconfig.json that basically tells typescript "if you're not sure that arr: T[] has an element at i, do not infer that arr[i] is a T"?

A: TypeScript 4.1 introduced support for checked indexed accesses, which can be enabled via the --noUncheckedIndexedAccess compiler option.  If you turn that on, you get this behavior:
const arr = ['hello', 'world'];
const x = arr[10] // number | undefined
console.log(x.toUpperCase()) // compiler error
//          ~ <-- object is possibly undefined

console.log(x?.toUpperCase()) // okay

which is what you're looking for.  This option is not included in the --strict suite of type checking features, because it can make the compiler complain even for code which is generally considered safe:
for (let i = 0; i < arr.length; i++) {
    console.log(arr[i].toUpperCase()) // error!
    // -------> ~~~~~~
    // arr[i] is possibly undefined
}

So you'll have to decide if your desired behavior is worth the possible false warnings from the type checker, and if so, turn on --noUncheckedIndexedAccess explicitly.
Playground link to code


text:
Q: Disable iphone scaling/resize on hide/show address bar? I'm working on a special site which is quite "stupid". It's supposed to be very flashy with a lots of animations, and on this be responsive. The body element is set to overflow: hidden; and the scruture looks something like this:

 Some content with down button goes here ...

 Some content with up/down button goes here ...

 Some content with up/down button goes here ...

 Some content with up button goes here ...

each .content has a up/down navigation button which will scroll you to each div. These are full width and height and if the content is "too big" the div itself is scrollable. That is, you "can't" scroll to next content by just keep scrolling - you have to use the navigation to go to next div.
Since resizing alters the content, the alignment of .content can crash. That is, two content-divs can be visible (like 80% of #1 and 20% of #2. There fore i have a function which "restes" the page and gets you to the top (.content #1) on resize.
This works fine on desktops (and in chrome on android) but then there's iOS and safari. The adress bar is visible, and the classic window.scrollTo(0,0); (or window.scrollTo(0,1);) wont work. fine. i can live with that. But, in some cases, when you scroll in the content, safari just can think "hey, let's hide the address bar now" (i have not really figured out how this logic is) and this is seen as a rezise which brings you to the top.
So, is there any smart way of always keeping the address bar visible, or for that matter always hide it?
Or any other ideas to solve this issue?

A: I had the same issue with Chrome Mobile. When I scrolled, the address bar disappeared making the window resize event fire.
The solution was to block the resize event while the scroll event is active.
https://stackoverflow.com/a/31546432/1612318

A: No, it is not possible to keep the address bar visible in iOS 8 (and 7 probably) when the user scrolls.


text:
Q: Google Map not show by using Angualrjs I am trying to use AngularJS to make a simple Google Map app.
I am not using Google APIs like "ngMaps" or "Angular-ui".
I have everything in very basic structure, and I can show see my google map object in the console, the problem is that nothing shows on the page
home.html:

app.js:
var app = angular.module('locator',['ngRoute', 'ngMaps']);

app.config(['$routeProvider', '$locationProvider', '$httpProvider',
function ($routeProvider, $locationProvider, $httpProvider){
    'use strict';

    $routeProvider
        .when('/', {
            templateUrl: './partials/home.html',
            controller: 'masterCtrl'
        })
        .otherwise({
            redirectTo: '/'
        });
}]);

masterCtrl:
app
 .controller('masterCtrl', ['$scope', '$window', masterCtrl]);

function masterCtrl($scope, $window) {
 function initialize() {
  var lat = 46.87916;
  var lng = -3.32910;
  var map_id = '#map';

  var myOptions = {
   zoom : 8,
   center : new google.maps.LatLng(lat, lng),
   mapTypeId : google.maps.MapTypeId.ROADMAP
  };
  $scope.map = new google.maps.Map($(map_id)[0], myOptions);
 }
  initialize();

}

A: The problem was solved, all I need to do is to add a "ng-init" to callback my initialize() function, which would initialize the map on the page.


text:
Q: Segmentation fault when running a simple nasm program on manjaro i'am trying to make a simple NASM program on Linux Manjaro 20.2, the code:
section .data
global _start

_start:
mov rax, 60
mov rdi, 0
syscall

and build it up with
nasm -f elf64 test.asm
ld -o test.out test.o
./test.out

but no matter what, it always outputs Segmentation fault.
On the other side, i tried it up on Linux Mint Ulyssa and the program exits perfectly.


text:
Q: Get amount of likes Facebook I always used this URL(https://graph.facebook.com/[PAGE-ID]) via JavaScript to get the amount of likes, but now I get an error:

"An access token is required to request this resource."

*

*Is there another possibility to get the likes without an token?

*Can I set my access token directly into the request (security)? Is the token a secret token?

A: I've found a solution to get it without a token. I can use the following URL:
https://api.facebook.com/method/fql.query?query=select%20fan_count%20from%20page%20where%20page_id=[PAGEID]&format=json

A: *

*No, you have to use a Token. But you can use an App Access Token that does not require authorization.

*You should always keep any Token secret, only use it on the server.

A: You cannot get it without token. Read more about how to generate tokens here


text:
Q: Entity Framework Update statement generating invalid SQL for Firebird I'm using Firebird 2.5.0 with the Entity Framework, which has been working well. However, recently I have changed something (I presume) and now the SQL that is being generated when I try to save my changes is not valid for Firebird:
update ( select [fields] from [table]) set [field] = @p0 where ([keyfieldn = @pn])

As far as I know, Firebird 2.5.0 does not support this syntax, and when I try to save changes I get back a SQL error that says as much ( "Token unknown, column 8: (" )
I'm not sure what to do now. What would cause the UpdateTranslator instance to generate this SQL instead of whatever it must have been generating before I broke it?

A: I went back through the edmx file and found that I had gotten some 'DefiningQuery' elements when I had it pull in some new fields from the database. I couldn't find any way to access those settings in the interface, so I just deleted them from the file and it is working correctly again.


text:
Q: From website to app to website on iOS I'm working on an iOS app some people want to link to from their website.
While I've managed to open my app from a webpage using schemes, I wonder if, when I'm done with what I have to do in my app, I can switch back to the original website tab in safari.
To my knowledge : it is pretty straightforward to open a new page in safari from my app but I don't know if it is possible to get back to the actual original page, just like the ios9 back-to-app button would do.
I could open a new page and close it straight away with some javascript, which would probably display the original page because it's the next one in the tab list... but it doesn't feel right (does it?)
I read stuff about ios9 deep linking, still can't find anything interesting.

A: To achieve this is to open Safari using URLScheme. However, (afaik) Safari App doesn't have a url scheme. If the user came to your app from Chrome, than you can use its url scheme
Google Chrome has the following two URI schemes: googlechrome:// and googlechromes://

iOS 9's back to app button can't be invoked programmatically, so you can't use it as well. However in jailbreaked devices an app can mimic that, maybe that will help you http://theunlockr.com/2015/08/23/enable-back-button-ios-8-video/

I could open a new page and close it straight away with some
  javascript, which would probably display the original page because
  it's the next one in the tab list... but it doesn't feel right (does
  it?)

It doesn't feel right at all. Because the typical behaviour for turning back to previos (or any other) application among iOS users is pressing home button twice, and selecting the app. Maybe you can simply show a message, and ask user to return Safari.


text:
Q: Using "more" in a sentence without "than". Grammatical? If you include the word "more" in a sentence without "than" in spoken English, would it be valid? Example: a talk about steps how to resolve environmental issues.

I'll get into them in more detail later as I progress through the talk.

Some say that do not use comparative adjectives such as, more, better and so on without "than" in a sentence/clause, because it would be ungrammatical. However, in the above sentence, it sounds right. Is this an exception?

A: This sentence is completely fine. It would seem weird to squeeze some comparison in unless it isn't obvious from context.

I'll get into them in more detail (than I am now?) later as I progress through the talk.
I would like more drink (than I have now?), please.

With the than just sounds unnatural, especially in the second sentence.
I would, however, like to correct your preposition usage. While into is fine, I would use just to here:

I'll get to them in more detail later as I progress through the talk.

A: English, in practice, often drops comparators (that's not, as far as I'm aware, a grammatical term; I'm borrowing its use in various academic disciplines, public policy and so on, for "the thing to which something is to be compared). If the comparator is obvious from context, you don't need to say it - and often saying it comes across as wrong.

"Why do you think A's more attractive than B?"
"He's taller."

Obviously, this is saying that A is taller than B, but including that would be unnecessary and can make it seem strange.
Similarly, when making an argument, presenting a talk, and so on, you will often make comparisons that seem, just from the words used at that time, to be missing their comparator, but everyone knows what it means, so it's unnecessary. Adding the comparator would break the flow, and leave everyone wondering "why did they bother to say that?".
I would say the general rule is not to use "than" expressions and other comparators unless necessary. We'd get horribly bogged down if we couldn't say "I'm stronger now", which is the same grammatically as any "more" expression. "I'm stronger now than I was" is unwieldy (though occasionally preferable for aesthetic reasons), and even that is actually missing a location in time. "I'm stronger now than I was a year ago" should only be said if there's some significance to "a year ago" in the context, and in fact would often end up being shortened to "I'm stronger now than a year ago", which if you try to parse it makes no sense unless you add an unwritten "I was".
However, if you use language of comparison and the comparator isn't obvious from context, it will read as wrong.


text:
Q: Dynamic attribute in element XSD Schema It is possible to add dynamic attribute in <element>
for example I have a  element it have a fixed attribute name mode

if mode is enable then it will add some more dynamic attribute in element `<A>`

like

if mode is disable then it will like this .

That means attribute mode is fixed and attr1,attr2,attr3 and attr4 depend on values of mode attribute
mode - Fixed attribute.
attr1,attr2,attr3 and attr4 -  Dynamic attribute depend on value of mode
Please give me suitable example.

A: To allow attributes depending on the contents of other attributes you need XSD 1.1 (or some XSD 1.0 extension such as Schematron). In XSD 1.1 you can use an assertion xs:assert where you declare the rules for the complex type using XPath.
To validate this instance:
<modes>

</modes>

You can use a XSD like the one below:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
    xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1">

    <xs:element name="modes">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="A" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:attributeGroup name="enabled-attributes">
        <xs:attribute name="attr1" type="xs:string" use="optional"/>
        <xs:attribute name="attr2" type="xs:string" use="optional"/>
    </xs:attributeGroup>

    <xs:attributeGroup name="disabled-attributes">
        <xs:attribute name="attr3" type="xs:string" use="optional"/>
        <xs:attribute name="attr4" type="xs:string" use="optional"/>
    </xs:attributeGroup>

    <xs:element name="A">
        <xs:complexType>
            <xs:attributeGroup ref="disabled-attributes"/>
            <xs:attributeGroup ref="enabled-attributes"/>
            <xs:attribute name="mode" use="required">
                <xs:simpleType>
                    <xs:restriction base="xs:NMTOKEN">
                        <xs:enumeration value="ENABLE" />
                        <xs:enumeration value="DISABLE" />
                    </xs:restriction>
                </xs:simpleType>
            </xs:attribute>
            <xs:assert test="(@mode='ENABLE'  and @attr1 and @attr2 and not(@attr3) and not(@attr4))
                          or (@mode='DISABLE' and @attr3 and @attr4 and not(@attr1) and not(@attr2))"/>
        </xs:complexType>
    </xs:element>
</xs:schema>

I placed the attributes for each mode in a separate attribute group. Your mode attribute is not actually fixed but can have two values, so I used an enumeration to restrict it to those two values.
The line that requires XSD 1.1 is the xs:assert line. The XPath expression is evaluated relative to the elements in the complex type. If the expression is true, it will validate.
Validation will fail otherwise. These A nodes will both fail validation:
<modes>

</modes>

Update: I added the not() clauses above, since the assertion was incomplete as you noted. Now this validates to false:

You can also use other criteria (it's a XPath subset), such as the number of attributes, for example if you have a lot of attributes and want to avoid a lot of not() clauses you can use:
@mode='ENABLE' and @attr1 and @attr2 and count(@*) = 3

that will restrict the total number of attributes to 3.


text:
Q: Windows 10 v1803: where is OpenSSH Client? At one time I installed OpenSSH Client as an Optional Feature when running Fall Creators Update (version 1709).  I've since updated Windows to version 1803 and I no longer have OpenSSH Client installed.  How do I get it back?
My understanding is that after updating to Windows 10 version 1803 (April 2018), OpenSSH client is automatically installed. However, it's not installed and the information I've seen online for how to install OpenSSH appears to be for previous versions of Windows 10, when OpenSSH Client was in beta.
I've looked for OpenSSH under Manage optional features and do not see it listed:

From Manage optional features, I've tried selecting Add a feature to see if OpenSSH is there, and I see "No features to install.":

When I had the Fall Creators Update (version 1709) and OpenSSH was in beta, I successfully installed it using the above Manage Optional Features. I don't know why it's not installed now and I can't find it anywhere to install.
When looking at See optional feature history, I see that OpenSSH Client was installed on 4/12/18 and uninstalled on 8/10/18.  I don't recall explicitly uninstalling it, but that's the same day I installed a number of Windows updates and had to reboot a couple of times after updating.

I've also tried looking for it under the standard Windows Features (Turn Windows Features on and off) as suggested by this answer and I do not see it listed. (I've even tried expanding all of the collapsible items just to make sure it wasn't hiding under IIS or something):

I've also rebooted several times, to see if it appears as a feature to enable/install after a clean boot, but still nothing.
I've verified I'm updated to Windows 10 Pro Version 1803, OS build 17134.191.
There are no more Windows updates to install.
I still do not have an ssh client.  I see that ssh-agent.exe, ssh-add.exe, ssh-keygen.exe, and even sshd.exe (OpenSSH server!) is available under C:\Windows\Sysetm32\OpenSSH.  But no ssh.exe (OpenSSH client).
How do I install OpenSSH client on Windows 10 version 1803?
Is there a way to simply download the installation package from Microsoft and install it?

A: Answering my own question and providing additional information for anyone else looking to figure out how to get OpenSSH installed on various versions of Windows 10.

First, to explicitly answer the questions:

I've since updated Windows to version 1803 and I no longer have
  OpenSSH Client installed. How do I get it back?

This should not happen. There appears to be something wrong with this Windows system or something has modified the default installation options as others have suggested. (There are a number of reasons that may prevent Optional Features from being available. See this answer for some examples.)
I've now verified this to be true after completing a fresh install of Windows 10 version 1709 and then updating to version 1803. When updating to Windows 10 version 1803 without making any changes or installing any additional packages, OpenSSH Client was installed automatically as a result of the update.

How do I install OpenSSH client on Windows 10 version 1803?

See section below for installation on Windows 10 version 1803 (April 2018).

Is there a way to simply download the installation package from Microsoft and install it?

Yes. It's possible to download OpenSSH directly from Microsoft's Win32-OpenSSH project on GitHub.  See Alternate Installation Methods section below for details. This also makes it possible to install more recent releases of OpenSSH.

Windows 10 version 1709 (Fall Creators)
If running Windows 10 version 1709 (Fall Creators) there are two primary ways to install OpenSSH.  If you're running a version of Windows 10 older than 1709, you will want to update to a newer version of Windows 10 via Automatic Updates.  (It's also possible to use the Alternative Installation Methods listed below on older versions of Windows.)

*

*Option 1: Update to Windows 10 version 1803 and OpenSSH Client will be automatically installed. See Windows 10 version 1803 (April 2018) section below for more details.

*Option 2: OpenSSH Client (Beta) and OpenSSH Server (Beta) are available as optional features in this version of Windows.  To install the OpenSSH optional features:
From Manage optional features -> Add a feature, select OpenSSH Client (Beta) and (if desired) OpenSSH Server (Beta) to install:

Microsoft's instructions for installing the OpenSSH Beta in this version of Windows, which also covers additional steps for configuring and using OpenSSH, can be found here: Using the OpenSSH Beta in Windows 10 Fall Creators Update and Windows Server 1709

Windows 10 version 1803 (April 2018)
OpenSSH Client should already be installed after updating to Windows 10 version 1803. If you've verified you're running Windows 10 Version 1803 and OpenSSH Client is not installed, see the section below for Alternative Installation Methods.
OpenSSH Client is already installed and listed as such under Manage optional features:

OpenSSH Server is available as an Optional Feature in this version of Windows.  To install OpenSSH Server, from Manage optional features -> Add a feature, select OpenSSH Server to install:

Alternative Installation Methods
The alternative installation methods listed here may be used at your own risk if the above options do not work.  They should also work on older versions of Windows.
These methods can also be used for installing more recent versions of OpenSSH:

*

*Windows 10 Version 1709 (Fall Creators Update) installs OpenSSH version 7.5p1 (released as version 0.0.18.0 by Microsoft in July 2017).

*Windows 10 Version 1803 (April 2018 Update) installs OpenSSH version 7.6p1 (released as v7.6.0.0p1-Beta by Microsoft in February 2018).

*The most recent release of Win32-OpenSSH at the time of this writing appears to be based on version 7.7.2.

Install from Win32-OpenSSH GitHub project
Follow the instructions on the Win32-OpenSSH Wiki on Microsoft's Win32-OpenSSH GitHub Project.  Pay close attention to the Wiki instructions and the version of Win32-OpenSSH as they change periodically.
Install OpenSSH via Chocolately
If you're a fan of Chocolately, a Win32 OpenSSH Chocolately package is available.
However, this method is no longer recommended by Microsoft and the Microsoft Win32-OpenSSH Wiki explicitly states that this is "deprecated" (i.e. NOT RECOMMENDED), even though recent versions of the Chocolately package are released and available.
If you go this route, be sure to read the Win32 OpenSSH Automated Install and Upgrade using Chocolatey link on the Win32-OpenSSH Wiki.

A:
My understanding is that after updating to Windows 10 version 1803
  (April 2018), OpenSSH client is automatically installed. However, it's
  not installed and the information I've seen online for how to install
  OpenSSH appears to be for previous versions of Windows 10, when
  OpenSSH Client was in beta.

As per the original configuration, as described in the question, within an elevated PowerShell the following command Get-WindowsCapability -Online | ? Name -like 'OpenSSH*' would have printed the following.

Name  : OpenSSH.Client~~~~0.0.1.0
State : NotPresent
Name  : OpenSSH.Server~~~~0.0.1.0
State : NotPresent

Likewise, running the following commands would have installed OpenSSH Client and OpenSSH Server.

Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

Running the same command as before, Get-WindowsCapability -Online | ? Name -like 'OpenSSH*' , would have generated the following output after a restart.

Name  : OpenSSH.Client~~~~0.0.1.0
State : Installed
Name  : OpenSSH.Server~~~~0.0.1.0
State : Installed

I was able to confirm that OpenSSH Client is indeed installed by default on 1803, likewise, OpenSSH Server is an optional feature that must be enabled.

I've also tried looking for it under the standard Windows Features
  (Turn Windows Features on and off) as suggested by this answer and I
  do not see it listed. (I've even tried expanding all of the
  collapsible items just to make sure it wasn't hiding under IIS or
  something):

Unlike the feature when it was still in its beta form, it does not appear, in the legacy list of windows optional features.  It only appears in the list accessed within Settings.  The command to install OpenSSH Client and OpenSSH Server are identical between Windows 10 1709 and Windows 10 1803 by the way.
Using the OpenSSH Beta in Windows 10 Fall Creators Update and Windows Server 1709

A: if you, like me, got to this question because you have openssh installed but you are getting the "not recognised" error in power shell, here's what worked for me:

*

*uninstall openssh client via the "optional features" menu in settings

*re-install what you just uninstalled

*reboot

*reboot again

I have no idea why the second reboot was necessary, but after one reboot %SYSTEMROOT%\System32\OpenSSH\ had been added correctly to my $env:PATH, but I was still getting the "not recognized" error, but rebooting again fixed it.

A: Here's what worked for me to get back up and running with ssh.  It's not what I would call an ideal solution since I still don't know how to properly install OpenSSH through Windows.  But this worked.
I followed the instructions on Matt McElreath's TechSnip's blog post to download and install Win32-OpenSSH:
OpenSSH on Windows: How to Get it Set Up
I slightly modified the steps from Matt's blog because I already had some components of OpenSSH installed such as OpenSSH Authentication Agent (ssh-agent.exe) and OpenSSH Server (sshd.exe). I was only missing OpenSSH Client (ssh.exe):

*

*After downloading and unzipping the archive into C:\Program files\OpenSSH I skipped the steps to install sshd.exe (PowerShell script install-sshd.ps1) and to install the Windows Services for sshd and ssh-agent, because these were already installed and working for me.

*I copied ssh.exe executable (missing on my system) from C:\Program Files\OpenSSH\OpenSSH-Win64 to C:\Windows\System32\OpenSSH:

And that's it. ssh now works as expected.  It works with ssh-agent, ssh-add, and git is also working again with ssh.
If anyone has a clue to why I cannot simply reinstall OpenSSH Client through the standard Windows managed features, I'd love to hear it.
This should also work for anyone that just wants to install and use OpenSSH on Windows, regardless of which Windows version they're using.

A: I am just dealing with the same issue, again, so I am putting this here to remind myself as I keep forgetting this one:
Open windows powershell as administrator and past two of these:
Install the OpenSSH Client
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0

Install the OpenSSH Server
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

Both of these should return the following output:
Online        : True
RestartNeeded : False
And then configure it:
Start-Service sshd

OPTIONAL but recommended:
Set-Service -Name sshd -StartupType 'Automatic'

Confirm the Firewall rule is configured. It should be created automatically by setup.
Get-NetFirewallRule -Name *ssh*

There should be a firewall rule named "OpenSSH-Server-In-TCP", which should be enabled
If the firewall does not exist, create one
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
It says no reboot require as usual but always reboot Windows after installing a service.
This is from the official Microsoft help site.


text:
Q: asmx file in asp.net I am using http://api.jangomail.com/ api in my web application and added a reference using "Add service refernce" and giving the path http://api.jangomail.com/api.asmx and selecting the HttpGet in add service reference.
I want to use this method :
http://api.jangomail.com/help/html/655d20ca-2164-c483-fb21-d3d0ee049155.htm
But I dont get intellisense? Do I need to add assembly reference or what?
Thanks

A: you do not need to add any assembly.
You just need to reference to the web service and, when asked, you have to give a proper name to the namespace.
If the reference has been created you will see a "Service References" folder with your service object (let's say ServiceReference1) and the configuration files (wsdl, etc).
Now you can write your code:
        var jango = new ServiceReference1.JangoMailHttpGetClient();
        jango.SendTransactionalEmail();


text:
Q: A way to begin learning financial Mathematical modelling with help of modelling software I would like to begin self studying in modelling financial situations where I have at least two conditions for the book before I begin:
(1) There should be some explicit examples here and there, but it the Mathematical information should be somewhat dense since I dont't really like reading long paragraphs consisting of solely words.
(2) I want to learn how to implement my models in e.g. MATLAB or some other common used modelling software.
I've come across "Financial Modelling: Theory, Implementation and Practice with MATLAB Source" by Daniel Wetterau and Joerg Kienitz. Also, "Foundations of Computational Finance with MATLAB" by Ed McCarthy.
Any opinions on these book? They are both very recently published (2013 and 2018) so I guess that's fairly up to date. Do you suggest other books that satisfy my conditions listed above?


text:
Q: Intersecting multiple points from CSV with multiple polygons using PyQGIS I'm writing a script that imports many CSV files containing x and y coordinates from a specific folder and intersect each CSV file with each polygon from another folder. Example:
the csv_1, csv2, intersects with polygon1_, polygon_2...
I'm trying to write the code. I get all the layers without problems, but I don't know how to get intersection between them and how to write it in this code.
import glob, os, processing

output = 'C:/Users/Brubisgeo/Downloads/teste/csv/shp'
path_to_csv = 'C:/Users/Brubisgeo/Downloads/test/csv'
os.chdir(path_to_csv)

#Importing all the csvs from a folder and plotting:

for fname in glob.glob('*csv'):
    filepath = os.path.join(path_to_csv, fname)
    uri = f'file:///{filepath}?type=csv&delimiter=%5Ct;&maxFields=10000&detectTypes=yes&xField=x&yField=y&crs=EPSG:31983&spatialIndex=no&subsetIndex=no&watchFile=no'
    name = fname.replace('.csv', '')
    lyr = QgsVectorLayer(uri,name, 'delimitedtext')
    QgsProject.instance().addMapLayer(lyr)

#Importing all the polygons from a folder:

path = 'D:/SCRIPTS/shps'
os.chdir(path)
layer = []
for root,directory,files in os.walk(path):
    for file in files:
        if file.endswith('.shp'):
            full_path = os.path.join(root,file)
            vlayer = QgsVectorLayer(full_path,file[:-4],'ogr')
            b = QgsProject.instance().addMapLayer(vlayer)

            #This is what I tried to do, create the lists (one from csvs files and another from polygons) but doesn't work.

            for layers in layer:
                inter = {'INPUT':[lyr],'OVERLAY':[vlayer],'INPUT_FIELDS':[],'OUTPUT': (output+lyr+'_intersected.shp')
                processing.run('native:intersection',inter)


text:
Q: typeof undefined not working with .get() within variable I'm using .get() in a variable which returns 'undefined' until I deselect items in multiple select options.
I tried to avoid this with a condition typeof but it still returns undefiend when selecting new options.
var $slidesoptions = $('#Slidesnumber');
var $deselected = $slidesoptions.find('option.selected:not(:checked)');
$slidesoptions.find('option:checked').addClass('selected');
$deselected.removeClass('selected');

if(typeof $deselected.get()[0].value === "undefined"){
    console.log("its undefined");
}
else {
    console.log("its not undefined");
    console.log("$deselected:",$deselected.get()[0].value);
}

Uncaught TypeError: Cannot read properties of undefined (reading
'value')

UPDATE: I think i found it, I need to check only for the array, not the value in the array, not exactly sure why though.
if(typeof $deselected.get()[0] !== "undefined"){
console.log("its not undefined");
}


text:
Q: Orthogonal Matrix filled according to function I want to create an orthogonal matrices in Python to visualize the decline of a signal according to the distance from the source and the angle to the source.
For simplicity we can describe the decline:
NewValue = cos(angle)*(StartingValue – a*(distance))

I found that Scipy.stats has ortho_group, which can be used to create random orthogonal matrices:
 from scipy.stats import ortho_group

 x = ortho_group.rvs(3)
 np.dot(x, x.T)

 # returns:
 array([[  1.00000000e+00,   1.13231364e-17,  -2.86852790e-16],
        [  1.13231364e-17,   1.00000000e+00,  -1.46845020e-16],
        [ -2.86852790e-16,  -1.46845020e-16,   1.00000000e+00]])

 import scipy.linalg
 np.fabs(scipy.linalg.det(x))
 # returns:
 1.0

Since a random matrix isn't really useful, I keep wondering how I can create a orthogonal matrix with values according to my function.
A second challenge, I'm encountering is how to limit the range of the matrix to a range of angles of 0-45° degrees.


text:
Q: Trying to find a (jquery?) popup date/time selector with callback to php I have a large table with input boxes.
Three columns of these are dates/times (in unix format).
Im trying to find an easy to implement way of allowing the user to click on this box, being able to (graphically) select a date/time, and when done, sending the selection to a php script to make the physical changes of the data. (i can convert the date/time back to unix from here if necessary).
The caveat is that each input is named dynamically according to its row number.
Here is my script where i output the date fields
}elseif(in_array($j, array(19,33,54))){
    echo "<input type=text value=\"$value\" name=\"date$j\" class=med>		";

A: jQuery UI datepicker supports a great number of options and events including an on-select event. It's also possible to have a datepicker attached to a hidden input with a separate activation control, so there's no problem at all with using it for AJAX.

A: Try to integrate the jQuery datepicker, but what you need to do is some kind of ajax call to the PHP!


text:
Q: HttpWebRequest times out on the second call to the Web Server I've got a very strange problem here:
There is a RESTfull web service on a Python Paste web server, a WPF .net application makes a  http POST request to the server every 2 seconds. The problem is that on the second call to the server, the request times out! sometimes later (say forth or fifth) requests work again and later again I get this "time out" exception!
The IntelliTrace shows that there was a blocked operation in ws2_32.dll:

A blocking operation was interrupted by a call to
  WSACancelBlockingCall

I simulated the REST web server on the IIS using asp.net and the problem no longer exists, so I assume it might be the Python server config! But the Python Web Server works normally when I make the request from within the browser!
However I tried different things in the .net client application:

*

*I have increased the ServicePoint's DefaultConnectionLimit:
ServicePointManager.DefaultConnectionLimit = 500;

*I created a new thread for any new request to the server and aborted it when request is done!

*I created a new AppDomain before any request and explicitly unloaded it when process is done!

*Tried different http request headers: connection=keep-alive, accept=*
None of the above seems to work! However the funny part is that when I set a break-point to the GetRequestStream() line in VS 2012, the request dos not timeout and works properly!
Debugging the .net managed code using reflection I figured that the unmanaged recv method of the ws2_32.dll causes the operation to block and hence the web request times out!
Here's the C# code:
static void Main(string[] args)
{
    Task.Run(() =>
    {
        while (true)
        {
            Thread.Sleep(2000);
            Console.WriteLine(PostData());
        }
    });

    Console.ReadLine();
}

public static string PostData()
{
    try
    {
        var response = "";
        var httpRequest = WebRequest.CreateHttp("http://remote_address");
        httpRequest.ServicePoint.ConnectionLimit = 500;
        httpRequest.Method = "POST";
        httpRequest.ContentType = "application/x-www-form-urlencoded";
        httpRequest.Timeout = 5000;

        using (var writer = new StreamWriter(httpRequest.GetRequestStream()))
        {
            writer.Write("req=" + "[some parameters]");
        }

        using (WebResponse httpResponse = httpRequest.GetResponse())
        {
            using (var data = httpResponse.GetResponseStream())
            {
                StreamReader sr = new StreamReader(data, Encoding.UTF8);
                response = sr.ReadToEnd();
            }

            httpResponse.Close();
        }

        return response;
    }
    catch (WebException ex)
    {
        return "time out!";
    }
}

Is there anything I can do to make this work?

A: I managed to fix the issue with disabling Expect100Continue header:
ServicePointManager.Expect100Continue = false;

According to the HTTP 1.1 protocol, when this header is sent, client requests that use the POST method expect to receive a 100-Continue response from the server to indicate that the client should send the data to be posted.
Having this property set to true (which is the default behavior of .Net) the data is not sent with the initial request. Instead, this header is sent to the web server which responds with 100-Continue if implemented correctly. However, not all web servers handle this correctly, including the server to which I am attempting to post data. I sniffed the headers using Fiddler and noticed that my code does send this header, while the Python Paste does not!


text:
Q: [opinion] the same as [subjective]? opinion is pretty much the same thing as subjective and is being tagged onto questions in the same manner (now deleted, 10k+ only). Time to blacklist?

A: Blacklist? How 'bout, make opinion into a kiss of death: Go through the questions so-tagged, and vote to close them. If they're already closed, vote to delete them. If they don't deserve either, then re-tag them.

A: Ex-ter-min-ate!  Ex-ter-min-ate!
Seriously, this is even more vacuous than "subjective".  I have a lot of opinions, and varying amounts of objective support for them.  Many of them are shared very widely, and I introduce some of them into all but the most objective questions (like "Is this valid according to the Standard?").
My opinion, which is only somewhat subjective, is that "opinion" is worse in every way than "subjective".


text:
Q: Can we explicitly call a virtual `operator delete`? For reasons I wish not go into in depth here, I need to fully instrument allocations and deallocations in a large, existing code base, which makes use of custom operator new and operator delete. To this end, I am rewriting (using a clang frontend pass) every occurrence of new X(...) with new (allocate<X>()) X(...), where the default implementation of allocate<X> calls out to the class-specific operator new, if it exists, or ::operator new otherwise. I know that this is not 100% sound, but it is "good enough" for the code base I am targeting.
Now I'm trying to introduce a similar intercepting behavior for delete, but this is harder than expected, due to the weird nature of virtual operator delete. From https://en.cppreference.com/w/cpp/memory/new/operator_delete:

The call to the class-specific T::operator delete on a polymorphic class is the only case where a static member function is called through dynamic dispatch.

Consider the following example:
struct A {
    virtual ~A() { cout << "~A" << endl; }
    static void operator delete(void* ptr) {
        cout << "A::operator delete" << endl;
        ::operator delete(ptr);
    }
};
struct B : public A {
    virtual ~B() { cout << "~B" << endl; }
    static void operator delete(void* ptr) {
        cout << "B::operator delete" << endl;
        ::operator delete(ptr);
    }
};

Ideally I would want to replace each occurrence of delete x in the code base with deleteWrapper(x), which is equivalent to delete x by default, but which I can add extra instrumentation to and specialize it for certain types of x if needed.
I thought I could do something like the following to achieve this:
template <typename T>
void deleteWrapper(T* x) {
  x->~T();
  // The deallocation behavior here should "tweakable" for certain types
  // of T, for example I might need different implementations for
  // std::pair<int, int> and std::pair<std::string, int>
  x->operator delete(x);
}

But (aside from invoking undefined behavior) this is not equivalent to delete x: With the above type hierarchy, deleteWrapper(static_cast<A*>(new B)) calls A::operator delete instead of B::operator delete. Is there a way to call the correct overload, given a polymorphic pointer, without using delete?
If there is a solution which involves a certain amount of source rewriting, I would be interested to hear about it as well since I am already using a modified clang.


text:
Q: Smack API - How to display loop jxTaskpane for expand and collapse roster list i have problem to display Taskpane for loop. i have a code to get the groups of roster (Groups : Friends - Business - Company, so on)
my code is :
Roster rost = xmppcon.getRoster();
Collection<RosterGroup> groups = rost.getGroups();

 for(RosterGroup group : groups){
            DefaultListModel model = new DefaultListModel();
            model.addElement(group.getEntries());
            String GroupNameCount = group.getName() + "("+group.getEntryCount()+")";
            jXTaskPane1.setTitle(GroupNameCount);
            jXList1.setModel(model);

        }

but jxTaskpane not loop, but when i print group name it print 2 line (because in database user A have two group is Friends and NIIT)
sample print
System.out.println(group.getName());

result:
Friends

NIIT

A: You're using the same instances of JXTaskPane and JXList at each iteration of the loop. You should really create one instance (JXTaskPane jXTaskPane1 = new JXTaskPane()), and same for the JXList in the loop.
When you've setup the JXTaskPane, add it to the containing component.


text:
Q: Is there caching in templating function in Magnolia? Is there a caching for the templating function in Magnolia? I created a custom templating function with a function that retrieves data from a specific workspace. I put logs in it to know if it is entering the function that I want to call, but seems like even if I call the function I created in the templating function, I don't see the logs, thus it will get the previous data that I have. Then what I notice is that, when I've updated something on that workspace, then when I call the function, it will enter that function and give me the updated data.
So is there caching or what? Is there a way to disable this? It was my first time to notice this so I find it a bit weird also because in my local dev environment, I can always see that it always enter to the function whenever it is called. However the one deployed in our UAT environment, when I check the logs, it doesn't always enter to the function for every call. So I'm quite lost here.
I'm using Magnolia 5.4.7.
Appreciate it a lot if anyone can help. Thanks!

A: I found the issue. Yeah there's really a cache. So what I did is I exclude my page for being cache so when I call the templating function in my page, it will return me the latest one.
Also, this caching only happens in delivery instance.  That's why in my local environment it was working because I'm actually using the author instance to test! That's made the difference.
You have to configure your custom cache policy under "/modules/cache/config/configuration/default/cachepolicy" of the config workspace. For more information, please check: https://documentation.magnolia-cms.com/display/DOCS53/Cache+module , read the "Excluding content from cache" for this


text:
Q: Real time request/response server (Java) I need to write a service which will be acting as a real time mock server. We have multiple microservices and some of them are not ready. That is why I got a task to write this kind of service using java. But the main challenge for me is that it should create response upon requests in real time, so this service should mock APIs in real time without new deploy.
Architecture can be built on API calls which will set request and response, and those requests and responses will be used later.
Or it can read from some folder requests and responses in .json format files and mock APIs.
I am not sure did I explained my question clearly. Appreciate any kind of help.
I haven't tried something, but I saw Mockoon has this functionality. It is written in python.

A: Well, a simple mock server in your case can be build by -

*

*Get the signatures & input/output payloads of your Microservices api's that are not yet developed. If the signatures & payloads are not yet defined, you need to get in a huddle with stakeholders to articulate them first

*Simulate the input/output jsons and place them in a folder structure having the mapping in folder naming conventions

*Write a simple Spring Boot Webservices component, with Swagger enabled. Your Spring endpoints can refer the json folders & return the example jsons. Swagger will allow you to publish an API listing url for consumption by respective teams.


text:
Q: How to modify the "Global.asax" of a Web API just to impact the Help Page? (MVC) * Scenario: *
I have got a web api service application made in C# Visual Studio 2012.
This web service has an "Areas" folder with the default project of Web Api Help Page.
* Problem: *
By requeriment, I must to implement a manual input to authenthicate and authorize the user that can read the Web Api Help Page. But NOT in the web service.
So far so good, I've made an account controller, log in procedures, get roles from the database, etc etc.
But now, what I try to realize is how to write the Application_PostAuthenticateRequest procedure in the global.asax, because the only global.asax that I've is from the main project, the Web API Help Page has not his own.
* QUESTION *
How can I write the Application_PostAuthenticateRequest method without impacting on the main service, in order to use the Authorization attributes ONLY in the Web API Help Page?
Thanks and kind regards,

A: If I understand your question you want to route to just a specific path with Authorization only?
If this is the case you can use routing as part of WebAPI 2
Within the WebAPIConfig.cs add the following configuration
public static void Register(HttpConfiguration config)
{
 //Enable attribute routing
 config.MapHttpAttributeRoutes();

//... additional configuraitons
}

Then within your API controller you can setup a route independent of the default and add whatever attribute you need:
[Route("apiname/authroizedLogin")]
[Authorize(Roles="admin")]
public void IHttpActionResult(string username, stringpassword)
{
   try
   {
    dosomething...
    return Ok(somecontext);
   }
   catch(exception e)
   {
    return BadResponse(e.message);
   }
}

Here is a link with more information on routes in WebAPI 2
Edit
With regards to accessing the role. It depends on your implementation. I'm personally not a fan of using the global.asx as it would make a db request more frequently. I'd need more info on your implementation to make any real recommendation. However here are a few options. If you are using claims based authentication the role can be a part of the claim and would be passed to the API as part of the http context/request. From here you can derive the identity as:
   public long RoleId
    {
        get
        {
            var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
            string id = identity.Claims.Where(c => c.Type == "http://myschema.com/app/claims/roleid")
                .Select(c => c.Value).SingleOrDefault();

            //return 0 if no claim is located
            return (!String.IsNullOrEmpty(id)) ? Convert.ToInt32(id) : 0;
        }
        set
        {
            _userId = value;
        }
    }

If you're not using claims another option would be to generate a FormsAuthenticaitonTicket which could be encrypted and stored as a cookie once the user is authenticated.


text:
Q: Need explanation on why my pi is equal to 0 I was rewriting the code below using OpenMP task to parallilize the Pi program.
Original Code:
#include <omp.h>
#include <stdio.h>
static long num_steps = 1024*1024*1024;
#define MIN_BLK  1024*1024*256

double pi_comp(int Nstart,int Nfinish,double step)
{  int i,iblk;
double x, sum = 0.0,sum1, sum2;
if (Nfinish-Nstart < MIN_BLK){
  for (i=Nstart;i< Nfinish; i++){
     x = (i+0.5)*step;
     sum = sum + 4.0/(1.0+x*x);
  }
}
else{
  iblk = Nfinish-Nstart;
  sum1 = pi_comp(Nstart,         Nfinish-iblk/2,step);
  sum2 = pi_comp(Nfinish-iblk/2, Nfinish,       step);
  sum = sum1 + sum2;
}return sum;
}
int main ()
{
int i;
double step, pi, sum;
double init_time, final_time;
step = 1.0/(double) num_steps;

init_time = omp_get_wtime();
sum = pi_comp(0,num_steps,step);
pi = step * sum;
final_time = omp_get_wtime() - init_time;
printf(" for %ld steps pi = %f in %f secs\n",num_steps,pi,final_time);

}

OpenMP Code:
#include <omp.h>
#include <stdio.h>
static long num_steps = 1024*1024*1024;
#define MIN_BLK  1024*1024*256

double pi_comp(int Nstart,int Nfinish,double step)
{  int i,iblk;
double x, sum = 0.0,sum1, sum2;
if (Nfinish-Nstart < MIN_BLK){
  for (i=Nstart;i< Nfinish; i++){
     x = (i+0.5)*step;
     sum = sum + 4.0/(1.0+x*x);
  }
}
else{
  iblk = Nfinish-Nstart;
  #pragma omp task firstprivate(sum1)
  sum1 = pi_comp(Nstart,Nfinish-iblk/2,step);
  #pragma omp task firstprivate(sum2)
  sum2 = pi_comp(Nfinish-iblk/2, Nfinish,step);
  sum = sum1 + sum2;
}return sum;
}
int main ()
{
int i;
double step, pi, sum;
double init_time, final_time;
step = 1.0/(double) num_steps;

init_time = omp_get_wtime();
#pragma omp parallel
{
#pragma omp single
sum = pi_comp(0,num_steps,step);
}

pi = step * sum;
final_time = omp_get_wtime() - init_time;
printf(" for %ld steps pi = %f in %f secs\n",num_steps,pi,final_time);

}

I dont know why the output for the OpenMP program has pi = 0 instead of pi itself when testing the speed of a certain amount of thread. Is there something I did wrong in the OpenMP code that didn't give me pi?
Output:
g++ -fopenmp  -c pi_recur_omp.cpp
g++ -fopenmp  -o pi_recur_omp pi_recur_omp.o -lm
./pi_recur
 for 1073741824 steps pi = 3.141593 in 4.562793 secs
./pi_recur_omp
 for 1073741824 steps pi = 0.000000 in 2.990318 secs

A: In this case, I'd say the mistake is using recursion at all. It doesn't really gain you much (if anything at all). I'd probably just do a simple iterative version:
#include <omp.h>
#include <stdio.h>
static long num_steps = 1024*1024*1024;

double pi_comp(int Nstart,int Nfinish,double step)
{
    int i,iblk;
    double sum = 0.0,sum1, sum2;

#pragma omp parallel for reduction(+:sum)
    for (i=Nstart;i< Nfinish; i++){
        double x = (i+0.5)*step;
        sum = sum + 4.0/(1.0+x*x);
    }
    return sum;
}
int main ()
{
    int i;
    double step, pi, sum;
    double init_time, final_time;
    step = 1.0/(double) num_steps;

    init_time = omp_get_wtime();
    sum = pi_comp(0,num_steps,step);
    pi = step * sum;
    final_time = omp_get_wtime() - init_time;
    printf(" for %ld steps pi = %f in %f secs\n",num_steps,pi,final_time);

}

Result:
for 1073741824 steps pi = 3.141593 in 0.455449 secs

A: Your OpenMP code is not working properly because of:

*

*sum1 and sum2 should be shared. Using the firstprivate clause (which is the default) makes them private, so the updated values are not available outside the tasks.

*You have to wait for tasks to finish before you can sum them, so a #pragma omp taskwait line is needed.

So, your code can be corrected using:
#pragma omp task shared(sum1)
sum1 = pi_comp(Nstart,Nfinish-iblk/2,step);
#pragma omp task shared(sum2)
sum2 = pi_comp(Nfinish-iblk/2, Nfinish,step);
#pragma omp taskwait
sum = sum1 + sum2;

As pointed out by @JerryCoffin a simple iterative method gives much better performance compared to your recursive code using tasks.


text:
Q: virtual inheritance and protected members access I saw the example below in an SO question about preventing class inheritance, and I didn't understand why it should work : If I have a class "CTest" that inherits publicly CBase, the compilation fails because in constructor 'CTest::CTest()' 'CSealed::CSealed()' is protected. If I get rid off the virtual keyword, the compilation succeeds, why ?
class CSealed
{
protected:
CSealed()
{
}
};

class CBase : virtual CSealed
{
public:
 CBase() {
 }
};

class CTest : public CBase
{
public:
CTest() { std::cout << "TEST !!!!\n " << std::endl; }
};

A: The code you've posted,
class CSealed
{
protected:
    CSealed()
    {}
};

class CBase : virtual CSealed
{
public:
    CBase()
    {}
};

will not permit CBase to be derived from. That's because the virtual base class must be initialized by the (each) constructor of the most derived class. And since the virtual base is a private base class, it's not accessible to a class derived from CBase.
E.g., this class derivation,
class CTest
    : public CBase
{};

should not compile it CTest is ever instantiated.
However, as a matter of fact, while it fails to compile with Visual C++ 2015, it does compile with MinGW g++ 6.3.0, so in practice it's not entirely reliable.
Instead of this old C++03 technique you can just use C++11 final:
class CBase final
{
public:
    CBase()
    {}
};


text:
Q: How to convert MySQL datetime value to google chart api datetime I am trying to convert a value from a datetime field in a MySQL database to a value I can pass on to a Google chart datetime field.
For example a MySQL value: 2012-03-05 17:03:56.
Google Chart Api link: http://code.google.com/apis/chart/interactive/docs/gallery/linechart.html
I want to pass this into a column defined like this: data.addColumn('datetime', 't');
I want to send it into a row as such: data.addRow([date_value]);
I'm not sure how to convert between the two. So what I am asking is How do I convert MySQL datetime value to a google chart api datetime value?

A: Google's just using the standard javascript Date object. Easier method would be to get a unix_timestamp(yourdatefield) out of MySQL, which gives you seconds-since-the-epoch.
Javascript's date object accepts milliseconds-since-the-epoch as one initializer value, so:
data.addRow(new Date(<?php echo ($seconds_from_db) ?>000));
                                                     ^^^--- 3 extra zeroes to make it a millisecond value


text:
Q: How can I make placing cursor on empty line behavior to place it after virtual indent? When I have an empty line between a few code lines and I place a cursor at this empty line, it's placed without any indentation in Rider. In VS it's placed after the virtual indentation same as the indentation of the surrounding code and this is the behavior I expect. Also, in Rider Home key doesn't move the cursor to the virtual indention.
Is there any way to have the behavior in Rider same as in VS?
Wrong:

Correct:

A: The only thing in Rider that I'm familiar of is Virtual Space (see here). Open File | Settings | Editor | General and set the highlighted property:

Now you can click anywhere in the editor and Rider will automatically create the necessary number of whitespaces.
But I understand that this is not 100% what you are looking for


text:
Q: how to deal with R0915: Too many statements (69/50) (too-many-statements) in pylint? I have a Python code (GUI with with multiple graphical items) in PyQt5 . How can I shorten the code to suit PEP8 50 statements per function recommendation? Is it suitable to break the definitions of the graphical items to multiple functions?
    def __init__(self, pulse_number, on_time, off_time, x, y, offset):
        self.offset = offset
        self.laser_pulse_n = pulse_number
        self.laser_on_time = on_time
        self.laser_off_time = off_time
        self.laser_x_loc = x
        self.laser_y_loc = y
        # set window properties
        self.setMinimumSize(QSize(250, 300))
        self.setWindowTitle("Laser settings")

        self.int_validator = QIntValidator()

        # LASER
        # Create pulse number label
        self.pulse_number_label = QLabel(self)
        self.pulse_number_label.setGeometry(QRect(10, 0, 80, 20))
        self.pulse_number_label.setText("Pulse n.:")

        # Create pulse number input box
        self.pulse_number_input = QLineEdit(self)
        self.pulse_number_input.setGeometry(QRect(60, 0, 40, 20))
        self.pulse_number_input.setText(str(self.laser_pulse_n))
        self.pulse_number_input.setValidator(self.int_validator)

        # Create laser on label...

        ...

        # Apply button
        self.validate_button = QPushButton(self)
        self.validate_button.setGeometry(QRect(10, 240, 230, 40))
        self.validate_button.setToolTip("Click to save settings")
        self.validate_button.setFont(QFont('Times', 20))
        self.validate_button.setText("Apply")
        self.validate_button.clicked.connect(self.validate_settings)

A: In my opinion there are two solutions : you can disable this warning ecause PyQT is kinda forcing you to code it like this. It's clearer to have every attribute definition in the constructor and if you create sub-function you'll get a attribute-defined-outside-init warning anyway. Another solution would be to refactor a little and create a property setter or a function for setting up the object.
Ie for example, going from this:
        ...
        self.validate_button = QPushButton(self)
        self.validate_button.setGeometry(QRect(10, 240, 230, 40))
        self.validate_button.setToolTip("Click to save settings")
        self.validate_button.setFont(QFont('Times', 20))
        self.validate_button.setText("Apply")
        self.validate_button.clicked.connect(self.validate_settings)

To this:
        ...
        self.validate_button = self.validate_settings

    @property
    def validate_button(self):
        return self.__validate_button

    @validate_button.setter
    def validate_button(self, validate_settings):
        self.__validate_button = QPushButton(self)
        self.__validate_button.setGeometry(QRect(10, 240, 230, 40))
        self.__validate_button.setToolTip("Click to save settings")
        self.__validate_button.setFont(QFont('Times', 20))
        self.__validate_button.setText("Apply")
        self.__validate_button.clicked.connect(validate_settings)

This has the advantages to permit to change the attributes later if you need to.
Or this:
        ...
        self.validate_button = QPushButton(self)
        self.__init_validate_button()

    def __init_validate_button(self):
        self.validate_button.setGeometry(QRect(10, 240, 230, 40))
        self.validate_button.setToolTip("Click to save settings")
        self.validate_button.setFont(QFont('Times', 20))
        self.validate_button.setText("Apply")
        self.validate_button.clicked.connect(self.validate_settings)

That permit to keeps the class immutable


text:
Q: Flush saveAll in JpaRepository Since there's a saveAndFlush(), is there a way to
Flush the updated entities when using saveAll()?
I'm trying to update entities by batch.
Will really be a big help!
Thank you!

A: No need to manually call flush() after saveAll(), just create a default method. Eg of Person:
@Repository
interface PersonRepo extends JpaRepository<Person, String> {
    default List<Person> saveAllAndFlush(Iterable<Person> iterable) {
        List<Person> list = saveAll(iterable);
        flush();
        return list;
    }
}

A: No, but you can manually call saveAll() and then flush().