text:
Q: Register with username using identity 2.1 New .net identity system uses email and password as registration pair. I would like to change it as it was before and use username for loging users to my webapp. Also I'd like to keep somme additional information during registration as email, phone number.
Can You help me and point where I should look for information for solving the problem. I cant find usefull information.

A: Actually the old identity framework system (v 1.0) registration UI different to the new version. You can easily understand what exactly happening in the registration code.
New out of the box registration code is:
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

You can see that the Username and Email both uses model.Email.
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

Update your code as below
Register method
[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {

            UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager)
            {
                RequireUniqueEmail = false,
            };

            var user = new ApplicationUser { UserName = model.UserName };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

RegisterViewModel
public class RegisterViewModel
    {
        [Required]
        [Display(Name = "UserName")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

LoginViewModel
public class LoginViewModel
    {
        [Required]
        [Display(Name = "UserName")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }

Further you need to update other view models not to use email and instead use
[Required]
    [Display(Name = "UserName")]
    public string UserName { get; set; }

Then update all views to use UserName instead Email like below.
@model WebApplication2.Models.RegisterViewModel
@{
    ViewBag.Title = "Register";
}

@ViewBag.Title.

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()

Create a new account.

    @Html.ValidationSummary("", new { @class = "text-danger" })

        @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })

            @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })

        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })

            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })

        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })

            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })

            <input type="submit" class="btn btn-default" value="Register" />

}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Hope this helps.


text:
Q: Can I upgrade linux-base to newer major version? I'm on Trusty and would like to continue installing the newest mainline kernels. These started to depend on linux-base >= 4.5, while Trusty only has linux-base 3.5 in its PPAs. Is it safe to get linux-base from a xenial PPA and install it on my trusty? Could it break something?

A: It's safe to download linux-base 4.5 from the official Ubuntu Download Page for linux-base_4.5ubuntu1~16.04.1_all.deb and double-click the linux-base_4.5ubuntu1~16.04.1_all.deb that you downloaded to open it for installation in the Ubuntu Software Center. There won't be any dependency problems either.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PL SQL relationship and procedure issues I would like to ask some help with pl/sql oracle. I am trying to figure out this object oriented database stuff but not much success so far. I am into programming and i understand rdbms as well, already managed some complex database but this object oriented is over my understanding.
So the task is the following:
There are teachers and students. need to make a timetable which has two type of lessons. day and afternoon.
day class can have maximum 10 students and afternoon max 5.
the followings i have so far:
/*create student type and table*/
create type student_typ as object(
st_id char(3),
st_name varchar(50)
)
create table student_tbl of student_typ(
st_id primary key not null,
st_name not null
)

/*create teacher type and table*/
create type teacher_typ as object(
tr_id char(3),
tr_name varchar(50)
)
create table teacher_tbl of teacher_typ(
tr_id primary key not null,
tr_name not null
)

/*create array type to store the student id-s*/
create type students_arr as varray(20) of char(3);

/*create table for timetable*/
create table timetable_tbl(
t_ID char(5),
t_Date date,
t_Time varchar(5), /*store time format as 12:00*/
t_Type char(1),
teacher ref teacher_typ scope is teacher_tbl,
students students_arr,
constraint chk_type check(t_Type='D' or t_Type='N')
)

/*insert values into the tables*/
insert into teacher_tbl values ('t01','bob');
insert into teacher_tbl values ('t02','smith');
insert into student_tbl values ('s01','lara');
insert into student_tbl values ('s02','john');

/*insert values into timetable*/
insert into timetable_tbl( select 't01','01-Apr-17','09:00','D',ref(t),students_arr('s01','s02') from teacher_tbl t where t.tr_ID='t01');
insert into timetable_tbl( select 't02','01-Apr-17','19:00','N',ref(t),students_arr('s01') from teacher_tbl t where t.tr_ID='t02');

/*display timetable records*/
select t_ID, t_Date, t_Time, t_Type, deref(teacher).tr_ID,deref(teacher).tr_Name, students from timetable_tbl;

/*create procedure to add new student*/
create or replace procedure Add_Student(
v_id in student_tbl.st_id%type,
v_name in student_tbl.st_name%type,
verror out varchar2 )
is begin
insert into student_tbl (st_id,st_name) values (v_id,v_name);
commit;
exception when others then
verror := sqlerrm;
end;

/*call add_student procedure*/
declare
verror varchar2(500);
begin
Add_Student('s03','sam',verror);
end;

So that is what i have so far. The questions are the next.

*

*Is this the right way to do this?

*how can i reference the students in the varray? i have tried ref as with the teacher ref but no result at all?
students student_arr ref student_typ scope is student_tbl; this code is not working.
the students_arr array should accept only existing records from student table

*how can i create a procedure for timetable? because the main thing there is when the t_Type is "D" then the student_arr should allow maximum 10 values
and if the t_Type is "N" then the student_arr should allow maximum 5 values only. i Should do something like add_record procedure for timetable and using if statement but i am not sure it would be a good idea.
if t_type='D' then
if students.count<=10
or
if t_type='N' then
if students.count<=5
Im kind of stucked now. I have watched a lot of tutorials about pl sql but got even more confused. The annoying things is that i managed the same with
rdbms (sql server) and java in no time. But this language and object database got me hard now.
Any help would be appropriated!

A: You can expand the students array using the table() function:
select t_id, t_date, t_time, t_type, deref(teacher).tr_id,deref(teacher).tr_name
     , s.column_value as student
from   timetable_tbl cross join table(students) s;

You'll also see that join written as
from   timetable_tbl, table(students) s;

