text:
Q: Array with fast insertion/deletion I am looking for a data structure that stores an array of elements and supports these operations:

*

*Accessing element at a given index

*Adding or removing an element at a given index (and hence shifting the following elements)

Arrays do the first operation in O(1) but the second one takes O(n), while linked lists do the opposite. Is there a middle-ground data structure? Say, something that can do both operations in O(lg n) or O(n^epsilon) "worst-case" time?
Note that I am not asking for a balanced binary search tree. Here the keys (indices) are changed and shifted every time a new element is added/removed. For example, removing the smallest element decreases the indices for all other elements by 1.

A: There is 'AVL-Array', an STL-style container that
performs both operations in O(log n).
It is built on top of an AVL-Tree, but it is still not
an associative container, but sequential.
It supports index access [] with vector semantics.
Notice that AVL-Array does not implement a search tree,
but rather a sequential container that
happens to come in tree form. Indexing, iteration, insertion
and deletion all do what you would
expect a vector to do.
You can find it here

A: You can do this with a kind of balanced binary tree whose in-order traversal gives the array elements in order, i.e., the leftmost node stores A[0] and the rightmost node stores A[n-1], where n is the number of elements in the array.
At each node we will store the total size s of the sub-tree rooted at that node (i.e. the total number of nodes), the value v of the array element stored at that node, the left child l of the node, and the right child r of the node.
You can retrieve the value of A[i] from such a tree as follows (for simplicity of exposition, no error conditions are checked):
int get_element(node *n, int i) {
  int ls = (n->l == NULL) ? 0 : (n->l)->s;

  if (i < ls) return get_element(n->l, i);
  else if (i == s) return n->v;
  else return get_element(n->r, i-(ls+1));
}

If the tree is balanced, this will take O(log n) time.  Inserting at an index or deleting at an index is similar to any balanced tree scheme, except that you are using the sub-tree sizes to navigate rather than the key value, which will also take O(log n).   Balanced tree data structures generally use a "rotation" to restore balance, e.g., a right rotation:
   y o                  o x
    / \                / \
 x o   C     ==>      A   o y
  / \                    / \
 A   B                  B   C

We can maintain the size of the new subtree at node y as size(B)+size(C)+1, and then that of x as size(A)+size(y)+1.
If you use the ideas from the finger search tree then you will also be able to iterate through the whole array in O(n), iterate through a sequence of length k in O(k), and skip forward or back from A[i] to A[i+k] or A[i-k] in O(log k).

A: B-tree is a good choice for you. https://en.wikipedia.org/wiki/B-tree


text:
Q: Detect version of Javascript used by NodeJS in Eclipse when running .js file? I'm doing all sorts of JS experiments to clarify various language points, many being run in Eclipse using Run As --> Node application (or Node program).
I'm surprised to find that Array.prototype.flat() is not available, although it is in my browser (Firefox 70), and am wondering what version of JS my Eclipse NodeJS installation is running.
My system's CLI version of NodeJS is v10.16.3. This also does not recognise Array.flat(). I haven't been able to find out the version of ECMAScript to which this corresponds (if it does). The version of "NodeEclipse" installed in Eclipse is said to be 1.0.2. I don't know how to read across from there to the NodeJS version...
There's a "pure-JS" answer here about obtaining the JS version, but you have to access the document, which I can't when I'm not running in a browser. Isn't there a simple way to find this out?
I'm confused: does Eclipse run a particular version of Node, and does a particular version of Node correspond to a particular version (ECMAScript version) of JS?
If I could just somehow get the Node version and the ES version when running a script this would help a great deal! Maybe there's some idiot-proof feature test?
PS
To add to my general bafflement: Array.flat() is not listed in the general page for Array.prototype, but it is listed as a method of Array.prototype on another page. Nor do either of these pages say to which ECMAScript version they correspond. Perhaps I should presume it is the latest for FF, since this is Mozilla, (i.e. ES7)?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Will a Handler's constructor always return before it starts accepting messages? I create a Handler that processes messages via handleMessage() in my app that needs to trigger other stuff once it's up and running. To accomplish this, I've set it up so it calls this.sendEmptyMessage() on itself in the constructor, which gets things going. This ensures the class is fully initialized before anything else tries to send messages to it. I just need to be absolutely sure the constructor will return before the sendEmptyMessage() call is executed because I later access the Handler via the variable returned by the constructor, and sending messages to a null Handler would be a problem.
Here's my code:
public myFavoriteHandler(Looper looper) {
    super(looper);
    this.sendEmptyMessage(DO_INITIALIZE); // DO_INITIALIZE is a static final int
}


text:
Q: How to give feedback after code review process I am currently reviewing some of the code of junior developers who just joined my team, I am wondering how should I deliver the output of this review:

*

*Should I fix the code myself?

*Should I give them feedback on the review process and let them do the fixes according to my instructions? And if so, how do I give this feedback, do I fill certain template document and send it to them, or there is some software that will help me mark things with problems inside the code files where they can later check for it? (I am using Visual Studio).
After I have done reviewing the code and fixes are done then some time has passed and some parts of the code I have reviewed in the past has changed, how do I do the re-review process? Should I recheck all the code all over again? Or do I just check the parts that have changed? And if so how do I keep track of the parts that have changed so that I avoid double reviewing code?

A: A lot depends on how you understand code reviews at your company. There are companies where a code review is a highly formalized process which takes place rarely but is a big deal. At others, code review is a mandatory part of each task which gets implemented, and is a very mundane and quick thing with little formalism. Personally, I opt for the latter approach, but it may or may not be your decision if you can use it or not.
I wrote a blog post titled Are code reviews worth your time? to summarize the process used by my team. The takeaways, as they relate to your question would be:

*

*Let the developers fix the code. This will allow them to better understand your comments (or realize they don't fully understand them and ask), and performing a task is a better way of learning than only reading about it.

*Software for code reviews is the way to go. There are many options available, both open-source and proprietary. Most of it works with git. My team uses BitBucket (formerly known as Stash), there's also GitLab and GitHub, Gerrit (which I personally am not a fan of), and a bunch of others. Most of these apps are web-based so it doesn't matter what IDE you use, but there are also plugins for many IDEs, so I'm sure there are some for Visual Studio as well. Software like this allows you to review code before it is merged into the main branch (usually via Pull Requests) and it shows the modified parts and some context lines around each change. This makes the code review fluent and hassle-free.

As for the review-fix-check-the-fix cycle, what you choose should depend on the developers' maturity and the gravity of the issues you spotted. Once teams make code reviews a daily process, you can expect trivial changes such as renaming a class, to simply be applied and there is probably no need to re-check them. If the team is not yet sold on code reviews or the people are really inexperienced, you might want to check such things regardless. On the other hand if your review spotted a complex concurrency issue which junior devs may not fully understand even after you point it out to them, you better check the fix and not give the change your approval before you are sure it was really corrected.
Tools can help you with this since if you work with pull requests, you can easily set up the software to not allow merging a change until it has the approval of a predetermined number of developers. Usually you can view the changes in individual commits of a change which allows you to easily look at only the changes added since your last round of comments.

A: Short Answer

Should I fix the code myself?

No.

Should I give them feedback on the review process and let them do the fixes according to my instructions?

Yes. According to your suggestions, not instructions. Instructions sound too authoritative.

And if so, how do I give this feedback, do I fill certain template document and send it to them, or there is some software that will help me mark things with problems inside the code files where they can later check for it? (I am using Visual Studio).

Use a tool to give the feedback. You may use Visual Studio.
Long Answer
I used to use Visual Studio but I constantly had to ask other developers, "Hey can you send me your work so I can review it?" I did not like that and it never worked out really well. Now, I use Review Assistant because I can start a review by looking at checkins. I do not need to rely on another developer sending me work to review. It also helps me mark items as defects, or simply mark items to be looked at by the author. This works for our team because once we start a review, it stays right there on the review board and does not get lost in translation. This is integrated with Visual Studio. As I mentioned, Visual Studio also has its native review process but I find it has limitations and the process is not natural; therefore, I use Review Assistant.
This tool also helps with the back and forth process, discussions etc.
The process, more or less, is as following:
I review something, then I send it to the author (in your case junior dev). They make changes and then they send it back. I look at the changes and provide feedback. If I am good with the changes, I close the review. Otherwise it goes back and forth. Sometimes if there is too much back and forth, I will just walk over to their desk and use a whiteboard--it really expedites the process.
Code reviews are a sensitive area so be very careful with the wording choice. I never tell anyone
Poor choice of wording

I reviewed your code and there are some items you need to change.

I instead say this:
Better choice of wording

I looked at your code and I need some help. Can you please review the items I sent you and see if you can clarify some of my questions?

This makes the author think:

*

*I need help so they do not go into a defensive mode.

*It sounds like they are the reviewer, not me. Technically speaking, since I am asking them to have another look and change some things, they sort of are like the reviewer.

These simple word choices have helped me enormously.
I never underestimate junior devs. I have worked with some senior developers (over 10 years experience) and there code was worse than a junior co-op student. So just because they are senior or junior is not all that important; their work is really what speaks louder than years of experience.
Oftentimes, to encourage junior devs and get them participating in reviews, I will send them something to review for me: Something they can figure out, something they will find challenging but not totally beyond them. I may word it like below:

Can you please review some code for me because I cannot figure it out.

This helps me greatly again. This helps because it clearly shows that I am not the only one who reviews, but they also do reviews and they are also part of the process. It shows that the whole idea is to produce good, clean code and ask for help if needed. The review process is a culture so we really need to work at it.
Now some people may worry that if they do the above, the junior devs will lose respect because they just did something you could not do. But that is far from the truth: asking for help shows humility. Plus there are plenty of situations wherein you can shine. Finally if that is your fear, you have self-esteem issues. Lastly, maybe I really do not know it: I mean some of these devs have algorithms fresh in their head because they just studied them a month ago.
Anyways, back to juniors and reviews.  You should see the look on their faces when they figure it out and send me a reply. I then may tell them, "OK, let me make the changes and if you are happy with it, please close the issue."
They feel awesome having the power to look at my work and say: "Yes, your changes are good. I closed the issue."
I never fix the code myself though because:

*

*The author will not learn from that.

*It is like me saying: "Move aside, let me show you how it is done. My code is better than yours."

*Why would I? This is more work for me.

But I will suggest ideas and code snippets in my comments to help out the author. Please note that sometimes my reviews are simply asking the author that I do not understand their code; there may be nothing wrong with their code. They may need to change variable names, add comments etc. Thus, I will not even know what to change in that case; only they will.
If you keep doing reviews, you will, sooner or later, have a really good idea of the knowledge level of each developer on the team. Knowing this is really useful and you need to take advantage of it and unleash it. Here is how: If I review some code and see obvious areas for improvement and I know another developer may catch them too, I will get them to review it instead. Something like "Hey, I see a few areas that can be improved. Can you please review it in more detail and send your comments to the author?" This works great too because now I have 2 other devs working with each other.
If I am reviewing some work and I notice something that the whole team can benefit from, then I will create a hypothetical scenario and explain the issue in a meeting. I will start by explaining the scenario and ask everyone if they can find the issue or see an issue, get them involved. Get everyone to ask questions. Then finally present a better approach. If someone else has a better approach, I thank them and acknowledge in front of the team their approach is better. This shows I am not "my way or the highway" type of personality. Furthermore, I NEVER open someone's work and start pointing out the issues in a meeting, the author will not appreciate it--regardless of how nice and harmless I think I am being.
When I do reviews, I do not just look for good clean code but also what the code is doing. If the business requirement is: If an employee has been with the company for longer than 10 years, give them 5% increase. Otherwise, 2.5%. The first thing I check is if it is actually doing that. Then I check if it is doing it it in a clean, consistent and performant way.
If I do a review, I make sure to follow up or no-one will take the reviews seriously.
I used to work with someone years ago who would do a review and cc the dev manager, and the QA manager but both managers came from a business background or had little development experience. He only did this to impress them. No one liked it and that is when I told myself I would never make that mistake.
The other thing he used to do is pick on programming style and was convinced his style is the best ("My kungfu is way better than your monkey style..."). That was another lesson for me: there is always more than 1 way of solving a problem.
Answer to some of your numbered questions

1- should I fix the code myself?

No, please see reasons I stated above.

2- should I give them feedback on the review process and let them do the fixes according to my instructions?

Yes, try to use sentences and a tone that is friendly but yet requires attention. Be as clear as you can. State what the issue with the code is, how to improve it. DO not simply ask to change it. But provide reasons.

how do I give this feedback, do I fill certain template document and send it to them, or there is some software that will help me mark things with problems inside the code files where they can later check for it? (I am using Visual Studio).

Like I said, you can use the tool I use or another tool. Do not use email or word documents because they get lost and it is hard to keep track of it.

After I have done reviewing the code and fixes are done then sometime has passed and some parts of the code I have reviewed in the past has changed, how do I do the re-review process? should I recheck all the code all over again?

Mostly what I do is to check the delta (changes only). But you need to have the overall picture in mind to ensure nothing is broken and it follows the architecture.
Final Thoughts
I personally think the word "code review" is a poor choice and do not know how it got started. They could have chosen a much better and less authoritative word.

A: I vote for the second option. Juniors may may have a better "lerning curve" when doing the changes themselves.
Also: don't be the only one reviewing the code.
Let some of the experienced members of your team also look at the code and schedule a regular review meeting  where the reviewers present their findings (they made before the meeting!) to the author. This will raise the motivation of both, the juniors and the experiences team members.


text:
Q: How to get the JSON from the Body of a Request on Go I'm a newbie with Go, but so far I'm liking it very much.
I have a problem I can't figure out. I'm migrating an API from Node to Go and there is this log where I have to capture the Body of a POST AS IT IS and save it to a jsonb type column in a Postgresql database.
This means I can't use a struct or anything predetermined.
The POST is made with body raw Content-Type: application/json like so:
{
    "debug": false,
    "order_id_gea": 326064,
    "increment_id_gea": 200436102,
    "date": "2017-05-18T01:44:44+00:00",
    "total_amount": 10000.00,
    "currency": "MXN",
    "payment_method": "Referencia bancaria",
    "reference": "857374",
    "buyer": {
        "buyer_id_gea": 1234,
        "full_name": "Juan Perez Martinez",
        "email": "juanperez@gmail.com",
        "phone": "5512341234"
    },
    "products": [
        {
            "sku":"PEP16114",
            "price": 10000.00,
            "currency": "MXN",
            "student": {
                "school_id_gea": 172,
                "grade_id_gea": 119,
                "level_id_gea": 36,
                "name": "Benancio",
                "last_name": "Perez",
                "second_last_name": "Garcia",
                "email": "benancio@gmail.com"
            }
        }
    ]
}

On Node + Hapi is quite simple:
const payload = request.payload

and then I can access the JSON from payload.
I am using Go with Echo, so context is a wrapper where I can find Request() *http.Request.
I have tried the following, but everytime the result is empty or an error because it is empty:
var v interface{}
err := json.NewDecoder(context.Request().Body).Decode(&v)
if err != nil {
    return result, err
}
fmt.Println(v)

Result: EOF
--
m := echo.Map{}
if err := context.Bind(&m); err != nil {
    return result, err
}
fmt.Println(m)

Result code 400, message EOF
--
body, error := ioutil.ReadAll(context.Request().Body)
if error != nil {
    return result, error
}
fmt.Println(body)

Result []
--
What am I missing and/or doing wrong? Thanks!

A: TIL that http.Response.Body is a buffer, which means that once it has been read, it cannot be read again.
It's like a stream of water, you can see it and measure it as it passes but once it's gone, it's gone.
However, knowing this, there is a workaround, you need to "catch" the body and restore it:
// Read the Body content
var bodyBytes []byte
if context.Request().Body != nil {
    bodyBytes, _ = ioutil.ReadAll(context.Request().Body)
}

// Restore the io.ReadCloser to its original state
context.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

// Continue to use the Body, like Binding it to a struct:
order := new(models.GeaOrder)
error := context.Bind(order)

Now, you can use context.Request().Body somewhere else.
Sources:
http://grokbase.com/t/gg/golang-nuts/12adq8a2ys/go-nuts-re-reading-http-response-body-or-any-reader
https://medium.com/@xoen/golang-read-from-an-io-readwriter-without-loosing-its-content-2c6911805361

A: I believe you can do this:
m := make(map[string]interface{});
if err := context.Bind(&m); err != nil {
    return result, err
}
fmt.Println(m)


text:
Q: Populate slice of objects together with referenced objects Imagine I have 2 structs:
type Order struct {
     ID             int64 `gorm:"primary_key"`
     CurrentStateID int64
     CurrentState   *OrderState
}
type OrderState struct {
   ID      int64
   .... // other fields
}

Now I want to make a search given a slice of orderIDs and have a slice of Order with filled CurrentState fields.
My current solution is really ugly as I firstly fetch all orders without states, then arrange state ids into a slice and make a search by them. After that, I iterate in a for loop over orders and match orders and states together. Like
var (
    states []*State
    orders []*Orders
)
//searches are done here
for _, order := range orders {
    for _, state := range states {
        if order.CurrentStateID == state.ID {
             order.CurrentState = state
             break
         }
     }
}

A: If I understand you correctly, you want to eagerly load the CurrentState when fetching your Orders.
In this case, I would suggest taking a look at the Preload-API at http://jinzhu.me/gorm/crud.html#preloading-eager-loading


text:
Q: In which order should I write Javascript (Coffeescript) to get code executed in Rails 4? I can generate succesfully ajax-generate my div like this:
View:
%table#sir_table.my_table{:data => {'si-id' => "#{@si.id}", 'source' => spectrum_identification_results_url(format: "json") } }

spectrum_identification_results.js.coffee:
$ ->
  $("#sir_table").dataTable
    sPaginationType: "full_numbers"
    bJQueryUI: true
    bProcessing: true
    bServerSide: true
    sAjaxSource: $('#sir_table').data('source')

With the json object and all I manage to generate the datatable serverside processing and ajax.
That's OK . But within the ajax table I create, I need another ajax link to the show action.
The link_to remote is formatted like so:
link_to( "#{sir.sir_id}", "results/#{sir.id}", :data => {'sir-id' => "#{sir.id}"}, remote: true )

and it works alright if I remove remote: true and make it work non-ajax ...
This is the javascript I'd like it to trigger:
spectrum_identification_results.js.coffee:
$ ->
  $("a[data-sir-id]").click ->
  alert "whassup"

But it never gets executed. I think it might be related to rails4 turbolinks gem, that only triggers $(document).ready on the first load, but I am not sure.
Any clue on why is this happening and/or how could I get the javascript executed?

A: Rails automatically compiles everything in the assets directory into the head application files (e.g. application.js and application.css). I'd check and be sure that in you're application.js you have something like this:
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

And then everything should work properly if all of your JavaScript and CoffeeScript files are under the "javascripts" directory. If you don't have Sprockets setup correctly (e.g. skipping JavaScript when executing the rails new command that generated you're project), then everything won't be compiled properly.


text:
Q: Why the console still needs a passord when changing to an user that generated with --disabled-password option I was trying to create new user for my ssh connection('lenlapcon' with option '--disabled-password'), but when I tried to switch back to the default user 'ubuntu', the console requires a password.
like this:
enter image description here
What should I do to skip the password or how can I create a password-free user? Thanks.
I don't think they should ask me for a password. The sudo su should work as smoothly as when I switch from 'ubuntu'(the default one) to 'lenlapcon'(created with --disabled-password).