which looks neater in this context but I've officially switched to ANSI join syntax.
Since students_arr is a generic varray of varchar2 it has no attribute names, hence the default name column_value.
As for the procedure to insert timetables, if it takes a students_arr varray parameter named p_students, yes just check p_students.count against the t_type value. (You can't use a cardinality() function in a check constraint unfortunately, which otherwise might have been the declarative approach.)
Regarding "the right way to do this", use ordinary, normalised relational tables unless you have a good use for the object/nested table stuff.

A: It seemed i was not clear about the questions. So here is the things again but in a simplified way.
There is a person class which holds info about persons. And there is a test class which holds other info like a timetable but it holds persons in a column. So it is a multi-valued column which i can manage with either using varray or nested table type.

The problem is how to use ref in this way. I can use ref for a single object but not in collection.
/*create person type and table*/
create type person_ty as object(
pid varchar(3),
pName varchar(50)
);
create table person_tbl of person_ty;

/*create table which will be used as nested table*/
create type nest_ty as object(
tID varchar(3),
person ref person_ty
);
create type nest_tbl as table of nest_ty;

/*create table for test*/
create table test_tbl(
tID varchar(3),
tDate date,
persons nest_tbl
)nested table persons store as persons;

*

*so how can i insert data into the test table?

i know a single nested table without ref type would be:
insert into test_tbl values ('123','12-dec-17', nest_tbl(
nest_ty('123','p01'),
nest_ty('345','p06')
));

and i know that insert data with a single ref type looks like this:
insert into test_tbl
select '123', '12-dec-17', ref(a) from person_tbl a where a.pID='p01';

Again i am very new with oodb and plsql so my questions might not be clear or make no sense. In that case im sorry.
Still appropriate all kind of help.


text:
Q: A sequent calculus proof Consider the sequent calculus (with multiplicative contexts) defined by the following rules (without contraction and weakening). The sequent calculus is taken from p.23 here: http://users.ox.ac.uk/~cpgl0036/pdf/asudeh-giorgolo-perspectives.pdf):
$$ \frac{\qquad }{A \vdash A} \,{Id} $$
$$ \frac{\Gamma\vdash B \qquad B, \Delta\vdash C}{\Gamma, \Delta \vdash C} \,{Cut} $$
$$ \frac{\Delta\vdash A \qquad \Gamma, B\vdash C}{\Gamma, \Delta,  A \rightarrow B \vdash C} \,{\rightarrow L} $$
$$ \frac{\Gamma, A \vdash B}{\Gamma \vdash A \rightarrow B} \,{\rightarrow R} $$
$$ \frac{\Gamma \vdash A}{\Gamma \vdash \bigcirc A} \,{\bigcirc R} $$
$$ \frac{\Gamma, A \vdash \bigcirc B \qquad }{\Gamma, \bigcirc A \vdash \bigcirc B} \,{\bigcirc L} $$
I can prove $\bigcirc (A \rightarrow B) \vdash \bigcirc A \rightarrow \bigcirc B$ in this calculus, but not the converse $\bigcirc A \rightarrow \bigcirc B \vdash \bigcirc (A \rightarrow B)$. Is the converse provable? I cannot find a proof of it.

A: The general recipe for answering such questions is based on a cut-elimination theorem. The authors state in footnote 28 that the $Cut$ rule is "admissible" for this calculus, which is another way to say that it can be eliminated.[*] To decide whether $\bigcirc A \to \bigcirc B \vdash \bigcirc (A \to B)$ is provable, it therefore suffices to ask, "Does it have a cut-free proof?"
Now, any cut-free proof of $\bigcirc A \to \bigcirc B \vdash \bigcirc (A \to B)$ must necessarily end in either ${\to}L$ or ${\bigcirc}R$, as in one of the following proof attempts:
$$
 \frac{\vdash \bigcirc A \qquad \bigcirc B \vdash \bigcirc (A \to B)}{\bigcirc A \to \bigcirc B \vdash \bigcirc (A \to B)} {\to}L
\qquad
 \frac{\bigcirc A \to \bigcirc B \vdash A \to B}{\bigcirc A \to \bigcirc B \vdash \bigcirc (A \to B)} {\bigcirc}R
$$
The first possibility can be immediately eliminated because it is not possible to prove $\vdash \bigcirc A$ for arbitrary $A$ (take $A$ to be any atomic formula). The second possibility can likewise be eliminated through a bit more case analysis of cut-free proofs: eventually we would be required to prove $\bigcirc B \vdash B$, but this is not possible for general $B$.
Therefore, $\bigcirc A \to \bigcirc B \vdash \bigcirc (A \to B)$ is not provable for general $A$ and $B$.
[*] technically, a rule is admissible for a sequent calculus if given derivations of the premises, we can construct a derivation of the conclusion without using the rule itself. In particular, the $Cut$ rule is admissible if given cut-free derivations of $\Gamma \vdash B$ and $B, \Delta \vdash C$, we can always construct a cut-free derivation of $\Gamma,\Delta \vdash C$.

Edit: Of course, the extra bit of reasoning which is missing from this argument is the proof of cut-elimination itself which the authors claim in the footnote. That is usually done on a case-by-case basis for a particular sequent calculus, and is a good exercise (you can find an example for another sequent calculus in these lecture notes by Frank Pfenning).


text:
Q: Reference / Survey for finite field analog number theory It is folklore that many number theoretic results on prime numbers have a simpler-to-prove finite field analog. For example, on the one hand, the proof of the Prime Number Theorem
$$\#\{\text{prime numbers}\leq x\} \sim \frac{x}{\log x}, \;\;\,\; x \to +\infty,$$
requires complex analysis and the study of the Riemann zeta function (or the elementary, albeit complicated, machinery of Selberg), while, on the other hand, the proof of
$$\#\{\text{irreducible monic polynomials in $\mathbb{F}_q[x]$ of degree} \leq n\} \sim \frac{q^n}{\log_q q^n}$$
requires only some combinatorial reasonings (which also gives an error term of the size of the one expected for the error term of the prime numbers counting function under the Riemann's hypothesis).
Do you know where I can find a survey or some other kind of collection of these finite field analog? Thanks

A: One of the best references I am aware of, is the book by Rosen 'Number theory in function fields' https://www.springer.com/gp/book/9780387953359.
A good survey, which also concerns the important connection with random matrix theory, is the following paper by Rudnick, although you won't find proofs there: http://www.math.tau.ac.il/~rudnick/papers/ICM-Proceedings-Rudnickv5.pdf


text:
Q: Getting an error using MongoDB aggregate $sample operation. -- MongoError: $sample stage could not find a non-duplicate document MongoError: $sample stage could not find a non-duplicate document after 100 while using a random cursor. This is likely a sporadic failure, please try again.
Using MongoDB version 3.2.8 and just upgraded to 3.2.10.
I'm following the example set forth by the MongoDB documentation.. There is very little documentation. The only thing I can find doing a search is a bug in an issue queue which doesn't solve the problem for me.
My implementation is very simple.
function createBattle(done) {
    // Need to make sure that the yachts are different.
    async.doWhilst(
        function(callback) {
            Yacht.aggregate(
                {
                    $sample: { size: 2 }
                },
                function (err, results) {
                    console.log(err.toString());
                    if (err) return callback(err);
                    callback(null, results);
                }
            )
        },
        function(results) {
            return results.length !== 2 || _.isEqual(results[0]._id, results[1]._id);
        },
        function(err, results) {
            if (err) return done(err);
            done(null, results);
        }
    )
}

I'm not sure what is going on. Any ideas?

A: I am using Mongoose. It is in development. My guess is that something occurred when I changed the schema of the document. It works with the test mock data after creating 100000 fake documents or just 10 documents. So I decided to try a fresh start on the collection on the development instance of the database. Regardless, I exported the collection into a clean JSON file. I deleted the collection in the database. Then I imported the JSON dump. It works fine.
It's a bug.
This is probably the last straw with MongoDB for me. I'll probably go back to SQL, use Redis, and try PostGRES.


text:
Q: Serial Number record Search I have created a saved search to display serial numbers above is my saved search script but the problem while printing in sales order. it is printing all the serial numbers which are displayed in saved search but the requirement is the sales order pdf to only show the serial number for that particular sales order only
var customrecordserial_number_01SearchObj = search.create({
   type: "customrecordserial_number_01",
   filters:
   [
      ["custrecord71","isnotempty",""],
      "AND",
      ["name","isnotempty",""]
   ],
   columns:
   [
      search.createColumn({name: "custrecord71", label: "Item Name"}),
      search.createColumn({
         name: "name",
         sort: search.Sort.ASC,
         label: "Name"
      }),
      search.createColumn({name: "custrecord70", label: "Item Fulfillment"})
   ]
});
var searchResultCount = customrecordserial_number_01SearchObj.runPaged().count;
log.debug("customrecordserial_number_01SearchObj result count",searchResultCount);
customrecordserial_number_01SearchObj.run().each(function(result){
   // .run().each has a limit of 4,000 results
   return true;
});
/*
customrecordserial_number_01SearchObj.id="customsearch1659425362410";
customrecordserial_number_01SearchObj.title="  Serial Number Record Search  (copy)";
var newSearchId = customrecordserial_number_01SearchObj.save();
*/


text:
Q: How can you request photo gallery permissions in iOS a second time In my iOS app I am accessing the user's photo gallery.  The first time the user does this, it asks them for permission.  Some of my users have reported getting a crash this first time due to the permission request, but it works fine on subsequent tries.
To be able to test this on my own, I need to be able remove the permission from my iPad and have it prompt again.  Is there a way to do this either through the iPad/iPhone itself or through code?

A: Run the Settings app. Go to General, then Reset. Tap on Reset Location & Privacy. This will reset all of your location and privacy settings, not just for your test app. But you are doing this on a development device so that should be OK. This works in the Simulator too.

A: In iOS 7+, you can go into Settings > Privacy > Photos and explicitly enable or disable access for individual apps.
This is much better than resetting your entire device privacy settings!

A: Another way is to temporary change Bundle Identifier (CFBundleIdentifier) in Info.plist.
System will treat such app as a new separate app and will display "would like to access your Photos" alert.
Don't forget to revert CFBundleIdentifier after you end testing.


text:
Q: Chrome Web Store Search Icon I've just published a Chrome extension, but am having difficulties displaying the right icon for my extension in the Web Store.
Here is what is currently being displayed:

Here is the icon context in my manifest:
  "icons": {
    "16": "icon02.png",
    "48": "icon02.png",
    "128": "promoSmall.png"
  },

The image being displayed it icon02.png, I'm trying to display promoSmall.png.
Where is the image from the store page looking at?
Note: I understand that this question is similar to this. I believe this question is more specific, and may serve more useful to others with this problem.
Thanks!


text:
Q: Backbone Views + deferred handlebars template loading I am trying to load handlebars templates and rendering them via deferred objects / promises, but when i refactored the code by putting in deferreds , errors are occurring:
My view is as follows:
var indexView = Backbone.View.extend({
    initialize: function (options) {
        this.options = options || {};
        manager.getTemplate('path/to/template').then(function(tpl){
            // tpl is a handlebar compiled template,returned by getTemplate
            this.template = tpl;
            this.render();
        // that causes
        // Uncaught TypeError: Object #<Object> has no method 'render'
        // "this" is Backbone.View.extend.initialize
        });
    },
    render: function (){
        // this.options is undefined
        this.$el.html(this.template(this.options.data));
        return this;
    }
});

i can't understand how i'm supposed to reach this.render from the .then() function and also why in the render() function this.options is now undefined
Thank you

A: Beware the malignant this! It may not be what you think it is when your deferred function is called, especially where jQuery is involved.
Try
initialize: function (options) {
    this.options = options || {};
    var myself = this;

    manager.getTemplate('path/to/template').then(function(tpl){
        // tpl is a handlebar compiled template,returned by getTemplate
        myself.template = tpl;
        myself.render();
    });
}


text:
Q: php pdo mssql declare insert select I'm trying access to a MS SQL server using PHP PDO:SQLSRV or PHP SQLSRV.
For PHP PDO:SQLSRV, I'm using this code:
<?php

    try {
        $db = new PDO("sqlsrv:Server=sql_server;Database=database", "username", "password");
        $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

        $test = $db->prepare('declare @t2 code.instancereferencestable;
                              insert into @t2 select top 10 [Instance Reference] from imported.instance where [Instance Type] = \'CENAS\' and [Instance Reference] = \'CENAS.8000\' order by [Instance (Id)] desc;
                              select * from transformed.attribute_instance_extended_from_references(@t2)');
        $test->execute();
        $test->fetch(PDO::FETCH_OBJ);

        echo "Connected!". "\n";
    }
    catch(Exception $e) {
            echo "Error: " . $e->getMessage() . "\n";
    }

?>

For PHP SQLSRV, I'm using this code:
<?php

    $serverName = "sql_server";
    $connectionOptions = array(
        "Database" => "database",
        "Uid" => "username",
        "PWD" => "password"
    );

    $conn = sqlsrv_connect($serverName, $connectionOptions);
    if ( $conn ) {
        echo "Connection established.".PHP_EOL;

        $sql = ("declare @t2 code.instancereferencestable;
                insert into @t2 select top 10 [Instance Reference] from imported.instance where [Instance Type] = 'CENAS' and [Instance Reference] = 'CENAS.8000' order by [Instance (Id)] desc;
                select * from transformed.attribute_instance_extended_from_references(@t2);");

        $stmt = sqlsrv_query($conn, $sql);
        if ( $stmt === false ) {
               die( print_r( sqlsrv_errors(), true));
        } else {
            $row = sqlsrv_fetch_array($stmt);
            print_r ($row);
        }

    } else {
            echo "Connection could not be established.".PHP_EOL;
            die( print_r( sqlsrv_errors(), true)).PHP_EOL;
    }

?>

The output that I get from the PHP PDO:SQLSRV is:
Error: SQLSTATE[IMSSP]: The active result for the query contains no fields.
And from the PHP SQLSRV I have no output.
I run the same SQL code directly in the SQL Server Management Studio and I have output.
Can anyone help!?
Thanks in advance!

A: A simple solution could be creating a Stored Procedure and call that instead.
Also you could try using php_mssql.dll module.
Info here: http://php.net/manual/es/book.mssql.php


text:
Q: Pagination links in profiles point to HTML snippets for Ajax, not actual pages
Possible Duplicate:
Links on user page are assembled to the wrong destination

I middle-clicked on a pagination link in my profile...

...and when I clicked on the new tab, I was startled to see nothing but the unformatted data from the next page:

It looks like the hrefs on the pagination links are the URLs used to retrieve the content with AJAX, not an actual URL that users are intended to use.
I can see how this makes the code a little simpler but it doesn't make semantic sense and screws up things like this which expect href's value to be meaningful.


text:
Q: Click a button using Selenium and Python I have the following code:
Expand all

When I click on expand all, the whole page loads. How can I do it using WebDriver for Python?

A: As per the HTML you can use the find_element_by_link_text and invoke click() method as follows :
driver.find_element_by_link_text("Expand all").click()

You can get more granualar with find_element_by_xpath as follows :
driver.find_element_by_xpath("//a[@class='sectionname' and contains(.,'Expand all')]").click()

Update
As you still don't see the expansion you can try the Javascript way as follows :
myElement = driver.find_element_by_xpath("//a[@class='sectionname' and contains(.,'Expand all')]")
driver.execute_script("arguments[0].click();", myElement)


text:
Q: xrange as an iterator and chunking The snippets
 xi = xrange(10)
 zip(xi,xi)

and
 xi = iter(range(10))
 zip(xi,xi)

behave differently. I expected to get
  [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

in the first snippet as well, but it returns
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]

instead. It seems the implicit container is being silently copied.  Could anyone explain whats going on here ? and reasoning behind choosing such semantics.
>>> sys.version
'2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)]'

A: The xrange object is not already an iterator, but an iterable object. You get the iterator by feeding it to the iter function. The zip function implicitly calls iter on all of its arguments, so it produces two parallel iterators over the xrange object. In the second example, you call iter once by hand, so you are comparing apples to oranges. To get the effect you want also for xrange, you should do
In [5]: it = iter(xrange(10))
   ...: zip(it, it)
Out[5]: [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

A: An xrange is not any sort of iterator. People keep calling it a generator, but it's not; an xrange is an immutable sequence, like a tuple:
>>> x = xrange(5)
>>> x[2]
2
>>> for i in x:
...     print i
...
0
1
2
3
4
>>> for i in x:
...     print i
...
0
1
2
3
4

As with any other sequence type, each time you request an iterator from an xrange, you get a new, independent iterator. Thus, when you zip xrange(10) with itself, you get the same output as if you had zipped [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] with itself, rather than if you had zipped iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) with itself.

A: I think you have a miss understanding about xrange types. based on pythons documentation about xrange type :

The xrange type is an immutable sequence which is commonly used for looping. The advantage of the xrange type is that an xrange object will always take the same amount of memory, no matter the size of the range it represents. There are no consistent performance advantages.

And following important part :

XRange objects have very little behavior: they only support indexing, iteration, and the len() function.

The xrange object is not an iterator its just an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously,Since you can not access to an iterator elements without traversing its preceding items and it doesn't supports operations like indexing or len() function.and when you traverse the iterator you can not go back!!
So in the second code the zip function consume each item at each iteration and it just can access to the next item.


text:
Q: How do I fix a recursive CTE to establish table dependencies based on sys.foreign_keys? The recursive CTE is producing duplicated results for nested dependencies in a hierarchy format. I want to have a field that spells out the path to each option.
I have tried rewriting this statement from a top down and bottom up approach but I have not been able to eliminate dependencies that don't actually exist.
For example, if I have base A, child B, and grandchild C, I want A, A\B, and A\B\C - but not A\C.
WITH rCTE
(
    [Level], -- Dimension count
    [RootSchema], -- Child table db schema
    [RootID], -- Child table ID, sys.foreign_keys.parent_object_ID
    [RTableName], -- Name of the child table
    [ParentSchema], -- Parent table db schema
    [ParentID], -- Parent table IDsys.foreign_keys.referenced_object_ID
    [PTableName], -- Name of the parent table
    [Path] -- The path to the item
) AS (
SELECT
    1 as [Level],
    object_schema_name(f.parent_object_id),
    f.parent_object_id as [RootID],
    object_name(f.parent_object_id) as [RTableName],
    OBJECT_SCHEMA_NAME(f.referenced_object_ID),
    CONVERT(int,null) as [ParentID],
    object_name(referenced_object_id) as [PTableName],
    CONVERT(varchar(150),object_name(f.referenced_object_id) --+ '\' + ISNULL(object_name(f.parent_object_id),'') -- Troubleshooting
    ) as [Path]
FROM
    sys.foreign_keys f join sys.tables t on t.object_id = f.parent_object_id
    --WHERE NOT EXISTS
    --( Select 1
    --  from sys.foreign_keys ff
    --  where f.parent_object_id = ff.referenced_object_id
    --)
UNION ALL
SELECT
    [Level]+1,
    object_schema_name(f.parent_object_id),
    f.parent_object_id,
    object_name(f.parent_object_id),
    OBJECT_SCHEMA_NAME(f.referenced_object_ID),
    f.referenced_object_id
    ,object_name(f.referenced_object_id)
    ,CAST(r.[Path] + '\' + r.[RTableName] as varchar(150))
from sys.foreign_keys f join rCTE r on f.referenced_object_id = r.rootID
    --where f.parent_object_id <> r.ParentID
)
select  distinct x.[level] -- change
        --,r.ParentSchema
        ,r.[PTableName]
        ,r.[RTableName]
        ,r.[Path]
from rCTE r join
    (
    select
        [ptableName], max([Level]) as [Level]
    from rCTE
    GROUP BY [pTableName]
    ) x on x.pTableName = r.pTableName
ORDER BY [Path]

--select distinct * from rcte

I referenced many sites but this was the best one, and this image taken from there demonstrates the kind of path I am talking about.
Picture of sample code results from a similar goal

A: I reached out to Kris Wenzel of the blog I had originally linked in my question after I received an e-mail from his mailing list that suggested sending him challenges you are encountering. He was able to provide a solution to the posed inquiry, which I've included below. This will map out a bottom-up approach to hierarchies based solely on the foreign keys within the database.
;
WITH cte_FKtable(Parent

                       , FKConstraintName

                       , Child)

       AS (SELECT PO.name AS ParentTable

                      , FK.name

                      , RO.name AS ChildTable

             FROM sys.foreign_keys AS FK

                      INNER JOIN sys.objects AS RO ON RO.object_id = FK.referenced_object_id

                      INNER JOIN sys.objects AS PO ON PO.object_id = FK.parent_object_id),

       cte_allTable(parent

                           , FKConstraintName

                           , child)

       AS (SELECT Parent

                      , FKConstraintName

                      , Child

             FROM cte_FKtable

             UNION

             SELECT O.name

                      , NULL

                      , NULL

             FROM sys.objects AS O

             WHERE type = 'U' AND -- user table

                       NOT EXISTS

             (

                    SELECT 1

                    FROM cte_FKtable

                    WHERE( cte_FKtable.parent = o.name OR

                                  cte_FKtable.child = o.name

                             )

             )),

       cte_tree(name

                    , description

                    , level

                    , sort)

       AS (SELECT DISTINCT

                           parent

                      , CAST(parent AS varchar(1024))

                      , 1

                      , CAST(parent AS varchar(1024))

             FROM cte_allTable AS a

             WHERE a.parent NOT IN

             (

                    SELECT child

                    FROM cte_allTable

                    WHERE child IS NOT NULL

             ) OR

                       a.child IS NULL

             UNION ALL

             SELECT FK.child

                      , CAST(REPLICATE('|---', cte_tree.level) + FK.child AS varchar(1024))

                      , cte_tree.level + 1

                      , CAST(cte_tree.sort + '\' + FK.child AS varchar(1024))

             FROM cte_tree

                      INNER JOIN cte_FKtable AS FK ON cte_tree.name = FK.parent)

       SELECT DISTINCT

                    name

               , description

               , level

               , sort

       FROM cte_tree

       ORDER BY sort;


text:
Q: Поиск однокоренных слов в списке Python Есть большой словарь. Где ключ - это ссылка на рецепт. А значение - это список ингредиентов. Пример:
dict {'https://random.com':['банан', 'яйца', 'мука', 'картофель']}
А есть запросы пользователя(в боте телеграм), которые я преобразую в список и сравниваю со списками в словаре и отдаю ссылку на рецепт, если есть попадание по запросу.
Так вот, многие рецепты не идут к пользователю, если нет точного попадания слов. Например,
когда пользователь ввел:
['картошка', 'яйцо']

И он не получает рецепт, хотя он подходит. Подскажите, как можно организовать проверку в этом случае? Как искать только по части слова 'карто', 'яйц'? Подскажите пожалуйста хотя бы направление поиска, если не само решение. Спасибо

A: Здесь стоит использовать алгоритм нечёткого сравнения строк. Вот пример:
from fuzzywuzzy import process
l = ['банан', 'яйца', 'мука', 'картофель']
print(process.extractOne("картошка", l))  # ('картофель', 59)

Второй элемент в кортеже — число от 0 до 100, которое показывает степень похожести слов. Например, можно считать, что ингредиенты одинаковые, если их похожесть >= 50.
Для повышения качества сравнения можно привести все слова в форму без окончаний:
from fuzzywuzzy import process
from nltk.stem.snowball import RussianStemmer
l = ['банан', 'яйца', 'мука', 'картофель']
stemmer  = RussianStemmer()
stem_l = [stemmer.stem(x) for x in l]  # ['бана', 'яйц', 'мук', 'картофел']
ingredient = stemmer.stem("картошка")  # 'картошк'
print(process.extractOne(ingredient, stem_l))  # ('картофел', 67)

Не забудьте установить необходимые библиотеки:
pip install fuzzywuzzy
pip install nltk

Конечно, при таком подходе можно перепутать похожие ингредиенты. Например, посчитать что "горох" и "горошек" это одно и то же.

A: Неплохой вариант - использовать pymorphy2 с русским словарем (pymorphy2-dict-ru) или его форк pymorphy3, который, похоже, отличается только обновленными словарями. Как сказано в комментариях к вопросу, он может привести слово к начальной форме. Что и требуется: приводим все ингредиенты и сравниваем. Такой подход отлично работает в другом телеграмном боте (полнотекстовый морфологический поиск).


text:
Q: python: iterate through two objects in a list at once Have a call to an SQL db via python that returns output in paired dictionaries within a list:
[{'Something1A':Num1A}, {'Something1B':Num1B}, {'Something2A':Num2A} ...]

I want to iterate through this list but pull two dictionaries at the same time.
I know that for obj1, obj2 in <list> isn't the right way to do this, but what is?

A: You can do this using zip with an iterator over the list:
>>> dicts = [{'1A': 1}, {'1B': 2}, {'2A': 3}, {'2B': 4}]
>>> for obj1, obj2 in zip(*[iter(dicts)]*2):
    print obj1, obj2

{'1A': 1} {'1B': 2}
{'2A': 3} {'2B': 4}

A: Use zip() here.
>>> testList = [{'2': 2}, {'3':3}, {'4':4}, {'5':5}]
>>> for i, j in zip(testList[::2], testList[1::2]):
        print i, j

{'2': 2} {'3': 3}
{'4': 4} {'5': 5}

Alternative (without using zip()):
for elem in range(0, len(testList), 2):
    firstDict, secondDict = testList[i], testList[i+1]

A: >>> L = [{'1A': 1},{'1B': 1},{'2A': 2}, {'2B': 2}]
>>> zip(*[iter(L)]*2)
[({'1A': 1}, {'1B': 1}), ({'2A': 2}, {'2B': 2})]

A: I believe the Python idiom for grouping items in an iterable is
zip(*[iter(iterable)])*n)

Where iterable is your list of dictionaries and n is 2 if you want them in groups of 2.
The solution would then look like this.
>>> data = [{'A':1}, {'B':2}, {'C':3}, {'D':4}]
>>> for dict1, dict2, in zip(*[iter(data)]*2):
    print dict1, dict2

{'A': 1} {'B': 2}
{'C': 3} {'D': 4}
>>>

This does not rely on slicing which means it's more memory efficient and likely faster as well since the two sequences that zip is 'zipping' in this case are being generated on the fly via iter(data), meaning one pass instead of three passes (1 for the first slice, 1 for seconds slice, 1 for zip).
If for some reason your data was very large then you probably wouldn't want to construct a whole new list of tuples which zip returns just to loop through it once. In that case you could use itertools.izip in place of zip.

A: http://docs.python.org/2/library/itertools.html
Look for 'grouper', you'd use n=2.
import itertools
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

A: simply
in Python 2
li = [{'Something1A':10}, {'Something1B':201}, {'Something2A':405} ]
from itertools import imap
for a,b in imap(lambda x: x.items()[0], li):
    print a,b

in Python 3, map() is already a generator

A: Use index to fetch two elements from the list.
testList = [{'2': 2}, {'3':3}, {'4':4}, {'5':5}]
for i in range(0,len(testList),2):
    print(testList[i],testList[i+1])


text:
Q: System properties and parallel test execution in JUnit 5 One of our classes uses a system property to load a configuration file. In a particular test case, we set this property to an invalid value to check the behavior of the class under test (CUT) in this situation.
The same class is also used transitively in various integration tests. Since we are using JUnit Jupiter's parallel test execution capabilities, we are witnessing race conditions in those integration tests that are using the CUT under the hood. They are failing because the system property is sometimes still invalid.
The parallelism itself is configured globally via the Maven Surefire plugin:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.0</version>
    <configuration>
        <properties>
            <configurationParameters>
                junit.jupiter.execution.parallel.enabled=true
                junit.jupiter.execution.parallel.config.dynamic.factor=1
            </configurationParameters>
        </properties>
    </configuration>
</plugin>

Consequently, all tests run in parallel per default. The CUT looks like this:
class AttributesProviderTest {

    @Test
    @ResourceLock( value = SYSTEM_PROPERTIES, mode = READ_WRITE )
    void invalid_attributes_file_should_yield_UncheckedIOException() throws Exception {
        final Properties backup = new Properties();
        backup.putAll( System.getProperties() );

        final String attributesFile = "foo";
        System.setProperty( AttributesProvider.ATTRIBUTES_FILE_PROPERTY, attributesFile );

        assertThatThrownBy( AttributesProvider::getTestInstance )
                .isExactlyInstanceOf( UncheckedIOException.class )
                .hasMessage( "Cannot read attributes file '" + attributesFile + "'." );

        System.setProperties( backup );
    }

    // Some other tests...

}

As it can be seen, we are trying to synchronize the system property access. However, if I have understood correctly, this only works for other @ResourceLock-annotated tests, and does not magically synchronize system property access in general?
Is there a way to fix the race condition (without annotating all other tests)? Some ideas:

*

*Ensure the CUT is executed sequentially at the beginning (or some other sort of synchronization).

*Refactor the CUT and invoke corresponding file-reading method with a parameter directly.

*Throw away the test case.


text:
Q: WiX - Install a driver which depends on the OS During the installation, I have to install an external driver which depends on the operating system of the PC. I know I can build several installer packages for every OS, but I have to do it in one installer. Is that possible?
My first problem is to find out which operating system exists on the PC. Via a condition like the following?
<Condition Message="Your Operating system is ... .">
    VersionNT = 500
    <?define PCPlatform = "Win2000" ?>
    OR  VersionNT = 501
    <?define PCPlatform = "XP" ?>
    OR  VersionNT = 600
    <?define PCPlatform = "Vista" ?>
    OR  VersionNT = 601
    <?define PCPlatform = "Win7" ?>
</Condition>

And then how to tell the installer which file is to execute?
<Component Id="Win32_W2K" Guid="...">
    <File Id="vbsetup7" Source="..\driver\32Bit\W2K\vbsetup7.exe" Name="vbsetup7.exe" KeyPath="yes" DiskId="1"/>
</Component>
<Component Id="Win32_XP" Guid="...">
  <File Id="vbsetup7" Source="..\driver\32Bit\XP\vbsetup7.exe" Name="vbsetup7.exe" KeyPath="yes" DiskId="1"/>
</Component>
<Component Id="Win32_Vista" Guid="...">
  <File Id="vbsetup7" Source="..\driver\32Bit\Vista\vbsetup7.exe" Name="vbsetup7.exe" KeyPath="yes" DiskId="1"/>
</Component>
<Component Id="Win32_Win7" Guid="...">
  <File Id="vbsetup7" Source="..\driver\32Bit\Win7\vbsetup7.exe" Name="vbsetup7.exe" KeyPath="yes" DiskId="1"/>
</Component>
<CustomAction Id="Virtual_Driver" FileKey="vbsetup7" Execute="deferred" ExeCommand="" Return="check" Impersonate="no"/>

A: You have to add Condition to your components. At runtime, Condition must evaluate to true  for only one of the component elements, that is, conditions must be mutually exclusive. Something like:
<Component Id="Win32_W2K" Guid="...">
    <Condition>VersionNT = 500</Condition>
    <File Id="vbsetup7" Source="..\driver\32Bit\W2K\vbsetup7.exe" Name="vbsetup7.exe" KeyPath="yes" DiskId="1"/>
</Component>

A: How are you installing the drivers? If you are using DifxApp then you will have to have more than one installer, one for each target architecture (x86 vs x64). There are wixlibs for Difxapp that make driver installation pretty easy.

A: You may have problems if you have to run one installer "inside" another, especially if the second package is also Windows Installer-based, because Windows Installer (MSI) does not support "nested" installs. Some of the resources that MSI works with are effectively global, so the inner installation can tromp on the outer-install-in-progress.
A better approach is to use a chain of installs. In WiX, these are called bundles, and are run by the burn bootstrapper. You can apply conditions to each element of the bundle, so that a given element is run only for a certain Windows version (or service-pack level, or x86|x64, or if some other package is or is not present on the system, or... Install conditions can be as flexible as you like).


text:
Q: Apple Music API, explicit content playback I'm trying to use the new API from Apple, but when trying to play some songs using setQueueWithStoreIDs(storeIds: [String]) method I noticed I couldn't play all of the songs in my queue. Trying to understand the problem was painful since the new APIs do not provide any errors. At the end I noticed I didn't have explicit content settings on in restrictions, but that took me some time. Apple Music actually does notify users when they try to play "explicit" flagged media if their app settings do not let them. Is there a way to do this in our apps?

A: I was having the same issue.
You need to make sure the ids you are adding to the queue belong to the same storefront where the user is.


text:
Q: Replace string of text in powershell I'm trying to replace string of text and I get  The regular expression pattern  is not valid.
This is to be able to change a policy using LGPO
$TextToBeReplaced="Computer`r`nSOFTWARE\Policies\Microsoft\Windows\DeviceGuard`r`nDeployConfigCIPolicy`r`nDWORD:1`r`n`r`nComputer`r`nSOFTWARE\Policies\Microsoft\Windows\DeviceGuard`r`nConfigCIPolicyFilePath`r`nSZ:C:\\WL\\politicas\\DeviceGuardPolicy.bin"

$NewText="Computer`r`nSOFTWARE\Policies\Microsoft\Windows\DeviceGuard`r`nDeployConfigCIPolicy`r`nDELETE`r`n`r`nComputer`r`nSOFTWARE\Policies\Microsoft\Windows\DeviceGuard`r`nConfigCIPolicyFilePath`r`nDELETE"

((Get-Content -path $LGPOTxt -Raw) -replace $TextToBeReplaced,$NewText) | Set-Content -Path $LGPOTxt

LGPO.txt contains this what I have to change is this string for the other in order to apply the new LGPO policy
; ----------------------------------------------------------------------
; PARSING Computer POLICY
; Source file:  C:\WL\LGPO\LGPOBackUp\DomainSysvol\GPO\Machine\registry.pol

Computer
SOFTWARE\Policies\Microsoft\Windows\DeviceGuard
DeployConfigCIPolicy
DWORD:1

Computer
SOFTWARE\Policies\Microsoft\Windows\DeviceGuard
ConfigCIPolicyFilePath
SZ:C:\\WL\\politicas\\DeviceGuardPolicy.bin

; PARSING COMPLETED.
; ----------------------------------------------------------------------

Any way to do this?

A: This is because -replace operator treats replacement text as regular expression.
<input> -replace <regular-expression>, <substitute>

Instead, you could use replace method on the string object.

(Get-Content -path $LGPOTxt -Raw).replace($TextToBeReplaced, $NewText) | Set-Content -Path $LGPOTxt


text:
Q: Nested struct memory layout in c I have a stuct a of size 16 bytes and another struct b which contains a.
Why is struct b of size 40 bytes? Where is the additional padding exactly?
typedef struct {

} a;

typedef struct {

  a x;

} b;

A: The struct a has 4-byte alignment since that's the largest alignment of any of its members (i.e. float).
From there, the fields of b are laid out with the following offsets:

*

*w: 0

*padding: 1 - 3

*x: 4 - 19

*padding: 20 - 23

*y: 24 - 31

*z: 32 - 33

*padding: 34 - 39

The member with the largest alignment is y which has 8-byte alignment.  This results in 4 bytes of padding between x and y, as well as 6 bytes of padding at the end.
The padding can be minimized by moving z to between w and x.  Then you would have:

*

*w: 0

*padding: 1

*z: 2 - 4

*x: 4 - 19

*padding: 20 - 23

*y: 24 - 31

For a total size of 32.
Alignment is of course entirely up to the implementation, but this is what you'll most likely see.  The Lost Art of C Structure Packing goes into this in much more detail.

A: You seem to understand why the size of a is 16 bytes, and I'll also assume that you see why a has an alignment requirement of 4 bytes (see the note about arrays in the discussion below on the alignment of b). From that, we can see that, in b, we will have 3 bytes of padding between w and x.
Now, on your platform (as on many/most), a double has a size and alignment requirement of 8 bytes – so, after the 20 bytes up to the end of x (1 for w, 3 for padding and 16 for x), we need to add 4 bytes padding between x and y, to align that double. Thus, we have now added 12 bytes to our total, giving a running size (up to y) of 32 bytes.
The z member takes another 2 bytes (running size of 34) but, as the alignment requirement of the overall b structure must be 8 bytes (so that, in an array of such, every element's y will remain properly aligned), we need a further 6 bytes to reach a size (40) that is a multiple of 8.
Here is a breakdown of the memory layout:
typedef struct {
    char w;     //  1 byte:  total =  1
         // 3 bytes padding: total =  4
    float x;    //  4 bytes: total =  8
    short int y;//  2 bytes: total = 10
         // 2 bytes padding: total = 12
    float z;    //  4 bytes: TOTAL = 16
} a;

typedef struct {
    char w;     //  1 byte:  total =  1
         // 3 bytes padding: total =  4
    a x;        // 16 bytes: total = 20
         // 4 bytes padding: total = 24
    double y;   //  8 bytes: total = 32
    short int z;//  2 bytes: total = 34
         // 6 bytes padding: TOTAL = 40
} b;

A: The algorithm compilers typically use to lay out structures is described in this answer.
For your structure a and characteristics typical in current C implementations (described below):

*

*The char w has an alignment requirement of 1 byte, so it needs no padding and is placed at offset 1. It occupies 1 byte.

*The float x has an alignment requirement of 4 bytes, so 3 bytes are needed to bring the current offset from 1 byte to 4 bytes. Then it occupies 4 bytes, giving us 8 total so far.

*The short int y has an alignment requirement of 2 bytes, so it needs no padding from the current offset of 8 bytes. It occupies 2 bytes, bringing the total to 10.

*The float z has an alignment requirement of 4 bytes, so it needs 2 bytes to bring the offset from 10 bytes to 12 bytes. It occupies 4 bytes, bringing the total to 16.

*The alignment requirement of the structure is 4 bytes (the strictest alignment requirement of its members), and the current total is 16 bytes, which is already a multiple of 4, so no padding at the end is needed.

Thus the size of a is 16 bytes.
For your structure b:

*

*The char w has an alignment requirement of 1 byte, so it needs no padding and is placed at offset 1. It occupies 1 byte.

*The a x has an alignment requirement of 4 bytes, so 3 bytes of padding are needed to bring the offset from 1 byte to 4 bytes. It occupies 16 bytes, bringing the total to 20.

*The double y has an alignment requirement of 8 bytes, so 4 bytes of padding are needed to bring the offset from 20 bytes to 24. It occupies 8 bytes, bringing the total to 32.

*The short int z has an alignment requirement of 2 bytes, so no padding is needed from the current offset of 32 bytes. It occupies 2 bytes, bringing the total to 34.

*The alignment requirement of the structure is 8 bytes (the strictest alignment requirement of its members), so 6 bytes of padding is needed to bring the total size from 34 bytes to 40.

Thus the size of b is 40 bytes.
The characteristics used are:

*

*char has size 1 byte and alignment requirement 1 byte. This is a fixed property of the C standard.

*short int has size 2 bytes and alignment requirement 2 bytes.

*float has size 4 bytes and alignment requirement 4 bytes.

*double has size 8 bytes and alignment requirement 8 bytes. (Having an alignment requirement of 4 bytes instead of 8 would not be very weird; hardware might load and store doubles in 32-bit chunks and not care whether either of them were 8-byte aligned.)

*The C implementation does not use more padding or stricter alignment than required by the sizes and alignment requirements of structure members. (This is not mandated by the C standard, but there is generally no reason to do otherwise.)


text:
Q: django how to assign a User foreign key id within view I am trying to create a model with a foreign key which references the django model User.
I have found that you are supposed to use this model when creating something like this:
    author = models.ForeignKey(User)

however any time i try to assign this from my view with this line:
    if form.is_valid():
        c = form.save(commit=False)
        c.author=request.user.id
        c.save()

I get an error complaining about how author should come from the model User. There is no User property (at least that i (a noob working on their first django project) could find) which has the user id. what is the preferred method for linking a post to it's author in django? am i going about this completely the wrong way? is there a better way of solving this problem that i am just not thinking of?

A: You just assign this only not id,
c.author=request.user

A: For assigning user, it should be like:
c.author= User.objects.filter(id= request.user.id)[0]


text:
Q: get Discussion setting in wordpress I am writing a shortcode for comments
i need to know if admin wants users to logged in for commenting
i need to know  this option user must be registered and logged in for commenting
is there any function like :
get_admin_option('discussion','only_logged_in');
or
is_comments_public($postId);

A: this code may help you
$status = get_option('comment_registration');
// 1 : Yes , user must be registered and logged in for commenting
// 0 : No (default)

You can use the following code for the comment section
if (comments_open($postId)) {
    if (get_option('comment_registration') == 0 || is_user_logged_in() ){
      //render comments section
    }else{
        echo "You must login first";
    }
}else{
    echo "comments are closed";
}

also you can see other options in https://codex.wordpress.org/Option_Reference


text:
Q: How to link 2 separate models in Laravel? I'm making a project management tool to learn Laravel.
Right now I have 2 models for Project and Task, and I have set the relationship between the two:
Project:
public function task()
{
    return $this->hasMany(Task::class);
}

Task:
public function project()
{
    return $this->belongsTo(Project::class);
}

These are working fine, I can see the correct results in php artisan tinker, but right now I'm hard-coding which project all tasks belong to.
I have created, working, forms that create both of these things independently at the moment but I'm now sure how to link them together like a professional developer would.
The only solution I can think of, is to have a dropdown list on the createTask view populated with all the projects that are currently live. This doesn't feel very elegant, and doesn't feel like how a proper developer would handle it. I feel like creating a task in this sense, should be properly tied in with the project?

A: It sounds like you're on the right path and I think its more a matter of how you want your application to work.
The approach you outlined is one way to accomplish it and would be appropriate for an "all projects" view where the app does not know what project the user is going to assign the task to.
Another option would be to create an "edit project" view that only displays information for a single project.   This time, since you know the ID of the project the task will be added to, rather than displaying a dropdown you can use a hidden form element to pass the ID.
Depending on the interface, both methods may be appropriate.


text:
Q: QGIS: smooth crs transformation I have an elevation-raster in .hgt format with CRS EPSG:4326. My aim is to calculate aspect and slope which - as far as I understand - are difficult to obtain when using geographic CRS. Projected CRS are much better suited as map units are not degrees but meters (or the like).
So I tried and transformed the layer to EPSG:5677. However, the transformation produces very unpleasant artifacts (see pictures). The angles which were produced by the transformation have the potential to distort further analyses to a significant extent, I fear.
Can anyone suggest a procedure to minimise these unwished effects?
before transformation:

after transformation:

close before transformation:

close after transformation:

A: Apparently, there is no "perfect" transformation (which also is obvios). However, the warp function has different resampling methods to it. In this case, "cubic" seemed to work best. The result is not exact the same as the input layer, however, the undesired artifacts can be minimized and further analysis should only be affected to a minor extent.


text:
Q: YII2 Подключение JS с привязкой к PHP переменной? Очень дибильный вопрос.
Есть YII2, Есть Модуль выводящий на форму N кнопок с объектами. Надо подвесить один и тот же JS на каждую кнопку. Различия в кнопках только по ID. В JS различия уже по входным параметрам от объектов и коду кнопки как триггер. Код один и тот же.
У меня единственное получилось сделать вот так:
while ( $i <= $categoryCount) {
echo '<button id="btn'.$i.'" >';
echo "<script> $('btn".$i."').on('click', function() { console.log( $('btn".$i."') ); })</script>";
}

Пример очень минимализированный. Если таким образом описывать 2-3 команды, то фиг с ним. Лишних 5 мин не решат проблемы, Но если Код будет более - менее объемный, то тут уже сначала запутаешься в кавычках а там...
В общем пытался вынести JS код в отдельный файл, но Либо браузер либо YII уже не хочет принимать php переменные в JS коде.
Подскажите, как вообще поступают в таких случаях ?

A: Если я правильно понял вопрос, то сделал бы как то так:
сначала выводим кнопки:
while ( $i <= $categoryCount) {
echo '<button id="btn'.$i.'" class="category-btn">Кнопка</button>';
}

каждой кнопке добавили класс category-btn
затем в отдельном js-файле пишем слушатель:
$(document).on('click', '.category-btn', function() {
  let btn = $(this);
  console.log('Это кнопка с id=' + btn.attr('id'));
});

тут можно увидеть, что слушатель вешается на $(document), то есть код сработает даже если кнопки добавятся на страницу спустя некоторое время после загрузки скрипта, или после загрузки скрипта, или вообще когда угодно. внутри обработчика получаем переменную btn - в ней будет jquery объект кнопки по которой кликнули. дальше делаем с ней что хотим внутри этой функции
p.s. вешать слушатель на селектор класса, вообще, не очень хорошая идея, т.к. классы используются в css и в любой момент может поменяться вёрстка, класс потеряется и js-функционал пропадёт. лучше использовать html data-атрибуты. с ними сразу будет видно, что на кнопку навешан js-функционал


text:
Q: google-maps-api-v3 getProjection I am using google maps projection method to calculate the distance between two latitude and longitude.
var projection = this.overlay.getProjection();
var projection only gives results when the user stops moving (dragend) or zooming in and out the map.
But it doesnot work on idle.
Let say map is initialize and no event is fired than projection does not gives any result. As there is some event projection will start giving the results.
Anybody has any idea on this issue or how to trigger some event by code.
Thanks in advance

A: the projection of a OverlayView-instance isn't available until the onAdd-method of the overlay has been executed.
observe the projection_changed-event of the overlay
   google.maps.event.addListenerOnce(this.overlay, 'projection_changed',function(){
     console.log(this.getProjection());
   });


text:
Q: How to insert a Boolean variable into a JSON string in C# Suppose I have the following:
var b = true;
var f = "{ \"templateName\": \"name\", \"Active\": \"" +b + "\"}";

That b value does not work for me :( , I tried different scenario's with no luck.

A: The proper way of doing this is to work with objects directly.  Then you can serialize to whatever format you want (if you want JSON, JSON.NET is what you should use).
For instance, you should have a class that looks something like this:
public class TestClass
{
    public bool Active { get; set; }
    public string TemplateName { get; set; }
}

This is a class that represents your JSON object, but instead of modifying strings and dealing with that headache, we just deal with objects.
In your code you can instantiate and/or modify an instance of that object:
var testObj = new TestClass()
{
    Active = true,
    TemplateName = "SomeName"
};

//changed my mind, I want Active to be false now
testObj.Active = false;

Then with the power of JSON.NET you can serialize this object into JSON:
string jsonString = JsonConvert.SerializeObject(testObj);


text:
Q: How to sense if someone has clicked an area in android? I am trying to create an activity that changes backgrounds once someone clicks (and holds) an image of a button in the middle of the screen. The app will switch back to its normal background once the button is released.
So far I've tried placing a button in front of the "area" to press and set its visibility to invisible.
Is there a better way to do this? Is there a way to sense if the person let go of the button? (e.g. on button pressed do some stuff, when button released do other stuff)
Thanks

A: You can do this using canvas.In that,you can just take an image to be displayed in middle of canvas and catch the touch event on area,the image covers.And when user touches that area,change the background color of canvas.

A: You want something like NumberPickerButton and NumberPicker.
You should enable long clicking (setLongClickable(true))  on your button.
Then respond to both onLongClick event, and the onTouchEvent, if action is UP.
Your event handlers should look something like this:
public boolean onLongClick(View v) {
  changeYourBackground();
  return true;
}

public boolean onTouchEvent(MotionEvent event) {
  if ((event.getAction() == MotionEvent.ACTION_CANCEL)
        || (event.getAction() == MotionEvent.ACTION_UP)) {
     putYourBackgroundBack();
  }
  return super.onTouchEvent(event);
}


text:
Q: ROBOCOPY: Suppress all output except PROGRESS BAR I would like to ask you how I can suppress all text output except the progress bar.
EXAMPLE CODE:

 echo [Copying files ...]  robocopy %USERPROFILE%\documents\ USERPROFILE%\desktop\ test_copy.zip /njh /njs /ndl /nc /ns

.. with these parameters I get:

[Copying files ...]  (Blank line)  100% path to file

So, how can I suppress the file name? If I put /nfl, then it shows nothing. Any advice?
And second question? How can I delete blank lines from Robocopy?
Only mid-solution, I invented was adding:

 echo | set /p= [Copying files ..]

Result:

 [Copying files ...](no blank lines, but new line) 100% path
to file

But, I would like to get this form (no file name, no blank/new line):

 [Copying files ...] 100

%
If you know how to help me, I would really appreciate that.
Thank you in advance

A: You can use these switches:
/NJH    no job description
/NJS    no job summary
/NFL    no file list
/NDL    no directory list

But although that should keep showing progress, for me it does not.
Secondly, to prevent any output (including blank lines) you could use some cmd tricks, like outputing to a temp file and then deleting it:
robocopy (...) > temp
del temp


text:
Q: Gradle: Failed to load native library 'libnative-platform.so' for Linux amd64 For Ubuntu
I have installed Gradle 7.2 and the repository directory in /opt/gradle/ to be shared for some users:
Therefore:
/opt/gradle/
      7.2        rwxr-xr-x root root
      repository rwxr-xr-x root root

Where each directory has  rwxr-xr-x root root, when I execute gradle --version appears
FAILURE: Build failed with an exception.

* What went wrong:
Gradle could not start your build.
> Could not initialize native services.
   > Failed to load native library 'libnative-platform.so' for Linux amd64.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

I have already read:

*

* Failed to load native library 'libnative-platform.so' for Linux amd64. #8107

*php - Failed to load native library 'libnative-platform.so' for Linux amd64 - Stack Overflow
Therefore if I use: gradle --version -g ~/.gradle it works fine - therefore it is an access permission problem/situation for each non-root user/group, but even when I created a common group (developer) for the users and added +w to the common group for both - I mean
/opt/gradle/
      7.2        rwxrwxr-x root developer
      repository rwxrwxr-x root developer

appears the same error - the goal is share among the users the same repository access.
What is missing to accomplish this goal?


text:
Q: QT: UIC command line tool and the -tr parameter When *.ui files are saved, they generate an *.h file which defines and implements a translation method "retranslateui()" which uses a QApplication::translate call where the context for the translation equals the UI class name.
I need to be able to override that and put in my own custom context name.
The reason if you must know is that we have a non-QT legacy translation tables, with 14 languages. I built a tool that translates those strings into a *.TS file. The problem is, there IS NO CONTEXT, it's just a flat list of strings, so my tool forces one context for my entire application. The automatic generation of translate method calls where the context = the UI class name fails my ui translation.
I found that the UIC command line utility, creating this *.h file from the *.ui file has a parameter to define a different translation method. I can use this to route to my own translation method that'll add on the single context. My problem is that I can't find out how to change the UIC call from qmake to include this parameter with a custom value.

A: You can modify QMAKE_UIC property in your .pro file
QMAKE_UIC += -params to add


text:
Q: Modify Z-index on Series object in Excel 2010 I am using excel 2010.
I have a chart diagram on which i put a rectangle to surround the highest column bar.
In order to make things more readable, i would like to place this rectangle on the chart but NOT in front of the lines/bars/etc...It has to be behind them.
Shape objects (like my rectangle) have a ZIndex property than can be modified in order to achieve that. Thing is, it seems impossible to put that behind the elements of my chart, nor the chart itself.
The main reason is because Chart objects and Series objects (which are the columns inside my chart) doesn't have a Z-Index property.
Is there a way which could allow me to achieve this ? Other than modifying ZIndex property ?

A: You can move the Chart in front of the Shape, or the Shape in front of the Chart. But what you are looking to do is to stuff the Shape behind some components of the chart, but still in front of the chart background.
That, as far as I know cannot be done.
But you can simulate the effect by making the Chart's background and the Plot area transparent (no fill, instead of the default White fill) by simply right clicking and adjusting properties.
Also, you can highlight both the chart and the shape (Ctrl-Multiple Select) and lock the two together so your Shape will look like it's a part of the chart and is behind the components.
Of course, the shape will be behind the whole chart itself (by setting the appropriate Z-value, which you may find by simply clicking on Record Macro and running the formatting once to get sample code) but since the chart's background is transparent and so is the plot area's it'll look as if the rectangle's behind the lines and all.


text:
Q: How to unpack a tuple while calling an external method in Python? I call a method of an external library multiple times in my class like this:

class MyClass:

    const_a = "a"
    const_b = True
    const_c = 1

    def push(self, pushee):
        with ExternalLibrary.open(self.const_a, self.const_b, self.const_c) as el:
            el.push(pushee)

    def pop(self):
        with ExternalLibrary.open(self.const_a, self.const_b, self.const_c) as el:
            return el.pop()

The lines containing the with statement are bugging me, because they require passing the the constants as arguments every time. I would like to store the arguments in a predefined data structure like a tuple and pass that to the external library.

A: You can do this:
args = (const_a, const_b, const_c)
ExternalLibrary.open(*args)

The * syntax unpacks an iterable (tuple, list, etc.) into individual arguments in a function call.  There is also a ** syntax for unpacking a dictionary into keyword arguments:
kwargs = {'foo': 1, 'bar': 2}
func(**kwargs) # same as func(foo=1, bar=2)

You can also use both in the same call, like func(*args, **kwargs).


text:
Q: Spring Boot Entity to DTO ConverterNotFoundException I have a simple API, built with Spring Boot, where I am trying to convert entity classes to the corresponding dtos.
Student Entity
@Entity(name = "students")
@AllArgsConstructor
@Getter
@Setter
public class Student extends AbstractUpdatable<Long> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "student_id")
    private Long id;

    @Column(name = "student_first_name", nullable = false)
    @NotNull(message = "First name is mandatory")
    private String firstName;

    @Column(name = "student_last_name", nullable = false)
    @NotNull(message = "Last name is mandatory")
    private String lastName;

    @Column(name = "student_ssn", unique = true, nullable = false)
    @NotNull(message = "SSN is mandatory")
    @Size(min = 10, max = 10)
    private String ssn;

    @Column(name = "student_age")
    @Min(5)
    @Max(100)
    private Integer studentAge;

    @Column(name = "student_email")
    @Email
    private String email;

    @Column(name = "student_level")
    private Integer studentLevel; // TODO could be enum or separate entity

    @Column(name = "student_creation_date")
    private Date creationDate; // TODO check spring's feature to manage creation and update dates (auditing)

    @ManyToOne
    @JoinColumn(name = "group_id")
    private Group group;

    public Student() {
        this.creationDate = new java.util.Date(); // TODO this will be removed when spring's auditing is utilized
    }

}

Group Entity
@Entity(name = "groups")
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class Group extends AbstractUpdatable<Long> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "group_id")
    private Long id;

    @Column(name = "group_name")
    private String Name;

    @OneToMany(mappedBy = "group")
    @JsonIgnore
    private List<Student> students;

}

Student DTO
public class StudentDto extends AbstractStudentDto implements Serializable {

    private final Long id;

    private final Date creationDate;

    public StudentDto(String firstName, String lastName, String email, Long id, GroupDto group, Integer studentAge, Integer studentLevel,
                      Date creationDate) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.group = group;
        this.studentAge = studentAge;
        this.studentLevel = studentLevel;
        this.creationDate = creationDate;
    }

    public Long getId() {
        return id;
    }

    public Date getCreationDate() {
        return creationDate;
    }
}

Group DTO
public class GroupDto extends AbstractGroupDto{

    private final Long id;

    public GroupDto(Long id, String name, List<StudentDto> students) {
        this.id = id;
        this.name = name;
        this.students = students;
    }

    public Long getId() {
        return id;
    }
}

GroupToGroupDtoConverter
@Component
public class GroupToGroupDtoConverter implements org.springframework.core.convert.converter.Converter<Group, GroupDto> {

    private final ConversionService conversionService;

    @Autowired
    public GroupToGroupDtoConverter(ConversionService conversionService) {
        this.conversionService = conversionService;
    }

    @Override
    public GroupDto convert(Group source) {

        var convertedStudents = new ArrayList<StudentDto>();

        if (!CollectionUtils.isEmpty(source.getStudents())) {
            source.getStudents().forEach(student ->
                    convertedStudents.add(conversionService
                            .convert(student, StudentDto.class)));
        }

        return new GroupDto(source.getId(), source.getName(), convertedStudents);
    }
}

And a very similar StudentToStudentDtoConverter.
The issue is that when the code needs to do the conversion from any of the entities to their dtos I get

org.springframework.core.convert.ConverterNotFoundException: No
converter found capable of converting from type
[com.studentmanagement.model.Group] to type
[com.studentmanagement.dto.group.GroupDto]

Now if I try to remove the conversion of the students' list to a list of student dtos in the converter above, so the converter looks like this:
@Component
    public class GroupToGroupDtoConverter implements org.springframework.core.convert.converter.Converter<Group, GroupDto> {

        @Override
        public GroupDto convert(Group source) {
            return new GroupDto(source.getId(), source.getName(), new ArrayList<StudentDto>());
        }

    }

The conversion works with no issues (with a dummy students list of course). Am I missing something when I am adding the conversion service inside my converters?

A: I tried to replicate the issue and did a small working demo on this.
One thing I found while doing that, that could be relevant to your case, is that injecting a conversion service into a converter is not trivial (see e.g. this and this relevant issues).
Also, important as well, do not forget to register the converters, as shown below on the code samples, and e.g. here. From the error message you posted, seems like the service cannot find the needed converter.
For my demo, please note I removed the group field from the StudentDTO class to simplify things. I hope it helps, happy to share the full code as well in github.
I used the following converter for Group:
@Component
public class GroupToGroupDtoConverter implements org.springframework.core.convert.converter.Converter<Group, GroupDto> {

    private ConversionService conversionService;

    public GroupToGroupDtoConverter(ConversionService conversionService) {
        this.conversionService = conversionService;
    }

    @Override
    public GroupDto convert(Group group) {

        List<StudentDto> studentDtoList =
                group.getStudents().stream().map(a -> conversionService.convert(a, StudentDto.class)).collect(Collectors.toList());
        GroupDto groupDto = new GroupDto(group.getId(), group.getName(), studentDtoList);

        return groupDto;
    }
}

But in order to successfully inject the conversion service and register the converters I added this:
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    @Lazy
    ConversionService conversionService;

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new GroupToGroupDtoConverter(conversionService));
        registry.addConverter(new StudentToStudentDtoConvervter());

    }
}