text:
Q: error with updatepanel and accordion I have a accordion control(using jQuery) on the page.  When I insert the contents of my page into an updatepanel, the accordion stops working.  If I remove the updatepanel, it starts working.
Why?
How can i fix this error?
Do i have to re-instantiate the accordion script/plugin, If yes then how?

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>

Dynamic Drive

            Some random content here

CSS Examples

            Some random content here

JavaScript Kit

            Some random content here

CSS Drive

           Some random content here

Coding Forums

           Some random content here

   </ContentTemplate>
</asp:UpdatePanel>

A: Use pageLoad, it gets called on all partial postbacks:
$(document).ready() and pageLoad() are not the same!

A: if all content is in update panel than just put your script in update panel and it will start working.

A: Since the entire content/definition of your accordion is inside your update panel, you will have to re-init it every time the update panel updates because you're essentailly getting a 'fresh' copy of the accordion and any events tied to it are gone.
We've had this problem too (with differnet controls) and our solution is to put the bare minimum we have to inside the update panel, like hidden buttons, and then code the accordion to 'push' those buttons so the update panel does its thing without hosing the accordion.

A: I know this is an old post but it is still unsolved.
So, here you have two issues:
The first, as pointed out by @rickschott, you need to initialize the plugin after each partial postback (not only the first time) because the plugin is inside an UpdatePanel, so it will stop working after the UpdatePanel is updated.
When you fix that, you encounter a second issue: seems that the page gets refreshing all the time, and never loads. This issue could be consider as a bug of ddaccordion jquery plugin. Seems it is not designed to be reset (or to destroy and recreate without loading the page from scratch). I did a workaround but you may have to test it:

*

*Open ddaccordion.js and find init:function(config) in it.

*Remove this four lines:

document.write('


text: Q: How I can get the checked values of drop down list into the cell of ag-grid I'm developing an application using ag-grid in angular2 and want to get the checked values of drop-down list into the cell of ag-grid.


text:
Q: Angular Performance Functions in Template vs properties. How Do I measure the performance? Is One way Faster? I need to show a message when an input is touched and invalid. There are several input where I needed to do this so I created a function: Let me re-iterate this form has SEVERAL controls on it,so I need consider re-use if possible
isInvalid = (control: AbstractControl): boolean => {
    const invalid = (control.touched && control.invalid);
    return invalid;
  }

In the HTML template I do this:
<input autocomplete="off" id="firstName" class="form-control" formControlName="firstName">
          <div *ngIf="isInvalid(firstName)"> Please enter a valid value </div>

Now of course this called the invalid function numerous times. so I tried this approach and removed the function and just called the properties on the form control.
<input autocomplete="off" id="lastName" class="form-control" formControlName="lastName">
          <div *ngIf="lastName.touched && lastName.invalid"> Please enter a valid value </div>

I can't find any way to prove that this way is better for performance.
Then I got the bright idea to extend the form control and do something like this:
export class FormControlExtended extends FormControl {

    touchedAndInvalid = false;
    constructor(formState?: any,
        validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
        asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null) {
        super(formState, validatorOrOpts, asyncValidator);

        this.statusChanges
            .subscribe(() => {
                this.markTouchAndInvalid();
            });
    }

    markAsTouched({ onlySelf }: { onlySelf?: boolean } = {}): void {
        super.markAsTouched({ onlySelf });
        this.markTouchAndInvalid();
    }

    markTouchAndInvalid = () => {
        this.touchedAndInvalid = (this.touched && this.invalid);
    }
}

and in the html I do this
<input autocomplete="off" id="lastName" class="form-control" formControlName="lastName">
          <div *ngIf="lastName.touchedAndInvalid"> Please enter a valid value </div>

My Questions:
Is one way better than the other? How could I prove it with some tool or extension that one way has better performance? Is there a better way? Am I off my rocker?

A: Not sure about performance measure's but the convention I use is a getter/setter.
this.exampleForm = this.fb.group({
  lastName: ''
});

get isValid() {
  const ctrl = this.exampleForm.get('exampleControl');
  return ctrl.touched && ctrl.invalid;
}

<input autocomplete="off" id="lastName" class="form-control" formControlName="lastName">
<div *ngIf="isValid"> Please enter a valid value </div>


text:
Q: Сложение результатов из текстового файла с помощью php Здравствуйте, есть текстовый файл с текстом и цифрами.
Задача: считать текст, сложить цифры и сохранить в другом файле.
Например, в файле написано:
ИванИвановичИвановДегтяревМеряев111100111
Нужно, чтобы php файл посчитал все единицы, и записал значения в новый текстовый файл в виде:
Иван Иванович Иванов, Дегтярев, Меряев, 7

A: <?php

$file = file_get_contents('file.txt'); //берем данные из файла

preg_match_all("/[А-Я][а-я]+/", $file, $names); //парсим ФиоФФФ
preg_match_all("/\d{1}/", $file, $numbers); //парсим цифры

$sum = 0;

//перебираем массив с цифрами
foreach($numbers[0] as $num) {
    $sum = $sum + $num; //складываем
}

//собираем данные
$data = $names[0][0].' '.$names[0][1].' '.$names[0][2].', '.$names[0][3].', '.$names[0][4].', '.$names[0][5].', '.$sum;

//записываем в новый файл
file_put_contents('new_file.txt', $data);


text:
Q: SonarQube analysis works in IDE but not in Jenkins Pipeline Which versions am I using (SonarQube, Scanner, Plugin, and any relevant extension):

*

*SonarQube 7.9.1 (on a remote server)

*Sonar maven plugin 3.7.0.1746 (in my pom.xml file)

*Jenkins 2.222.1 (local server)

*Maven 3.6.0

What am I trying to achieve:
I want to perform an analysis with a Jenkins Pipeline with my remote server
What have I tried so far to achieve this :
I have succeed to do an analysis with my IDE (intelliJ) and it works with the command :
mvn -B sonar:sonar

After that, the server note the last analysis with the Quality Gate.
Nevertheless, it does not work with my Jenkins Pipeline.
I do not understand why it works with the IDE and not with Jenkins.
I have put in my pom.xml a sonar.login which is a specific user token. This user has the right to execute an analysis on this particular project. In my ~/.m2/settings.xml, I have put the sonar.host.url.
I also tried to set up manually a SonarQube server in Jenkins (in system configuration). I put there the url and my token thanks to a secret text but it does not work to.
I have also generated a Webhook but this is for the qualitygate variable in the pipeline and I don't think it matters here.
I don't know what to test now…
Any idea ?
Thanks

A: It is ok now : I have added on a sonar installer in the settings. In addition I move the sonar.host.url from ~/.m2/settings.xml to my pom.xml file.


text:
Q: Change of Activity with Intent doesn't work and don't know why I am studying and learning Android with a YouTube tutorial, I went to change between activities, followed it step by step and it just doesn't work.
I tried the only way I find, with the Intent, some codes may vary but at the end uses Intent.
This is what I have. The Button at activity_main.xml:
<Button
                    android:id="@+id/btnNext"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:layout_constraintTop_toBottomOf="@+id/lvFood"
                    android:text="@string/btnNext" />

The Button at MainActivity.java:
Button btnNext;
btnNext = findViewById(R.id.btnNext);

The Listener of the Button:
btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent toSecond = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(toSecond);
            }
        });

Also tried this, but the same result.
Intent toSecond = new Intent (v.getContext(), SecondActivity.class);
                startActivityForResult(toSecond, 0);

My manifest file:
<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/hello"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".SecondActivity"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

The Run Log:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.helloworld, PID: 11503
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloworld/com.example.helloworld.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.example.helloworld.SecondActivity.onCreate(SecondActivity.java:19)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Edit
The code on MainActivity:
package com.example.helloworld;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Button btnSayHello, btnSayAnything, btnNext;
    TextView tvHelloWorld;
    EditText etSayAnything;
    Spinner spOptions;
    ListView lvFood;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnSayHello = findViewById(R.id.btnSayHello);
        tvHelloWorld = findViewById(R.id.tvHelloWorld);
        btnSayAnything = findViewById(R.id.btnSayAnything);
        etSayAnything = findViewById(R.id.etSayAnything);
        spOptions = findViewById(R.id.spOptions);
        lvFood = findViewById(R.id.lvFood);
        ArrayAdapter<CharSequence> spOptionsAdapter = ArrayAdapter.createFromResource(this, R.array.spOptions, android.R.layout.simple_spinner_item);
        spOptions.setAdapter(spOptionsAdapter);
        ArrayAdapter<CharSequence> lvFoodAdapter = ArrayAdapter.createFromResource(this, R.array.lvFood, android.R.layout.simple_list_item_1);
        lvFood.setAdapter(lvFoodAdapter);
        btnNext = findViewById(R.id.btnNext);

        btnSayHello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(tvHelloWorld.getVisibility() == View.INVISIBLE)
                {
                    tvHelloWorld.setVisibility(View.VISIBLE);
                }else
                {
                    tvHelloWorld.setVisibility(View.INVISIBLE);
                }
            }
        });

        btnSayAnything.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvHelloWorld.setText(etSayAnything.getText());
                etSayAnything.setText("");
            }
        });

        lvFood.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tvHelloWorld.setText(lvFood.getItemAtPosition(position).toString());
            }
        });

        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent toSecond = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(toSecond);
            }
        });
    }
}

The code on SecondActivity:
package com.example.helloworld;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class SecondActivity extends AppCompatActivity {

    Button btnBack;
    Button btnExit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent toMain = new Intent(SecondActivity.this, MainActivity.class);
                startActivity(toMain);
            }
        });
        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}

The videos I was following:

*

*https://www.youtube.com/watch?v=T1MPy8pRha8

*https://www.youtube.com/watch?v=6RtF_mbHcEc
It should take me to the activity SecondActivity, which only have two buttons, one for back to the MainActivity and one for close the app.
But, the app just stop and closes.