If, for example, I comment out the first addConverter line, I get the Converter not found exception:
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [com.example.conversion_entities.Group] to type [com.example.conversion_entities.GroupDto]

Once all is done, the following test passes:
@RunWith(SpringRunner.class)
@SpringBootTest
class GroupToGroupDtoConverterTest {

    @Autowired
    ConversionService conversionService;

    @Test
    void convert() {
        Student studentA = new Student();
        studentA.setFirstName("John");
        studentA.setLastName("Doe");

        Student studentB = new Student();
        studentB.setFirstName("Jane");
        studentB.setLastName("Doe");

        List<Student> studentList = new ArrayList<>();
        studentList.add(studentA);
        studentList.add(studentB);

        Group group = new Group(1L, "groupA", studentList);

        GroupDto convertedGroupDto = conversionService.convert(group, GroupDto.class);
        assertEquals("John", convertedGroupDto.getStudents().get(0).getFirstName());
        assertEquals("Jane", convertedGroupDto.getStudents().get(1).getFirstName());
    }
}

A: I think the problem is ConversionService can't convert your classes by default. Instead try to inject a class implementing ConversionService with correct convert method implementation inside.


text:
Q: Plotting first few elements of array I have two arrays that are each 56 elements in size. I want to create several different plots. The first plot would be the first 12 elements from each of the arrays.
x=np.arange(1,57,1)
y=np.arange(1,57,1)

plt.scatter(x[0,11], y[0,11], c='r')

this results in the error:
IndexError: too many indices for array

How can I select only the specific elements from the array I want to plot?

A: IIUC, you should modify your array slice to:
plt.scatter(x[:12], y[:12], c='r')


text:
Q: Upload canvas image to the server and save to file I want to upload a canvas image and save it as a .png file on the server, which uses webapi.
I have figured out a means to upload a dataurl as a string to the server.  I have tried making a byte[] from that and saving it, but when I open the file with paint it tells me I have a corrupted file.
client:
    var dataURL = canvas.toDataURL('image/png');

Server:
    string strData = postParam.dataURL.Substring("data:image/png;base64,".Length);
    List<byte> src = new List<byte>();

    for (int i = 0; i < strData.Length; i++)
    {
    char c = strData[i];
    byte b = Convert.ToByte(c);
    src.Add(b);
    }

    System.IO.FileStream fs = System.IO.File.Create(@"D:\git\Lens\Lens.Server.UI.HTML5\reports\chartImages\hello.png", 100000, System.IO.FileOptions.None);
                System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
                bw.Write(src.ToArray());

So I think my question is , is the byte[] of the image datasource even the right thing to store in an png file or do I do something else.  Then if so I have to convert my string correctly which I might be screwing up too.