A: The button you are attempting the action click is not found; make sure you do this in your oncreate() of the SecondActivity.
setContentView(R.layout.your_second_activity_layout);

And also make you sure you instantiate your two button in the second activity like you did in your first activity:
btnNext = findViewById(R.id.btnNext);

Edit
After I saw your SecondActivity, you forgot:
btnback = findViewById(R.id.btnBack);
btnExit = findViewById(R.id.btnExit);

A: When you create an Android activity, you also have to define a layout that will become the activity's user interface. You bind the layout to the activity through the setContentView method, called as soon as possible on the activity's onCreate method (you have to override this method). Only after binding the layout to the activity can you start binding specific items on the layout (in this case, your button) to the appropriate objects declared in your code. If you try to bind these items before binding the layout to the activity, you'll get a null pointer instead of the actual item. Fore more information on Activities and their lifecycles, read this.
Edit:
You're not initializing your buttons. Please make sure that you have something similar to this in SecondActivity:
public class SecondActivity extends Activity {

  private Button btnBack;
  private Button btnExit;;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    btnBack = findViewById(R.id.btnBack);
    btnExit = findViewById(R.id.btnExit);

    // set the button listeners
  }
}

A: This could be caused because you try to find your button before the layout for it is created. Are you sure you are using findViewbyIdafter the onCreate (or in it) ?
Please post your whole main activity code (and the second one).
Edit: I just saw the exception is thrown at your second activity so its probably not what i said above

A: Try to always look for the words like 'Error', 'Exception', 'Caused By' in the Log report, cause in that line you will mostly find the reason of the crash.
Like in your case at the Log line number 3 it says...
Unable to start activity ...com.example.helloworld.SecondActivity

because
Attempt to invoke method Button.setOnClickListener on a null object reference

that probably means your Button btnNext is null. Why? We can't see the whole the code but I assume it is because you have not set the layout view with setContentView() inside your onCreate() method.

A: I have solved it, I forgot findViewById in my SecondActivity.


text:
Q: xmlhttp request in a node-red function node Is it possible to make http GET requests from within a node-red "function" node.
If yes could somebody point me to some example code please.
The problem I want to solve is the following:
I want to parse a msg.payload with custom commands. For each command I want to make an http request and replace the command with the response of a HTTP GET request.
expl:
msg.payload = "Good day %name%. It's %Time% in the %TimeOfDay%. Time for your coffee";

The %name%,%TimeOfDay% and %Time% should be replaced by the content of a Get request to http://nodeserver/name,..., http://nodeserver/Time.

A: thnx Hardilb,
After half a day searching I found out that the http-node can also be configured by placing a node just before it setting the
msg.url = "http://127.0.0.1:1880/" + msg.command ;
msg.method = "GET";

I used the following code to get a list of commands
var parts = msg.payload.split('%'),
len = parts.length,
odd = function(num){return num % 2;};

msg.txt= msg.payload;
msg.commands = [];
msg.nrOfCommands = 0;
for (var i = 0; i < len ; i++){
    if(odd(i)){
        msg.commands.push(parts[i]);
        msg.nrOfCommands = msg.nrOfCommands + 1;
    }
}
return msg;

A: You should avoid doing asynchronous or blocking stuff in function nodes.
Don't try to do it all in one function node, chain multiple function nodes with multiple http Request nodes to build the string up a part at a time.
You can do this by stashing the string in another variable off the msg object instead of payload.
One thing to looks out for is that you should make sure you clear out msg.headers before each call to the next http Request node


text:
Q: NGSPICE dc simulation error I want to do dc simulation of differential amplifier circuit, and this is my .cir file looks like:

When i run simulation, ngspice give me an erorr:
Supplies reduced to   0.1000% Warning: singular matrix:  check nodes vin1 and vin1
Supplies reduced to   0.0000% Warning: singular matrix:  check nodes vin1 and vin1
Warning: source stepping failed
doAnalyses: iteration limit reached
run simulation(s) aborted

A: Your input voltage source (V4) is floating.
There is no path to provide it a reference to the ground node That makes the problem singular.


text:
Q: Redirect non-www requests to www URLs in Ruby on Rails It is a simple issue, but I can't seem to find an answer doing some quick googling.
What's the Ruby on Rails way of doing this 301 direct (http://x.com/abc > http://www.x.com/abc). A before_filter?

A: For rails 4, use it -
  before_filter :add_www_subdomain

  private
  def add_www_subdomain
    unless /^www/.match(request.host)
      redirect_to("#{request.protocol}www.#{request.host_with_port}",status: 301)
    end
  end

A: While John's answer is perfectly fine, if you are using Rails >= 2.3 I would suggest to create a new Metal. Rails Metals are more efficient and they offers better performance.
$ ruby script/generate metal NotWwwToWww

Then open the file and paste the following code.
# Allow the metal piece to run in isolation
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)

class NotWwwToWww
  def self.call(env)
    if env["HTTP_HOST"] != 'www.example.org'
      [301, {"Content-Type" => "text/html", "Location" => "www.#{env["HTTP_HOST"]}"}, ["Redirecting..."]]
    else
      [404, {"Content-Type" => "text/html"}, ["Not Found"]]
    end
  end
end

Of course, you can customize further the Metal.
If you want to use Apache, here's a few configurations.

A: There is a better Rails 3 way - put this in your routes.rb file:
  constraints(:host => "example.com") do
    # Won't match root path without brackets around "*x". (using Rails 3.0.3)
    match "(*x)" => redirect { |params, request|
      URI.parse(request.url).tap { |x| x.host = "www.example.com" }.to_s
    }
  end

Update
Here is how to make it domain agnostic:
  constraints(subdomain: '') do
    match "(*x)" => redirect do |params, request|
      URI.parse(request.url).tap { |x| x.host = "www.#{x.host}" }.to_s
    end
  end

A: Ideally you'd do this in your web server (Apache, nginx etc.) configuation so that the request doesn't even touch Rails at all.
Add the following before_filter to your ApplicationController:
class ApplicationController < ActionController::Base
  before_filter :add_www_subdomain

  private
  def add_www_subdomain
    unless /^www/.match(request.host)
      redirect_to("#{request.protocol}x.com#{request.request_uri}",
                  :status => 301)
    end
  end
end

If you did want to do the redirect using Apache, you could use this:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.x\.com [NC]
RewriteRule ^(.*)$ http://www.x.com/$1 [R=301,L]

A: An alternative solution might be to use the rack-canonical-host gem, which has a lot of additional flexibility.  Adding a line to config.ru:
use Rack::CanonicalHost, 'www.example.com', if: 'example.com'

will redirect to www.example.com only if the host matches example.com. Lots of other examples in the github README.

A: I found this article when trying to achieve the opposite (www to root domain redirection).
So I wrote the piece of code that redirects all pages from www to the root domain.

A: You can try the below code -
location / {
  if ($http_host ~* "^example.com"){
    rewrite ^(.*)$ http://www.example.com$1 redirect;
  }
}


text:
Q: SQLiteStudio can I see the SQLite query generated by clicking options? I use the wizard in "Tools" (SQLiteStudio 3.2.1, circa June 2019) to import a csv file into a table. I need to repeat the task a few (5) dozen times and I want to submit a query instead of pointing and clicking each time.

A: Unfortunately there is no way to get these SQL statements, but there is something else that may be useful to you.
You can use SQL function available from SQLiteStudio: import() as described at https://github.com/pawelsalawa/sqlitestudio/wiki/User_Manual#built-in-sql-functions
For example:
SELECT import('my_file.txt', 'CSV', 'target_table');

This is much easier to repeat.


text:
Q: How to create Azure on demand HD insight Spark cluster using Data Factory I am trying to use Azure Data factory to create an on demand HD insight Spark cluster using Hdi Version 3.5. The data factory is refusing to create with an error message

HdiVersion:'3.5' is not supported

If currently there is no way of creating an on Demand HD insight spark cluster, then what is the other sensible option? It seems very strange to me why Microsoft hasn't added an on Demand HD insight Spark Cluster to the Azure Data factory.

A: Here is a full solution, which uses ADF to schedule a Custom .NET activity in C#, which in turn uses the ARM templates, and SSH.NET to execute the command which runs the R script.
So, ADF is used to schedule the .NET Activity, the Batch service is used to run the code in the dll, then the json template file for the HDInsight cluster is sored in blob and can be configured as needed.
The full description is in the article "Automating Azure: Creating an On-Demand HDInsight Cluster", but here is the C# code which is the essence of the automation (everything else is just admin work to setup the bits):
using System;
  using System.Collections.Generic;
using Microsoft.Azure.Management.DataFactories.Models;
using Microsoft.Azure.Management.DataFactories.Runtime;

using Microsoft.Azure.Management.ResourceManager.Fluent;