A: You need to decode the base64 string part of the data uri
string strData = postParam.dataURL.Substring("data:image/png;base64,".Length);
byte[] data = Convert.FromBase64String(strData);


text:
Q: Error in Spinnaker Pipeline Webhook stage My pipeline cannot run manually and source json shows pipeline template as invalid. Also states, #stage function could not be mapped to typedvalue. I have similar pipeline stages created from the copy of failing stage and they work as expected. But the parent one is invalid.
expressionEvaluationSummary" : { "#stage( #root.execution, 'Get SHA')
['context']['webhook']['build'['object']['sha']" : [ { "description" :
"Failed to evaluate [repository_refspec] EL1022E: The function 'stage'
mapped to an object of type 'class
org.springframework.expression.TypedValue' which cannot be invoked",
"exceptionType" :
"org.springframework.expression.spel.SpelEvaluationException

A: This was missing the pipelineId used in evaluating the expression to resolve to current instance and not of type class


text:
Q: Let $\lambda(A)$ be the Lebesgue measure of $A$. There exists an interval $I$ such that $\lambda(E \cap I) / \lambda(I) < 1-\epsilon$ (Not mentioned in title but $\epsilon$ is a number greater than $0$ and $E$ a Lebesgue measurable subset of $\mathbb{R}^n$.) I know a question equivalent to this one has been asked (here). But it was not answered. Also my thinking is a bit different. So I would love to get some help on this problem.
So far I've got:
$$\frac{\lambda(E \cap I)}{\lambda(I)} > 1- \epsilon \iff \frac{\lambda(I)-\lambda(E\cap I)}{\lambda(I)} < \epsilon$$
And also, a theorem states that, for all $\epsilon$ there exists a closed set $F\subset E$ such that $\lambda(E\setminus F) < \epsilon$ so it would sufice to prove  that there exists an interval $I$ such that
$$\frac{\lambda(I)-\lambda(E\cap I)}{\lambda(I)}<\lambda(E\setminus F).$$
I'm not sure if this helps me much but any help is appreciated. What would you do?

A: The statement is false. For example, $\mathbb{R}$ is Lebesgue measurable but $\frac{\lambda(I\cap \mathbb{R})}{\lambda(I)}=1\not< 1-\epsilon.$
(restriction to proper subset of $\mathbb{R}$ behave as $\mathbb{R}$ since $\mathbb{R}\setminus \{0\}$.)
I can prove it when $\overline{E}\neq \mathbb{R}.$
If $\epsilon \geq 1$, it does not make any sense. Thus, let's assume that $0<\epsilon<1$.
But it is trivial. Let $A=\overline{E}$ be the closure of $E$, then $A$ is Lebesgue measurable. Then $A^c$ is open. Note that $A^c$ is a countable disjoint union of open intervals. Just choose one of them,(Let's say $I$). Then clearly, $\lambda(E\cap I)=0$ and $\lambda(I)>0$ so clearly $$\frac{\lambda(E\cap I)}{\lambda(I)}=0<1-\epsilon . $$
If you want to prove that

when $E$ is positive Lebesgue measurable set then for any $\epsilon\in (0,1)$, there exists an interval $I$ such that $$\frac{\lambda(E\cap I)}{\lambda(I)}>1-\epsilon,$$

it is a little bit difficult. But the proof is as follow.
Let's assume that the statement is false. Then there exists such $\epsilon $ such that for any interval $I$$$\lambda(E\cap I)\leq (1-\epsilon)\lambda(I).$$
Note that $$\lambda(E)=\inf\left\{\lambda(U): E\subset U \text{ and } U \text{ is open.}   \right\}.$$
Thus, there exists open set $U$ such that $E\subset U$ and
$$ \lambda(U)<\lambda(E)+\frac{\epsilon}{1-\epsilon}\lambda(E) = \left(\frac{1}{1-\epsilon} \right)\lambda(E)$$
Note that $U$ is countable disjoint union of open intervals $\{I_n\}_{n\in\mathbb{N}}.$
Now observe that
$$\lambda(U)<\frac{1}{1-\epsilon} \sum_{n=1}^{\infty} \lambda(E\cap I_n)\leq \frac{1}{1-\epsilon} \sum_{n=1}^{\infty} (1-\epsilon)\lambda(I_n)=\lambda(U)  $$
And note that $\lambda(U)<\lambda(U)$ does not make sense. Thus, it is a contradiction. Therefore, the statement is true.


text:
Q: Can't unset Qt::WindowStaysOnTopHint in linux I have some widgets in  my app that must react to some signal for changing "stay on top" flag. Well, setting it to be topmost is done successfully, but I can't remove this flag. My app is very big, so I can't post all the code here. But I have some code in constructor of these my widgets, that demonstrates the problem - it's behaviour is fully the same to my widgets.
So, the problem is:

*

*after setting/unsetting the flag and calling show() widget "jumps" a little bit upward (for about height of it's caption)

*"WindowStaysOnTopHint" applied successfully, but it can't be removed

*such a behaviour is only on Linux, in Windows everything is fine

My code, that demonstrates it (ugly, but it demonstrates the problem + it is only for debugging purpose):
static QWidget* wgt = new QWidget();
static QPushButton* btn = new QPushButton(wgt);
static bool *top = new bool(true);
static QHBoxLayout *l = new QHBoxLayout(wgt);
l->addWidget((btn));
wgt->setLayout(l);
connect(btn, &QPushButton::clicked, [&](bool chk){
    if (*top) {
        wgt->setWindowFlags(wgt->windowFlags() | Qt::WindowStaysOnTopHint);
        *top = false;
    }
    else {
         wgt->setWindowFlags(wgt->windowFlags() & ~Qt::WindowStaysOnTopHint);
        *top = true;
    }
    wgt->show();
});
wgt->show();

UPD: I couldn't do this in a Qt-way, so I fixed it by using XLib


text:
Q: Get the inverse of ratio, what is the mathematical term? I need to create kind of the inversed ratio. What i mean:
Let's say there are the numbers 1,1,2 the ratio is 0.25,0.25,0.5. The sum of the ratio is of course 1. But i want the "inversed" ratio so the small numbers become great and great numbers become small. It still needs the sum of 1.
so 1,1,2 becomes 0.375,0.375,0.25
I tried around a bit and came to this algorithm:
picture of algorithm (mistake: should be 0.375,0.375,0.25)
Can i simlify the algorithm to a mathmatical expression somehow? And had this "inversed" ratio special name so i do a search for it?

A: If you want to have it so that the ratio of any two numbers in the output is the inverse ratio of the same two numbers in the input, then it's pretty simple to do:

*

*Take the multiplicative inverse of your list (so $1, 1, 2$ becomes $1, 1, \frac{1}{2}$).

*Do your ratio calculations as before (so we get $1+1+\frac{1}{2} = \frac{5}{2}$, dividing the list elements by this value gives $\frac{2}{5}, \frac{2}{5}, \frac{1}{5} = 0.4, 0.4, 0.2$)


text:
Q: How to write a dictionary that stores non ascii characters into json file in python This is my first time with python and therefore sorry if the question is obvious.
Here I have a dictionary and I want to write it into a json file. To do that I did the followings :
result = {}
result["c2i"] = c2i # c2i is a dictionary
result["data"] = data # data is a list that stores integers
with io.open("json_test.json", 'w',encoding='utf-8') as outfile:
    json.dump(result, outfile)

Unfortunately, when I do that, I got the following error:
Traceback (most recent call last):
  File "dataprocess.py", line 140, in <module>
    json.dump(result, outfile)
  File "/home/anaconda2/lib/python2.7/json/__init__.py", line 190, in dump
    fp.write(chunk)
TypeError: write() argument 1 must be unicode, not str

The content of the i2c dictionary is as follows:
>>> i2c
{49: '&', 50: '|',  56: '^', 57: '=', 58: '<', 59: '*', 60: '\xc2', 61: '\xa3', 62: '$', 63: '\xc3', 64: '\xa2', 65: '\xe2', 66: '\x82', 67: '\xac', 68: '\xef', 69: '\xbc', 70: '\xa6', 71: '\xaf', 72: '\xb7', 73: '>', 74: '+', 75: '\xab', 76: '\x97', 77: '~', 78: '\xad', 79: '\x98', 80: '\x86', 81: '\xb3', 82: ']', 83: '\x84', 84: '\x83', 85: '\xf0', 86: '\x9f', 87: '\x87', 88: '\xb1', 89: '\xb4', 90: '\xc4', 91: '\xb0', 92: '\xb6', 93: '[', 94: '\\', 95: '\xf3', 96: '\xbe', 97: '\x8d', 98: '\x81', 99: '\xe3', 100: '\xbb', 101: '\x8b', 102: '\xc5', 103: '\x93', 104: '\x85', 105: '\xe4', 106: '\xbd', 107: '\xa0', 108: '\xe5', 109: '\xe7', 110: '\xae', 111: '\xe9', 112: '\x9a', 113: '\x94', 114: '\xe6', 115: '\x88', 116: '\x91', 117: '\xa5', 118: '\xe8', 119: '\xb2', 120: '}', 121: '\xe0', 122: '\xb8', 123: '\xa7', 124: ':broken_heart:', 125: ':loudly_crying_face:', 126: ':black_rightwards_arrow:', 127: ':white_left_pointing_backhand_index:', 128: ':dizzy_face:', 129: ':cloud:', 130: ':white_right_pointing_backhand_index:', 131: ':heavy_black_heart:', 132: ':smiling_face_with_smiling_eyes:', 133: ':sparkling_heart:', 134: ':smiling_cat_face_with_heart-shaped_eyes:', 135: ':oncoming_bus:', 136: ':man_with_turban:', 137: ':confused_face:', 138: ':cross_mark:', 139: ':smiling_face_with_open_mouth_and_tightly-closed_eyes:', 140: ':party_popper:', 141: ':open_hands_sign:', 142: ':earth_globe_asia-australia:', 143: ':sleepy_face:', 144: ':pensive_face:', 145: ':weary_face:', 146: ':smiling_face_with_sunglasses:', 147: ':droplet:', 148: ':persevering_face:', 149: ':crown:', 150: ':sleeping_face:', 151: ':musical_score:', 152: ':teacup_without_handle:', 153: ':hot_beverage:', 154: ':awe|boy:', 155: ':cocktail_glass:', 156: ':worried_face:', 157: ':thought_balloon:', 158: ':cat_face:', 159: ':personal_computer:', 160: ':splashing_sweat_symbol:', 161: ':electric_plug:', 162: ':kiss_mark:', 163: ':trophy:', 164: ':airplane:', 165: ':face_with_no_good_gesture:', 166: ':princess:', 167: ':disappointed_face:', 168: ':pouting_face:', 169: ':sparkles:', 170: ':high_voltage_sign:', 171: ':bomb:', 172: ':purple_heart:', 173: ':christmas_tree:', 174: ':black_heart_suit:', 175: ':speak-no-evil_monkey:', 176: ':woman_with_bunny_ears:', 177: ':person_bowing_deeply:', 178: ':smiling_face_with_halo:', 179: ':smiling_face_with_heart-shaped_eyes:', 180: ':beating_heart:', 181: ':unamused_face:', 182: ':ok_hand_sign:', 183: ':smiling_face_with_open_mouth:', 184: ':see-no-evil_monkey:', 185: ':face_without_mouth:', 186: ':musical_note:', 187: ':hocho:', 188: ':violin:', 189: ':smiling_face_with_open_mouth_and_cold_sweat:', 190: ':basketball_and_hoop:', 191: ':person_raising_both_hands_in_celebration:', 192: ':books:', 193: ':pistol:', 194: ':happy_person_raising_one_hand:', 195: ':thumbs_up_sign:', 196: ':heart_with_arrow:', 197: ':thumbs_down_sign:', 198: ':grinning_face_with_smiling_eyes:', 199: ':weary_cat_face:', 200: ':snowflake:', 201: ':multiple_musical_notes:', 202: ':frog_face:', 203: ':umbrella_with_rain_drops:', 204: ':runner:', 205: ':winking_face:', 206: ':fire_engine:', 207: ':face_with_medical_mask:', 208: ':green_heart:', 209: ':face_with_ok_gesture:', 210: ':camera:', 211: ':french_fries:', 212: ':tropical_drink:', 213: ':smiling_face_with_open_mouth_and_smiling_eyes:', 214: ':astonished_face:', 215: ':hundred_points_symbol:', 216: ':palm_tree:', 217: ':face_with_open_mouth_and_cold_sweat:', 218: ':clinking_beer_mugs:', 219: ':dash_symbol:', 220: ':flag_for_faroe_islands:', 221: ':face_with_stuck-out_tongue:', 222: ':pedestrian:', 223: ':face_throwing_a_kiss:', 224: ':raised_hand:', 225: ':confounded_face:', 226: ':dog_face:', 227: ':police_car:', 228: ':bath:', 229: ':face_screaming_in_fear:', 230: ':bust_in_silhouette:', 231: ':baseball:', 232: ':ambulance:', 233: ':squared_sos:', 234: ':wine_glass:', 235: ':imagined...re:', 236: ':face_with_tears_of_joy:', 237: ':dancer:', 238: ':clapping_hands_sign:', 239: ':heavy_large_circle:', 240: ':face_with_stuck-out_tongue_and_winking_eye:', 241: ':hatching_chick:', 242: ':open_book:', 243: ':white_smiling_face:', 244: ':fisted_hand_sign:', 245: ':tired_face:', 246: ':face_with_stuck-out_tongue_and_tightly-closed_eyes:', 247: ':snowman_without_snow:', 248: ':information_desk_person:', 249: ':two_women_holding_hands:', 250: ':two_hearts:', 251: ':angry_face:', 252: ':headphone:', 253: ':white_heavy_check_mark:', 254: ':wrapped_present:', 255: ':floppy_disk:', 256: ':soon_with_rightwards_arrow_above:', 257: ':white_frowning_face:', 258: ':grinning_face:', 259: ':black_sun_with_rays:', 260: ':crying_face:', 261: ':aubergine:', 262: ':face_savouring_delicious_food:', 263: ':victory_hand:', 264: ':flag_for_united_kingdom:', 265: ':flushed_face:', 266: ':mouse:', 267: ':rocket:', 268: ':person_with_folded_hands:', 269: ':father_christmas:', 270: ':face_with_look_of_triumph:', 271: ':nail_polish:', 272: ':skull:', 273: ':fork_and_knife:', 274: ':expressionless_face:', 275: ':growing_heart:', 276: ':microphone:', 277: ':fire:', 278: ':sleeping_symbol:', 279: ':money_bag:', 280: ':grimacing_face:', 281: ':flexed_biceps:', 282: ':smirking_face:', 283: ':pile_of_poo:', 284: ':slice_of_pizza:', 285: ':neutral_face:'}

I believe, the keys like '\xc2' causes problems but I couldn't find a way to deal with it. I'll use these json file from another programming language later.
Edit: I use Python 2.7
EDIT 2

As suggested in one of the answers, I go with second option:
result = {}
result[u"i2c"] = {k:v.decode('iso-8859-1') for k, v in i2c.items()}
result["data"] = encoded_data
with io.open("deneme_jstonout.json", 'w') as outfile:
    json.dump(result, outfile)

However in that case, I got the following error:
Traceback (most recent call last):
  File "dataprocess.py", line 137, in <module>
    result[u"i2c"] = {k:v.decode('iso-8859-1') for k, v in i2c.items()}
  File "dataprocess.py", line 137, in <dictcomp>
    result[u"i2c"] = {k:v.decode('iso-8859-1') for k, v in i2c.items()}
UnicodeEncodeError: 'ascii' codec can't encode character u'\xc2' in position 0: ordinal not in range(128)

When I try to convert each value in the dictionary to unicode I also get an error:
Edit 3
>>> for i in i2c:
...     i2c[i] = unicode(i2c[i])
...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)

A: The thing is, JSON is Unicode, so the json module needs string data to be of unicode data type data because it is unwilling to guess the encoding of your strings for you. This is a Python2 problem, in Python 3 all strings are unicode already. You have 3 choices:
1) Use unicode literals
i2c = {
    49: u'&',
    50: u'|',
    56: u'^',
    57: u'=',
    58: u'<',
    ...
    285: u':neutral_face:',
}

If you are importing the data from some other source (API, Database, text file), the best practice is to always decode the data into unicode when it enters your application and encode the data when it leaves the application.
2) Convert string data to unicode
 result[u"i2c"] = {k:v.decode('iso-8859-1') for k, v in i2c.items()}
 result[u"data"] = data