using Microsoft.Azure.Management.ResourceManager.Fluent.Core;

 using Renci.SshNet;

 namespace VM

 {
  public class StartVM : IDotNetActivity
  {
      private IActivityLogger _logger;
      public IDictionary<string, string> Execute(
          IEnumerable<LinkedService> linkedServices,
          IEnumerable<Dataset> datasets,
          Activity activity,
          IActivityLogger logger)
      {
          _logger = logger;
          _logger.Write("Starting execution...");
          var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
               "" // enter clientId here, this is the ApplicationID
               , "" // this is the Application secret key
               , "" // this is the tenant id
               , AzureEnvironment.AzureGlobalCloud);
          var azure = Microsoft.Azure.Management.Fluent.Azure
              .Configure()
              .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
              .Authenticate(credentials)
              .WithDefaultSubscription();
          var groupName = "myResourceGroup";
          var location = Region.EuropeNorth;
          // create the resource group
          var resourceGroup = azure.ResourceGroups.Define(groupName)
              .WithRegion(location)
              .Create();
          // deploy the template
          var templatePath = "https://myblob.blob.core.windows.net/blobcontainer/myHDI_template.JSON";
          var paramPath = "https:// myblob.blob.core.windows.net/blobcontainer /myHDI_parameters.JSON";
          var deployment = azure.Deployments.Define("myDeployment")
              .WithExistingResourceGroup(groupName)
              .WithTemplateLink(templatePath, "0.9.0.0") // make sure it matches the file
              .WithParametersLink(paramPath, "1.0.0.0") // make sure it matches the file
              .WithMode(Microsoft.Azure.Management.ResourceManager.Fluent.Models.DeploymentMode.Incremental)
              .Create();
    _logger.Write("The cluster is ready...");
          executeSSHCommand();
          _logger.Write("The SSH command was executed...");
          _logger.Write("Deleting the cluster...");
          // delete the resource group
          azure.ResourceGroups.DeleteByName(groupName);

          return new Dictionary<string, string>();
      }
      private void executeSSHCommand()
      {
          ConnectionInfo ConnNfo = new ConnectionInfo("myhdi-ssh.azurehdinsight.net", "sshuser",
              new AuthenticationMethod[]{
              // Pasword based Authentication
              new PasswordAuthenticationMethod("sshuser","Addso@1234523123"),
              }
          );
          // Execute a (SHELL) Command - prepare upload directory
          using (var sshclient = new SshClient(ConnNfo))
          {
              sshclient.Connect();
              using (var cmd = sshclient.CreateCommand(
                  "hdfs dfs -copyToLocal \"wasbs:///rscript/test.R\";env -i R CMD BATCH --no-save --no-restore \"test.R\"; hdfs dfs -copyFromLocal -f \"test-output.txt\" \"wasbs:///rscript/test-output.txt\" "))
              {
                  cmd.Execute();

              }
              sshclient.Disconnect();
          }
      }
  }

  }

Good luck!
Feodor

A: I'm afraid that on-demand Spark isn't currently supported, but it's definitely in the roadmap. Please stay tuned.
As a workaround for now, you may try ADF CustomActivity to create / delete Spark cluster with your custom code.

A: Azure currently doesn't support On Demand HDInsight cluster creation for Spark activity. Since you are asking for workaround, here is what I do:

*

*Bring HDInsight cluster up using Powershell automation & scheduling (runbooks), takes about 20 mins for HDI to be ready.

*Submit Spark batch job from Data Factory, about 30 mins later than HDI schedule.

*Delete HDI cluster after 30 mins - 1 hour of expected job finish time.

Lots of work for simple task I know, but works for now.


text:
Q: Why do maintenance plans exist as a feature? Do maintenance plans provide any functionality beyond their component parts? It would seem that the only value added is the convenience of grouping subplans into logical bundles, and the simplified GUI for creation. All the actual work is being done by the underlying SSIS tasks which are being scheduled as agent jobs. Is there anything more to it than that?

A: Underlying SSIS task that do not require SSIS to be installed to run, nor require you to edit via BIDS or SSDT-BI.
They are there more or less for easy deployment of basic database maintenance that does not require much knowledge to build. Is it something that fits any environment? I would say no, it is mostly for the one man/woman shops that just need something up and running quickly and is sufficient.
Now that is not to say in large environments maintenance plans don't have a purpose, just find they may not used as often. You might consider them a stepping stone to SSIS packages.


text:
Q: Upper/lower bounds don't work as I expect, can not understand why Here is the code. As a result I get "4 4". Don't understand why it is not "2 4" (according to lower and upper bounds' defenitions).
#include <bits/stdc++.h>
using namespace std;
int main()
{
    vector<int> v = {1, 2, 4, 5};
    vector<int>::iterator s , f;
    s = lower_bound(v.begin(), v.end(), 3);
    f = upper_bound(v.begin(), v.end(), 3);
    cout << (*s) << " " << (*f);
    return 0;
}

A: From std::lower_bound:

Returns an iterator pointing to the first element in the range
  [first,last) which does not compare less than val.

The first element (from the beginning of the vector) which is not less than 3 is 4 and hence lower_bound returns 4.
From std::upper_bound:

Returns an iterator pointing to the first element in the range [first,last) which compares greater than val.

The first element (from the beginning of the vector) which is greater than 3 is 4 and hence upper_bound returns 4.
The reason for this confusion is because upper_bound returns the first element that is greater than the given value, so by symmetry we expect lower_bound to return the last element (from the beginning of the vector) that is less than the given value. But alas, the std function doesn't obey this "expected" symmetry.

A: It would be easier to understand/remember what std::lower_bound() and std::upper_bound() return knowing that std::equal_range() returns a pair of iterators, where the first one is equal to what std::lower_bound() returns, and the second one is equal to what std::upper_bound() returns.
So, here are different cases when they are called with a parameter of 4:
1 2 3 4 4 4 4 5 E
      |       |
      F       S    - first points to the first element, second to the one behind last, representing range which contains 4

1 2 3 4 5 E
      | |
      F S  same for one element

1 2 3 4 E
      | |
      F S  same as before, but 4 is the last element

1 2 3 5 E
      |
      F==S  first == second, which means range for elements equal to 4 is empty

1 2 3 E
      |
      F==S same as before but there is no element greater than 4

Where E means what container.end() returns - an iterator behind the last element.

A: The naming of lower_bound and upper_bound is unfortunate as it invites confusion. The names refer to the results when searching through a sequence that has multiple elements that are exactly equivalent to the one you're searching; lower_bound returns the iterator to the start, and upper_bound returns one past the end.
When the element isn't part of the sequence, they both return an iterator to the first element greater than the one you were searching for. This might be the end iterator if there are none greater.


text:
Q: swift ios check if local notification is dismissed I need to find if user dismissed the notification by clearing from lock screen or closing on notification bar.
Is there a way to detect it or any handler that would trigger after dismiss?

A: I have extensively looked into it and there's no exact way to tell as the notification centre lies outside of app sandbox and apple sends no notification either.
So it's not possible up until now


text:
Q: Scalar vs List Assignment Operator Please help me understand the following snippets:

*

*my $count = @array;

*my @copy = @array;

*my ($first) = @array;

*(my $copy = $str) =~ s/\\/\\\\/g;

*my ($x) = f() or die;

*my $count = () = f();

*print($x = $y);

*print(@x = @y);

A: [This answer is also found in table format here.]
The symbol = is compiled into one of two assignment operators:

*

*A list assignment operator (aassign) is used if the left-hand side (LHS) of a = is some kind of aggregate.

*A scalar assignment operator (sassign)  is used otherwise.

The following are considered to be aggregates:

*

*Any expression in parentheses (e.g. (...))

*An array (e.g. @array)

*An array slice (e.g. @array[...])

*A hash (e.g. %hash)

*A hash slice (e.g. @hash{...})

*Any of the above preceded by my, our or local
There are two differences between the operators.
Context of Operands
The two operators differ in the context in which their operands are evaluated.

*

*The scalar assignment evaluates both of its operands in scalar context.
  # @array evaluated in scalar context.
  my $count = @array;

*The list assignment evaluates both of its operands in list context.
  # @array evaluated in list context.
  my @copy = @array;

  # @array evaluated in list context.
  my ($first) = @array;

Value(s) Returned
The two operators differ in what they return.

*

*The scalar assignment ...

*

*... in scalar context evaluates to its LHS as an lvalue.
  # The s/// operates on $copy.
  (my $copy = $str) =~ s/\\/\\\\/g;

*... in list context evaluates to its LHS as an lvalue.
  # Prints $x.
  print($x = $y);

*The list assignment ...

*

*... in scalar context evaluates to the number of scalars returned by its RHS.
  # Only dies if f() returns an empty list.
  # This does not die if f() returns a
  # false scalar like zero or undef.
  my ($x) = f() or die;

  # $counts gets the number of scalars returns by f().
  my $count = () = f();

*... in list context evaluates to the scalars returned by its LHS as lvalues.
  # Prints @x.
  print(@x = @y);


text:
Q: Assign a row from an old dataframe to a new one only if the "if" condition is verified I'm trying to work on a dataframe on R about banks for my thesis!
In particular I have to select some rows from my dataset.

*

*First I check if there are 2 equal name in the column "company name"

*Second I check which is the "consolidation code" in the column

*Lastly, depending on the consolidation code, I try to assign the row of my dataset to a new dataset.

The last point is the one where I'm having problems.. I think I'm following all the instructions from how to assign a row to a dataset, but still cannot find a solution and I hope you can help me!
data <- data.frame()
for (i in 1:nrow(total)) {
  for (j in 2:nrow(total)){
    if(total$Company_name[i]==total$Company_name[j] & total$Consolidation_code[i] == "U2")
       {data <- total[i,]}
    else if (total$Company_name[i]==total$Company_name[j] & total$Consolidation_code[i] == "C2")
       {data <- total[i,]}
    else if (total$Company_name[i]==total$Company_name[j] & total$Consolidation_code[i] == "C1")
       {data <- total[i,]}
    else if (total$Company_name[i]==total$Company_name[j] & total$Consolidation_code[i] == "U1")
       {data <- total[i,]}
                       }
                     }

This is the code I wrote.. please let me know if you can spot my mistake and let me know if you know an easier way to code my problem.
Thanks in advance.
UPDATE now this code works, but it only assign 1 row to the new dataset.. can you spot the problem?


text:
Q: Automatic Update IoT Core Application I would like to build a C# application that would update itself on a RaspberryPi using Windows IoT Core. I've done this before in NodeJs on Linux using a repo in the cloud, the app was simply re-writing itself.
Is there such a feature already implemented on the IoT Core or in Azure or do I need to program my own solution?
I won't have physical access to the device or it's network once it is deployed.

A: we are in precisely the same situation. There is nothing yet at the level that can be found, for example, in debian. However, there are preview (very early) options in the iot-hub space moving in this direction. Also, you can create a custom image and have it updated from the windows store via the oem program (currently costs around 70 $/year). We are investigating both and, in the meantime, have written our own over-air-update. However, our custom update is now being hindered by the automatic updates of iot-core. Here is the thread with the current "play-by-play" as far as I can see. Hope this helps!


text:
Q: How to wait result from OKHTTP response without freezing app Kotlin? I am writing a small application in Kotlin with JetpackCompose and my application freezes (CountDownLatch) when a request is called, is there any way to avoid this?
Without CountDownLatch, okhttp does not have time to return the result before the method completes.
MainActivity.kt
fun infoServer() {

    val viewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)

    var txt = remember {
        mutableStateOf(0)
    }

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier.fillMaxWidth()
    ) {
        Row(
            horizontalArrangement = Arrangement.Center,
            modifier = Modifier
                .padding(10.dp)
        ) {
            Text(
                text = "Player Count ",
                style = MaterialTheme.typography.body1
            )
            Text(
                text = txt.value.toString(),
                style = MaterialTheme.typography.body1,
                fontWeight = FontWeight.Bold
            )
        }
        Row(horizontalArrangement = Arrangement.Center) {
            eveButton(
                text = "Update",
                onClick = ({
                    viewModel.updatePlayerCount()
                    txt.value = viewModel.res
                }),
                modifier = Modifier
                    .padding(10.dp)
            )

            eveButton(
                text = "Clear",
                onClick = ({
                    txt.value = 0
                }),
                modifier = Modifier
                    .padding(10.dp)
            )
        }
    }
}

MainActivityViewModel.kt
class MainActivityViewModel : ViewModel() {

    var res = 0

    fun updatePlayerCount() {
        res = MainActivityModel().updateServerPlayers()
    }
}

MainACtivityModel.kt
class MainActivityModel {

    var result = 0

     fun updateServerPlayers(): Int {

         val client = OkHttpClient().newBuilder()
             .connectTimeout(10, TimeUnit.SECONDS)
             .writeTimeout(10, TimeUnit.SECONDS)
             .callTimeout(10, TimeUnit.SECONDS)
             .readTimeout(10, TimeUnit.SECONDS)
             .retryOnConnectionFailure(true)
             .build()

         val request = Request.Builder()
             .url("https://esi.evetech.net/latest/status/?datasource=tranquility")
             .method("GET", null)
             .build()

         var countDownLatch = CountDownLatch(1)

         client.newCall(request).enqueue(object : Callback {
             override fun onFailure(call: Call, e: IOException) {
                 Log.d("Error Connection", e.toString())
             }

             override fun onResponse(call: Call, response: Response) {
                 response.use {
                     if (!response.isSuccessful) throw IOException("Error $response")

                     try {
                         var json =JSONObject(response.body!!.string())

                         countDownLatch.countDown()

                         result = json.getInt("players")
                     }
                     catch (e: Exception) {
                         Log.d("OKHTTP", e.toString())
                     }
                 }
             }
         })

         countDownLatch.await()

         Log.d("OKHTTP2", result.toString())
         return result
    }
}


text:
Q: Python Selenium Select Drop Down Menu Option I'm trying to get forms filled out on this auction website. Right now I need to figure out how to select the option on a hover-menu. I tried looking at other questions here but they all had XPATH or CSS as ways for identifying the sub menu option. I can't inspect the option with my browser and I would appreciate any insights!

What the code for for the Assignment button:

HTML 2 - when I hover over "Add Auction Assignment" it seems like it makes something called a javascript pop up, but I don't know.
Below is the code I have so far and the approach I attempted. It does find the assignment button and it does hover over it but it always times out.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import Select

browser = webdriver.Chrome("C:\Program Files\chromedriver_win32/chromedriver.exe")

actions = ActionChains(browser)

#Go to the desired website
browser.get("http://www.autoims.com/external/index.jsp")

usrname_box = browser.find_element_by_xpath('//*[@id="loginUsername"]')
pw_box =  browser.find_element_by_xpath('//*[@id="password"]')
login_button =  browser.find_element_by_xpath('//*[@id="submit"]')

#login process here

wait = WebDriverWait(browser, 10)

for vin in df['VIN']:
    assignments = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="_img0"]')))
    ActionChains(browser).move_to_element(assignments).perform()

    add_assignment = wait.until(EC.visibility_of_element_located((By.XPATH, "  HELP :(  "))) #always fails
    ActionChains(browser).move_to_element(add_assignment).click().perform()

A: did you try to find the html code of sub menu from the end of page souce,
for some JQuery navbar plugin,
it append the html code of sub menu to the end of body tag.
you can scroll down to the end of page source firstly, then hover on the Assignment menu, meanwhile watch any new html code appended or any html code
change.
only when we see the html code of sub menu, we can know how to locator
it in script.


text:
Q: In Ruby, why does !nil return => true? If you do this:
    $ nil
    => nil

But if you do this:
    $ !nil
    => true

Why is !nil true?

A: The ! operator is unary boolean NOT. It will return true if its operand is nil or false. Otherwise it will return false.
!nil # => true
!false # => true
!Object.new # => false

In boolean expression Ruby always consider nil and false as false and all the rest values as true.

A: When you use a boolean operator like ! on an object in Ruby the object must first be converted, behind the scenes, to a boolean value (true or false). Every object in Ruby is either "truthy" or "falsy," and Ruby's implementors have chosen for nil to be falsy, so !nil is equivalent to !false, which evaluates to true.

A: Because in general, comparisons, nil is regarded as false, so, if you do:
if something_that_returns_nil
  puts "did not return nil"
else
  puts "returned nil"

You would expect it to have the inverse behavior if it was:
if !something_that_returns_nil
  puts "did return nil"
else
  puts "did not return nil"

So, when you "invert" nil it becomes false as there isn't an specific object that represents not_being_nil (as not being nil is any value in Ruby).


text:
Q: Why is there no semicolon after a macro call? I am following some tutorial I found on Rust, and I ran across something that my Java/C/C++ mind cannot comprehend:
impl fmt::Display for Matrix {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}, {})\n({}, {})", self.0, self.1, self.2, self.3)
    }
}

I don't understand the lack of semicolon at the end of the write! macro call. I get an error from the compiler if I add it.
I am guessing that if the semicolon is not there then the Result from write! is used as return value of fmt, but can anybody provide a more specific explanation to why that is and if it always applies?

A: The write macro uses the write_fmt() method either from std::fmt::Write or from std::io::Write; both return Result<(), Error> and you need to omit the semicolon in order to have it as the output of fmt().
from The Rust Book, 1st edition:

Rust functions return exactly one value, and you declare the type
after an 'arrow', which is a dash (-) followed by a greater-than sign
(>). The last line of a function determines what it returns. You'll
note the lack of a semicolon here. If we added it in we would
get an error.
This reveals two interesting things about Rust: it is an
expression-based language, and semicolons are different from
semicolons in other 'curly brace and semicolon'-based languages.


text:
Q: How can I copy, recursive directory, only files with a attribute 1, and reset this a attribute to 0? How can I copy, recursive directory,
only files with a attribute 1,
and reset this a attribute to 0?
Thanks, Francisco

A: You will probably have to install the package attr if you want to set and get extended attributes.
You can write a script in a shell language, or a higher level language to descend directories and examine each file, copying the ones that meet your criteria. I would use python, personally.
By using the getfattr command you can retrieve the value for a user.name you define yourself as an extended attribute. After copying the file you could then set a different value by executing the setfattr command.
I don't see an option for rsync or dump to do this. Dump is said to ignore files with the d (non-extended) attribute set. These regular attributes are set with chattr and attributes are examined with lsattr. These commands also include setting a version for a file, in case that can be used as a substitute for the bit setting/clearing you are asking about. I suppose you could make the version alternate between 0 and 1 if you like. See man chattr and man lsattr and, in particular, the -v option.
The legacy dump command appears to use a file (/var/lib/dumpdates) of its own to keep track of what has been backed-up when so it can backup incrementally, which may be the sort of thing you are getting at.
It may be helpful to know more about what you are trying to achieve in case there is another approach that doesn't involve programming.


text:
Q: Arrays Program Debugging I am having a problem with debugging my program, the instructor said you only need to turn on or off the lines by using "#" or the comment sign in order for the program works. It is all about simple array in python only. Please help thank you
numbers = [10,20,300,40.5,50]

#random indexing --> O(1) get items if we know the index !!!
print(numbers[4]);

numbers[1] = 'Adam';

print(numbers[1]);

for num in numbers:
    print(num);

for i in range(len(numbers)):
    print(numbers[i]);

print(numbers[:-2]);

#O(N) search running time
maximum = numbers[0];
for num in numbers:
    if num > maximum:
        maximum = num;

print(maximum);

A: comment out numbers[1] = 'Adam' so that you can do numerical comparison in the looping part.
Btw you don't need ";" in python

A: Your program has error when 'Adam' compared with maximum. You must add checking if num not str, or you must add # to line: numbers[1] = 'Adam' to solve this problem