Your example does not look like UTF-8, so I guessed Latin1, but you must know the real codec because it may not be Latin1 (and anything decodes as Latin1).
3) Use Python3
Python 3 makes everything regarding unicode more explicit. Any io operation will give you unicode strings or bytes, so there is no ambiguity. Your program will work or not, in Python 2 the program may seem to work but explode in flames from time to time.


text:
Q: Is it possible to persist a List with hibernate annotations, where E is an interface? This seems like it should be fairly straightforward, but I'm having trouble coming up with an elegant solution.
Let's use the example of a basic file system, comprised of two hibernate-annotated classes, File and Folder.
We'll abstract out the common properties of the two classes into a FileSystemObject interface:
public interface FileSystemObject {
    public String getName();
    public URI getWhere();
}

And the two classes:
File:
@Entity
@Table(name = "FILE")
public class File implements FileSystemObject, Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "FILE_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "NAME", nullable = false)
    @Index(name = "FILE_NAME", columnNames={"NAME"})
    private String name;

    @Column(nullable = false)
    private URI where;

    public File() {}

    public File(String name, URI where) {
        this.name = name;
        this.where = where;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public URI getWhere() {
        return where;
    }

    public void setWhere(URI where) {
        this.where = where;
    }
}

Folder:
@Entity
@Table(name = "FOLDER")
public class Folder implements FileSystemObject, Serializable {