text:
Q: Probability that $m$ of $n$ elements is in set of $p$ elements Let say I have $n$ elements $X = \{x_1, ..., x_n\}$ and that I have 2 random subsets $X_1 = \{x_1', ..., x_m'\} \subset \{x_1, ..., x_n\}$ and $X_2 = \{x_1', ..., x_p'\} \subset \{x_1, ..., x_n\}$ with $m < p$.
My question is: 'What is the probability that 2 elemnts of $X_1$ are also present in $X_2$.
It is a long time ago that I did such things. I know that I certainly need combinations (https://en.wikipedia.org/wiki/Combination) but I can get to the solution. Can anyone help me?

A: If it is exactly 2 elements, the probability is :
$$\frac{\binom{n}{2}\binom{n-2}{m-2}\binom{n-m}{p-2}}{\binom{n}{p}\binom{n}{m}} $$
Since $\binom{n}{p}\binom{n}{m}$ is the number possibilities to make two sets of $p$ and $m$ elements out of a set of $n$ elements (since $\binom{n}{p}$ is the number of ways to get a set of $p$ elements out of a set of $n$ elements, and $\binom{n}{m}$ is the number of ways to get a set of $m$ elements out of a set of $n$ elements).
Then, I peak two elements that will be in both sets : $\binom{n}{2}$ possibilities ; for choosing the rest of the elements of the set of cardinal $m$ : $\binom{n-2}{m-2}$ possibilities and for choosing the rest of the elements of the set of cardinal $p$ (two are already chosen and I can't peak in the $m$ elements already chosen since I want EXACTLY 2 elements in common) : $\binom{n-m}{p-2}$ possibilities.
Now if I want to know the probabilities of at least to elements in common, it is equal to : 1- probability of 0 element in common - probability of exactly one element in common. So, with the same method, this probability is :
$$ 1- \frac{\binom{n}{m}\binom{n-m}{p}}{\binom{n}{p}\binom{n}{m}}-\frac{\binom{n}{1}\binom{n-1}{m-1}\binom{n-m}{p-1}}{\binom{n}{p}\binom{n}{m}}= 1- \frac{ \binom{n-m}{p}}{\binom{n}{p}}-n\frac{\binom{n-1}{m-1}\binom{n-m}{p-1}}{\binom{n}{p}\binom{n}{m}}$$


text:
Q: Is there a method in dojo 1.6 to get the current page for dojox.grid.EnhancedGrid? My first question, please be kind.
I'm using the Enhanced Grid's pagination plugin and I cannot find how to get the handle on the current page.
For example:
I am on page 3 of 10 pages, i want to store this page number in my cookie so that when I return to the grid it will automatically scroll to the page and highlight the row.
Thanks in advance.

A: The following code will give you the current page of grid.
grid.plugin('pagination')._currentPage


text:
Q: Failure to sync ExtJS store with Yii model on server: 400 Bad Request (POST) I want to sync my ExtJS store with Yii models on server. The reading goes smooth, but the writing to the server is not smooth: 400 Bad request (POST).
 The response goes: "You are not authorized to perform this request." The data are indeed formed in the POST:
Form Data
records:{"article":"YD40516","oem":"3397004667","title":"\u0429\u0435\u0442\u043a ...
In the store constructor:
this.proxy =
        {
            url:  "index.php?r=backend/index&Table=" + this.modelName + this.params,
            reader: {
                 root: "data",
                 totalProperty: "count",
                 type: "json"
            },
            writer: {
                 root: "records",
                 encode: true,
                 writeAllFields : false,
                //type: "json"
            },
            type:"ajax",
            // limitParam: this.limitParam,
        };

I've followed this post on how to add csrfToken to my POST ajax requests, yet it brought no result.
Still 400 Bad request, no Yii_CSRF_TOKEN post parameter added, though in the source-html there is this insertion:
 $.ajaxSetup({
     data: {"YII_CSRF_TOKEN": "63f62ed9c92752fab910386195d84eb8b0bbd420"},
     cache:false
 });

I've tried to add method redefinig to the proxy config but useless:
actionMethods: {
   read: 'GET', write: 'GET'
},

still for writing it goes POST without Yii_CSRF_TOKEN
Any help, any direction?

A: i've done it with setting extra parameter in store proxy:
this.proxy =
        {
            url:  "index.php?r=backend/index&Table=" + this.modelName + this.params,
            reader: {
                ...
            },
            actionMethods: {
                  read: 'GET', update: 'POST'
            },
            extraParams: {YII_CSRF_TOKEN : CSRF_TOKEN },
            writer: {
                 root: "records",
                 encode: true,
                 type: "json"
            },
            type:"ajax",
        };

but the trick was to insert CSRF_TOKEN as js variable.
So i used the layout file to manually insert CSRF_TOKEN in html BEFORE registered ExtJS js files:
In layout file i've inserted:
echo "<script language='javascript'>
     var CSRF_TOKEN = '" . Yii::app()->request->getCsrfToken() . "';
     console.log('CSRF_TOKEN = '+ CSRF_TOKEN);
</script>";

In a view file the js script pertaining to the store:
<?php Yii::app()->clientScript->registerScriptFile("js/UniversalStore.js"); ?>


text:
Q: Export a CSV from MODx? I have someone with a TON of database entries (similar to wordpress posts) in their MODx site. Can I export that in a CSV?

A: In MODX Evolution there is a native backup component that will export in MySQL format, but not CSV.
The simplest way to achieve this is to use phpMyAdmin and export your database to CSV (or Excel, or whatever format you want) from there.


text:
Q: Does JS support multi-threading now? I was perusing some answers but they were very old. Does somebody know about the latest development in this regard?
Also is there any chance that JS will become multi-threaded in the near future?
Related Question:-
link


text:
Q: Define 2 SLA's in an assignment in pega Hi all i have a requirement, I have Two Work Objects(WO): WO-A and WO-B in work basket both of them are different types. I need to define sla for as soon as deadline is finished WO-A should be approved automatically and WO-B should notify manager. Both are in same assignment.

A: One way of implementing this is using 1 SLA and create When rules to check the type of your Work Object and then conditionally do specifice actions. This can be done in either the Goal, Deadline or Post Deadline configurations of your SLA rule.  Check my example below in screenshot.


text:
Q: NotifyIcon icon looks terrible Using Windows Forms, I have a notification popup with the following code:
Notify.BalloonTipText = String.Format("Test 0", "Test 1", "Test 2", "Test 3");
Notify.Visible = true;
Notify.Icon = Properties.Resources.busy;
Notify.BalloonTipIcon = ToolTipIcon.None;
Notify.ShowBalloonTip(5000);

The resulting image looks terrible.

It doesn't seem to care that the icon has the correct dpi inside it.  It seems to always select the smallest and size it upwards, clearing the alpha channel to 0 at the same time.
I read about applications having to be DPI aware but I'm not sure how to do that with Windows Forms, or how to get it to load the most appropriate icon size.


text:
Q: Get Current Session When don't have the request object I'm having a problem with function calculate total user.
Inside database, I have a field login to check user logged or not.
I have a class SessionListener to check if session is destroyed and I'll update the status of the user of session.
The problem is when user logout by close brower and login again. I have two session one session keep current user and one keep user_logout. I check if current_user and user_logout have the same ID, I won't update status of the user. The problem is how can I check the current session to get the current_user?
Ex:
- User A login -> a session:111 create and keep user A(status login)

*

*User A logout by closing browser -> session:111 wait for one minutes to be destroyed.

*User A login again -> a session:222 create and keep user A

*session:111 destroyed and update_status of user A (status logout) but actually user A not logout.
Thanks so much.


text:
Q: add leading zeros to a list of numbers in Python I am new to Python. I am trying to adjust the format of a list which looks like below:
data=[1,10,313,4000,51234,123456]

and I would like to convert them to a list of strings with leading zeros:
result=['000001','000010','000313','004000','051234','123456']

each of the element has 6 digits.
I know for a single number X, I can do:
str(X).zfill(6)

but I am not sure how to apply this to a list. I would like to solve this problem without using a for loop.
Anyone could help? Thanks.

A: Apply the same zfill function in a list comprehension, like this
>>> [str(item).zfill(6) for item in data]
['000001', '000010', '000313', '004000', '051234', '123456']

Alternatively, you can use the string's format method, with format specifiers, like this
>>> ["{:06d}".format(item) for item in data]
['000001', '000010', '000313', '004000', '051234', '123456']

If you are going to do the formatting more often, then you can store that in a variable, like this
>>> formatter = "{:06d}".format
>>> [formatter(item) for item in data]
['000001', '000010', '000313', '004000', '051234', '123456']

If you are using Python 2.x, then you can use map and the formatter function, like this
>>> map(formatter, data)
['000001', '000010', '000313', '004000', '051234', '123456']

If you are using Python 3.x, map returns an iterable map object. So, you need to explicitly create a list, like this
>>> list(map(formatter, data))
['000001', '000010', '000313', '004000', '051234', '123456']


text:
Q: Combine recorded video and background music in iOS In my application I want to record a video with music playing in background. I have achieved this through AVCaptureSession and AVAudioSession.
After recording (through headset) my music output will only contain the recorded video sound. Is there any way to combine the music playback with the recorded video so that the final output will contain the music playback + recorded video with sound
I have gone through the following question : StackOverflow and added the below codes in my viewDidLoad but no change in volume.
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord  withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];

But no change on the final result.


text:
Q: Is there a way to run a function on something after it is written (python) I am creating a tkinter app with python, and I am faced with a problem.
from   tkinter import *
import math

root = Tk()
root.title("PyCalc")
root.resizable(False, False)

inpbox = Entry(root, width=40, borderwidth=5, font=("Courier New", 16))
inpbox.grid(row=0, column=0, columnspan=5, padx=0, pady=10)

def clicked(num):
    inpbox.focus()
    if num == 'C': inpbox.delete(0, END)
    elif num == '=':
        inpbox.icursor(END)
        text = inpbox.get().replace('√', "math.sqrt").replace('^', '**')
        inpbox.delete(0, END)
        try: num = eval(text)
        except: inpbox.insert(END, '?')
        else:
            try: inpbox.insert(inpbox.index(INSERT), float(num))
            except: inpbox.insert(END, '?')
    elif num == 'B':
        inpbox.delete(inpbox.index(INSERT)-1, inpbox.index(INSERT))
    else: inpbox.insert(inpbox.index(INSERT), num)

inpbox.focus()
button00 = Button(root, text='00', padx=17, pady=20, font=("Courier New", 32), command=lambda: clicked('00'))
button0 = Button(root, text='0', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('0'))
button1 = Button(root, text='1', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('1'))
button2 = Button(root, text='2', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('2'))
button3 = Button(root, text='3', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('3'))
button4 = Button(root, text='4', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('4'))
button5 = Button(root, text='5', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('5'))
button6 = Button(root, text='6', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('6'))
button7 = Button(root, text='7', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('7'))
button8 = Button(root, text='8', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('8'))
button9 = Button(root, text='9', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('9'))
buttonplus = Button(root, text='+', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('+'))
buttonsub = Button(root, text='-', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('-'))
buttonmult = Button(root, text='*', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('*'))
buttondiv = Button(root, text='/', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('/'))
buttonsqr = Button(root, text='√', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('√('))
buttonsq = Button(root, text='x²', padx=17, pady=20, font=("Courier New", 32), command=lambda: clicked('^2'))
buttonpow = Button(root, text='xⁿ', padx=17, pady=20, font=("Courier New", 32), command=lambda: clicked('^'))
buttoneq = Button(root, text='=', padx=91, pady=20, font=("Courier New", 32), command=lambda: clicked('='))
buttonc = Button(root, text='C', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('C'))
buttonb = Button(root, text='Õ', padx=11, pady=20, font=("Wingdings", 31), command=lambda: clicked('B'))
buttonfact = Button(root, text='x!', padx=17, pady=20, font=("Courier New", 32), command=lambda: clicked('!'))
buttonlp = Button(root, text='(', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked('('))
buttonrp = Button(root, text=')', padx=30, pady=20, font=("Courier New", 32), command=lambda: clicked(')'))

buttonsq.grid(row=1, column=4)
buttonplus.grid(row=1, column=3)
button9.grid(row=1, column=2)
button8.grid(row=1, column=1)
button7.grid(row=1, column=0)

buttonpow.grid(row=2, column=4)
buttonsub.grid(row=2, column=3)
button6.grid(row=2, column=2)
button5.grid(row=2, column=1)
button4.grid(row=2, column=0)

buttonsqr.grid(row=3, column=4)
buttonmult.grid(row=3, column=3)
button3.grid(row=3, column=2)
button2.grid(row=3, column=1)
button1.grid(row=3, column=0)

buttonfact.grid(row=4, column=4)
buttondiv.grid(row=4, column=3)
buttonb.grid(row=4, column=2)
button00.grid(row=4, column=1)
button0.grid(row=4, column=0)

buttonc.grid(row=5, column=4)
buttoneq.grid(row=5, column=2, columnspan=2)
buttonrp.grid(row=5, column=1)
buttonlp.grid(row=5, column=0)

root.mainloop()

When the exclamation mark is clicked a ! is shown. But it has no effect on the equation and results in an error (which leaves a question mark on the screen)
For aesthetic purposes I want to avoid adding a !( to the equation or a fact(; it would take too much space, and it's not the way you .
In theory, if I entered 3! the program would output 6.
I have tried:

*

*Doing setattr(int, 'factorial', fact) where fact is def fact(self): return math.factorial(self) (math had been imported in the program already) just returns the error:

  File "<pyshell#0>", line 1, in <module>
    setattr(int, 'factorial', fact)
TypeError: can't set attributes of built-in/extension type 'int'

I had hoped that I could add to the .replace chain in the third row of the clicked() function: text = inpbox.get().replace('√', "math.sqrt").replace('^', '**').replace('!', '.factorial()'), but since python won't let me add that attribute to numbers it was fruitless.

*

*trying int.__setattr__() yielded around the same results.


text:
Q: Change quantity steps depending on the user role of the in WooCommerce In WooCommerce, I am trying to change the product quantity field settings as step depending on user role and product.
Here is my code
add_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 ); // Simple products
function jk_woocommerce_quantity_input_args( $args, $product, $roles ) {
    if ( is_singular( 'product' ) ) {
        if( $product->get_id() == 85 ) {
            $args['input_value'] = 30;
        } else {
            $args['input_value'] = 5;
        }
    }

    if( array ( $roles, 'customer_roles')) {
        $args['min_value']      = 1;
         $args['step']           = 1;
    }

    if( $product->get_id() == 85 ) {
            $args['min_value'] = 30;
            $args['step']      = 5;
        } else {
            $args['min_value'] = 5;
            $args['step']      = 5;
        }
        return $args;
}

How can I make this code working for user roles too?

A: There are some mistakes in your code, like $roles variable doesn't exist for this hook argument and some others… Try the following:
add_filter( 'woocommerce_quantity_input_args', 'quantity_input_args_filter_callback', 10, 2 );
function quantity_input_args_filter_callback( $args, $product ) {
    // HERE define the user role:
    $user_role = 'customer_roles';

    $user = wp_get_current_user(); // Get the WP_Use Object

    // For a specific user role, we keep default woocommerce quantity settings
    if( in_array( $user_role, $user->roles ) )
        return $args; // Exit to default

    // For the others as following

    if ( is_singular( 'product' ) ) {
        if( $product->get_id() == 85 ) {
            $args['input_value'] = 30;
        } else {
            $args['input_value'] = 5;
        }
    }

    if( $product->get_id() == 85 ) {
        $args['min_value'] = 30;
        $args['step']      = 5;
    } else {
        $args['min_value'] = 5;
        $args['step']      = 5;
    }
    return $args;
}

Code goes in function.php file of your active child theme (or active theme). It should works.


text:
Q: Different CornerRadius to Border for each corner I try to give corner to view's corners with different size. Firstly, I give corner to all corners about min radius and then I try to change 2 left corner with bigger size.
enter image description here
func roundCorners(_ corners:UIRectCorner,_ cormerMask:CACornerMask, radius: CGFloat) {
    if #available(iOS 11.0, *){
        self.clipsToBounds = false
        self.layer.cornerRadius = radius
        self.layer.maskedCorners = cormerMask
    }else{
        let rectShape = CAShapeLayer()
        rectShape.bounds = self.frame
        rectShape.position = self.center
        rectShape.path = UIBezierPath(roundedRect: self.bounds,    byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
        self.layer.mask = rectShape
    }
}

//
viewMoreView.roundCorners(.bottomLeft, [.layerMinXMinYCorner , .layerMinXMaxYCorner], radius: 13)
viewMoreView.layer.borderWidth = 1
viewMoreView.layer.borderColor = UIColor(red:0.81, green:0.83, blue:0.83, alpha:1).cgColor
viewMoreView.clipsToBounds = true

This code change left sides but in the right side all changes (radius) is removed.
With this below link, borderRadius doesnt look properly like this pic!!!
enter image description here
Different cornerRadius for each corner Swift 3 - iOS

A: I know this is shortcut about this issue
    let demoView = UIView(frame: CGRect(x: 0, y: 0, width: vieww.bounds.width, height: vieww.bounds.height))
    demoView.backgroundColor = UIColor.lightGray
    demoView.layer.cornerRadius = 3.0

    let maskPath = UIBezierPath(roundedRect: demoView.bounds,
                                byRoundingCorners: [.topLeft, .bottomLeft],
                                cornerRadii: CGSize(width: 64.0, height: 0.0))

    let maskLayer = CAShapeLayer()
    maskLayer.path = maskPath.cgPath
    demoView.layer.mask = maskLayer

    vieww.addSubview(demoView)

    let demoViewInner = UIView(frame: CGRect(x: 2, y: 2, width: demoView.bounds.width-4, height: demoView.bounds.height-4))
    demoViewInner.backgroundColor = UIColor.white
    demoViewInner.layer.cornerRadius = 3.0

    let maskPathInner = UIBezierPath(roundedRect: demoViewInner.bounds,
                                byRoundingCorners: [.topLeft, .bottomLeft],
                                cornerRadii: CGSize(width: 60.0, height: 0.0))

    let maskLayerInner = CAShapeLayer()
    maskLayerInner.path = maskPathInner.cgPath
    demoViewInner.layer.mask = maskLayerInner

    demoView.addSubview(demoViewInner)

however adding and inner view looks like a solution also. After reshaping of layer, adding border may not be right way.

A: may be adding sublayer to the view is a clear solution that you can accept
let borderLayer = CAShapeLayer()
borderLayer.frame = self.view.bounds
borderLayer.path  = maskPath.cgPath
borderLayer.lineWidth   = 3
borderLayer.strokeColor = UIColor.lightGray.cgColor;
borderLayer.fillColor   = UIColor.clear.cgColor;

viewMoreView.layer.addSublayer(borderLayer)

Because adding layer border to the current view does not work as such as you would like. You should use sub layers.


text:
Q: Exporting a GeoTIFF with PyGRASS I want to export a GeoTIFF with PyGRASS but i can't figure out how I can do that.
my code so far:
# import grass python libraries
from grass.pygrass.modules.shortcuts import general as g
from grass.pygrass.modules.shortcuts import raster as r
from grass.pygrass.modules.shortcuts import vector as v
from grass_session import Session

inputfile = './data/gtifs/13.tif'

with Session(gisdb="./tmp", location="location", create_opts="EPSG:4326"):
    r.external(input=inputfile, output="layer_1", overwrite = True)
    print(r.info(map="layer_1").get_dict())

    r.mapcalc(expression='if(layer_1>0, 1, null())',overwrite=True)

    print(g.list(type='raster', flags="m").get_dict())
    # neither of the approaches below work
    r.external.out(directory='./', format="GTiff")
    r.out.gdal(input='layer_1', output='./test.tif')

r.out.gdal() produces an FileNotFoundError: [Errno 2] No such file or directory: 'r.out': 'r.out' and an GrassError: Error running: 'r.out --interface-description'. error
r.external.out() does not seem to exist as a method
how do I save my grass raster as an GeoTIFF? I'm using the Grass GIS 7.8 binaries and python 3.6.9

A: Since you are using the "Modules" approach of PyGRASS, be sure to change the second dot in 3-word-commands to an underscore:
No:
r.external.out(...)
r.out.gdal(...)

Yes:
r.external_out(...)
r.out_gdal(...)

See "Example 3, using "shortcuts" and external raster format support" in
https://grasswiki.osgeo.org/wiki/GRASS_and_Python#pygrass_Library