    private static final long serialVersionUID = 2L;

    @Id
    @Column(name = "FOLDER_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "NAME", nullable = false)
    @Index(name = "FOLDER_NAME", columnNames={"NAME"})
    private String name;

    @Column(nullable = false)
    private URI where;

    @CollectionOfElements
    @JoinTable(name = "FOLDER_CONTENTS",
               joinColumns = @JoinColumn(name = "FOLDER_ID"))
    private List<FileSystemObject> contents;

    public Folder() {}

    public Folder(String name, URI where, List<FileSystemObject> contents) {
        this.name = name;
        this.where = where;
        this.contents = contents;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public URI getWhere() {
        return where;
    }

    public void setWhere(URI where) {
        this.where = where;
    }

    public List<FileSystemObject> getContents() {
        return contents;
    }

    public void setContents(List<FileSystemObject> contents) {
        this.contents = contents;
    }
}

Logically, the contents of a Folder could be File or Folder, so it makes sense for the contents List to be of type FileSystemObject.
Now, assuming everything is set up correctly within pom.xml, when I try to generate some schema:
mvn hibernate3:hbm2ddl

It throws the following error:
Failed to execute goal org.codehaus.mojo:hibernate3-maven-plugin:2.0:hbm2ddl (generate-ddl) on
project foo: Execution generate-ddl of goal org.codehaus.mojo:hibernate3-maven
plugin:2.0:hbm2ddl failed: Could not determine type for: com.foo.data.FileSystemObject, for
columns: [org.hibernate.mapping.Column(element)] -> [Help 1]

Hopefully someone can shed some light on this!

A: It is possible for the type there to be an Interface, but it will not work the way you've configured your entities.  In order for both Entity types to be combined in the same collection, they need to share a common supertype that is itself an Entity.  (That is, you'd need something like FileSystemObject to be a common superclass they both inherit from, that defines ID at that level.)
The problem is, consider this query:
select c from Folder f, f.contents c where f.name = 'FOLDER' and c.id = 3;

If there are both a Folder and a File that have id 3, how is it supposed to know what you want?  This is why they need to share a common superclass if they are to be in the same collection.