text:
Q: How to delay command blocks until player respawns? I have a command block line set up so that it detects for a players death, then gives them weakness for 600 seconds. It applies weakness to soon before they get out of the respawn time. If there is not way to delay a command is there a way to detect a player respawn?

A: Can you use repeaters? If you can, have one command block that detects the player's death and then have a few redstone repeaters lined up to delay the signal to the block that gives the effect.

A: Target a player who died only once they've respawned by using the @e target selector instead of @a or @p and specifying [type = player] along with any other selector arguments you're using to pick the correct player (probably a tag or scoreboard value).  This works because @a targets any player while @e only targets alive entities as of 1.18.1 Java Edition.  So, to solve your problem, you'd do something like execute as @e[type = player, tag = dead] run effect give @s weakness 600 1 true or execute as @e[scores = {deaths=1..}] run effect give @s weakness 600 1 true.  Note that if you're using a scoreboard, specifying the type is redundant because only players can have scores.

A: Your real problem is that the players can wait arbitrarily long until they click "respawn", so no fixed delay would help you. What you can instead do is detecting when they have respawned. This can for example be done by checking if they are at a location (because dead players are nowhere*):
/execute as @a[scores={deaths=1..},distance=0..] run <command>

This distance=0.. might seem useless, because you're testing for a distance of 0 or more from the command block, but what it does is only activating if you have an alive player in the same dimension. You could also do the same for Nether and End, but since you want to detect respawning, that's not necessary. Dead players have no location, so their distance from the command block isn't 0 or more, it's nothing.

*This got a bit more complicated in 1.15, because the player is still registered as being at their death location for about a second after dying. That could be very helpful in some cases, I think it even used it in an answer here already, but it complicates this case. Now you need to check if they are not at any location first and then at a location again:
execute as @a[tag=!dead,scores={deaths=1..}] unless entity @a[scores={deaths=1},distance=0..] run tag @s add dead
execute as @a[tag=dead,distance=0..] run <command>
execute as @a[tag=dead,distance=0..] run scoreboard players set @s deaths 0
execute as @a[tag=dead,distance=0..] run tag @s remove dead

The first command is the real magic: Every player who died gets tagged, but only once no player who died can be found at any location anymore. This still fails if another player is currently in its death animation, I don't think this can be avoided.
Then you just run whatever command you want at a player that used to be at no location, but is at some location now. Finally, you reset the scoreboard (implied in my 1.14 solution) and the tag.

A: The repeater is a redstone block that when you give a redstone signal from the back, there will be a delay and then will transmit the redstone signal from the front. Try adding a repeater between the redstone source and your command block. Each repeater can be set to give a different delay, and if you need a longer delay, try lining up several.

A: You can make a scoreboard that detects when they spawn back in and set a /execute command when the scoreboard reaches a certain value. Depending on the spawn location, you can use /execute at or execute if to detect when a player spawns and we're they spawn. There are probably better videos of explaining this but I use this a lot


text:
Q: Overlapping appointments in Outlook 2003 I'm using Microsoft Outlook 2003 (Home and Student, if that makes any difference, which I doubt) as my calendar, and I have one minor gripe: it can't really handle appointments that don't begin and end right on the half-hour mark. For instance, if I have a class that ends at 9:22 AM and another class that begins at 9:27 AM, they will appear to overlap in the day view. Not a big deal, but it bugs me nonetheless. Anybody know of a hack or patch that will fix this issue? I've searched the Outlook documentation as well as Google to no avail.

A: Items in the calendar are rounded "out" (away from the middle of the appointment, effectively) to the nearest time step, which by default is 30 minutes. So, if something finishes at 9:22 it will round "out" to 9:30, while something starting at 9:27 will round "out" to 9:00, as so they overlap.
However, what no one here has yet mentioned, is that you can change the time step that is used and thus change the amount of "rounding" that can potentially be applied to an appointment entry. This isn't a perfect fix, and does restrict you to certain step sizes, but is the best option that is natively available in the software.
Please note that this does have the (potentially negativE) effect of "zooming in" the calendar if you select a shorter time step.
To make this change you simply right-click on the time-scale next to the calendar and select the desired step size:

A: Use the time select drop down to pick the time closest to what you want to use. (9:30 AM to follow your example)
Then notice when you bring the mouse over the time your cursor changes to the Eyebeam text cursor.
Double click on the minutes (i.e. :30) to select them.
Then type what you want it to be (i.e. 22).
Then save the appointment.
The same process works if you want to change the start time of your appointment.  However, Outlook still assumes 1/2 hour increments so you may have to reset your end time as well prior to saving the appointment.

A: Seems like not possible to me - this still happens in the preview of Outlook 2010 and I'd guess it's because it wants at least 30 minutes of "height" to render the text in the appointment box.
If I enter two meetings which are longer than 30 minutes it works in Outlook 2010 - they'll stack properly. Like booking meeting 1 at 11:00-13:22 and meeting 2 at 13:27-15:30.
I'm curious as to whether the same "workaround" (longer meetings) works for your Outlook 2003.

A: I downloaded Mozilla Sunbird and found that it actually supports this type of schedule, so I'll be using it in the future.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Orientability of manifold How to prove the following theorem (or where the detailed proof can be seen, since it isn't proved in lectures I've attended):
Two basis of tangent space of manifold have same orientation if matrix of transition map from one base to another has positive determinant. This defines relation of equivalence among basis of tangent space, with two classes of orientation. Choice of class of orientation is continuous in point $p$ if exists neighborhood of that point $U_p$ and locally defined  movable frame $X_1,\dots X_n$ in neighborhood $U_p$, such that is for every $q\in U_p$ one represent of chosen equivalence class $X_{1q}\dots X_{nq}$.
Show that this definition is correct and prove that manifold is orientable iff exists choice of class of orientation on manifold which depends continuously of points on manifold.
Thanks in advance.

A: If you define orientability in terms of the existence of a nowhere-zero top $n$ -form $w$ , then you can show (as a result of multilinear algebra), that if $w_p(X_p1,X_p2,..,X_pn) \neq 0$ (where $X_p1, X_p2,...,X_pn$) , and $T$ is a linear map between $T_p , T_q $ with $Det (T) \neq 0$ ,  then $w_q(T(X_q1),..,T(X_qn)) \neq 0$ , for any $p,q$ in the manifold. Then the existence of this linear map $T$ between tangent spaces at any two different points guarantees the existence of a nowhere-zero top form.


text:
Q: Recursion and Binary Trees #Get length of the longest path through recursion
def max_height(node):
    if not node:
        return 0
    left = max_height(node.left) #Base Case based on my understanding
    right = max_height(node.right) #Base Case based on my understanding
    return max_height(left, right) + 1

I keep calling the max_height to get the length but I'm getting an error. I've thought of three possibilities:
1) I misunderstand the concept of the base case and I don't actually have a base case.
2) I'm not properly spacing Python code.
3) I'm not recursively getting the height of the BST at all but rather the width of the tree, which is affecting later calculations.
I know it is similar to this question, but the main difference is that I'm really trying to use recursion , where the other question used iteration and merely called it recursion.
how to find the height of a node in binary tree recursively

A: *

*The base case is where the recursion stops and you have one: not node (node == None)

*I don't see an issue with the spacing... Make sure you use only tabs or only spaces

*This does produce the height: the number of nodes from root to leaf along the longest root-leaf path. At every node level, you add 1, and follow the higher subtree.
def max_height(node):
    if not node:  # this is the base case:
        return 0  # where all recursive calls eventually stop
    left = max_height(node.left)    # <- these are the recursive calls:
    right = max_height(node.right)  # <- function x is called inside function x
    return max(left, right) + 1  # max here, not max_height

Note that this is merely a more verbose version of this answer to the question you linked.

A: All answered were right but, I faced little problem while writing inside the class;
So, the code goes like this, I hope this helps.
    class Tree(object):
        def height(self, root):
            if root == None: #root == None
                return 0
            else:
                return 1 + max(self.height(root->left), self.height(root->left))
t = Tree()
t.height(t)


text:
Q: csv line parsing, printing extra line at end I have been supplied a CSV line parser to use in a program, and it seems to have a bug where if there is a blank line at the end of the text file it prints out an empty line, like so
My input is this
test, does, this, work
1, second, line, same

My output looks like this. Not only does it cut off the last word, but it prints out the empty line.
test = 1
 does =  second
 this =  line
 work =  same
test =

What it's supposed to do is match every word with the coinciding one in the top line, which it does, but I don't know where the last "test = " is coming from. Here's the code I was supplied, any ideas about what's wrong with it would be a huge help. Thanks.
/*
 * Just an array of characters representing a single filed.
 */

typedef char f_string[MAX_CHARS+1] ;    /* string for each field */

/*
 * A parsed CSV line, with the number of fields and upto MAX_FIELDS themselves.
*/

typedef struct {
    int nfields ;               /* 0 => end of file */
    f_string field[MAX_FIELDS] ;        /* array of strings for fields */
} csv_line ;

/*
 * Returns true iff the character 'ch' ends a field. That is, ch is end of file,
 * a comma, or a newline.
 */

bool is_end_of_field(char ch) {
    return (ch == ',') || (ch == '\n') || (ch == EOF) ;
}

/*
 * Return the minimum of two integers.
 */

int min(int x, int y) {
    return x < y ? x : y ;
}

/*
 * Read the next field from standard input. Returns the value of getchar() that
 * stopped (terminated) the field.
 */

int get_field(f_string field) {
/**BEGIN_SOLN**/
    int i ;
    int next_char ;

    next_char = getchar() ;
    for ( i = 0 ; ! is_end_of_field(next_char) ; ++i ) {
        field[i] = next_char ;
        next_char = getchar() ;
    }

    field[i] = '\0' ;
    return next_char ;
/**END_SOLN**/
}

/*
 * Read in a CSV line. No error checking is done on the number of fields or
 * the size of any one field.
 * On return, the fields have been filled in (and properly NUL-terminated), and
 * nfields is the count of the number of valid fields.
 * nfields == 0 means end of file was encountered.
 */

csv_line get_line() {
/**BEGIN_SOLN**/
    csv_line line ;
    int fi = 0 ;    /* index of current field in line */
    int stop_ch ;   /* character that terminated the last field */

    stop_ch = get_field(line.field[fi++]) ;
    while ( stop_ch == ',' ) {
        stop_ch = get_field(line.field[fi++]) ;
    }

    line.nfields = (stop_ch == EOF) ? 0 : fi ;
    return line ;
/**END_SOLN**/
}

/*
 * Print a CSV line, associating the header fields with the
 * data line fields.
 * The minimum of the number of fields in the header and the data
 * determines how many fields are printed.
 */

void print_csv(csv_line header, csv_line data) {
/**BEGIN_SOLN**/
    int i ;
    int nfields = min(header.nfields, data.nfields) ;

    for ( i = 0 ; i < nfields ; ++i ) {
        printf("%s = %s\n", header.field[i], data.field[i]) ;
    }
/**END_SOLN**/
}

/*
 * Driver - read a CSV line for the header then read and print data lines
 * until end of file.
 */

int main() {
    csv_line header ;
    csv_line current ;

    header = get_line() ;
    current = get_line() ;

    while ( current.nfields > 0 ) {
        print_csv(header, current) ;
        current = get_line() ;
    }

    return 0 ;
}

A: bool is_end_of_field(int ch) {
    return (ch == ',') || (ch == '\n') || (ch == EOF) ;
}

bool get_field(f_string field){
    int i ;
    int next_char ;
    for ( i = 0 ; ! is_end_of_field(next_char=getchar()) ; ++i ) {
        field[i] = next_char ;
    }
    field[i] = '\0';
    return (next_char == ',')? true :  false;
}

csv_line get_line() {
    csv_line line ;
    int fi = 0;
    while(get_field(line.field[fi++]))
        ;
    line.nfields = line.field[fi-1][0] ? fi : 0;
    return line ;
}


text:
Q: What will be the best performance scenario between database fetch or php generation I have a scenario where I just cannot put together which would yield the best performance results. My desire is performance,
I have a few big strings stored in a SQL database
Example:
0,0,0,0,0,0,0,0,0,2,4,4,0,0,0 - This can be (Say 1000 - 20000) characters long(Mostly 0's)
Now I would like to know what will be the best for performance. To keep them in the above format and dong a mysqli fetch or to convert it to something like:
Compressed Example: C0-9,2,4,4,C0-3
Where the number following the - a count. Then to reconvert them before usage. There are mostly huge blocks of 0's so I don't need to worry about condensing other numbers like this.
I know that the second option will have a positive effect on my database sizes. But I am not sure about optimum performance in this case.

A: You can do compression within PHP itself, which would be more efficient than trying it  yourself.
link to gzcompress()
The basic idea is that you can compress the data when putting it into the database, then decompress it on the way back out. It will improve performance since MySQL will have less memory in use, and function calls are not hugely costly


text:
Q: Can docker buildx build utilize a docker swarm for multi-platform building? Just got done compiling a buildx multi-arch docker container that includes amd64, arm64 and armv7. It took about two hours to build -- with the armv7 portion being particularly slow. It only takes about 15 minutes to build natively on a RaspberryPi3.
I've setup a Docker swarm with 4 nodes, including each of the architectures I want to build for, but I haven't been able to work out how to setup the buildx cluster to use these native nodes.
I'd appreciate some guidance from anyone that's been down this particular road!
Edit:
I've made some progress with this, and here's what I know so far:
buildx clusters have nothing to do with docker swarm -- it's a separate thing
ssh public key authentication needs to be setup between the ssh "client" and "server" with your platform-specific target build machines being the servers in this case, and here's a good link for doing that:
https://www.ssh.com/academy/ssh/copy-id

test that ssh authentication is working from the machine initiating your cluster, with:
docker -H ssh://username@hostname info

you should see docker client and server info returned
create a new builder on the machine you'll be running the buildx from in the form:
docker buildx create --name <your_cluster_name> --node <your_node_name> --platform <your_desired_build_platforms> --driver-opt env.BUILDKIT_STEP_LOG_MAX_SIZE=10000000 --driver-opt env.BUILDKIT_STEP_LOG_MAX_SPEED=10000000

create additional target build platforms just like the above, but add --append to the options
docker buildx ls

is used to confirm the builder, nodes and platforms (the ones with an * should be what you specified and will override defaults.
docker buildx use <your_cluster_name>

will change the default builder
docker buildx inspect --bootstrap

will initiate your cluster multi-arch multi-platform builder, including downloading the buildkit image on each platform.
I had issues here, with one of my platforms requiring multiple attempts with docker buildx inspect --bootstrap. Ultimately, for my modest armv7 machine, I downloaded the:
moby/buildkit:buildx-stable-1

image on that machine first, and then ran buildx inspect from the machine I'm using to initiate the build. With the image already present, the container was spun-up without further issue.
It all looks to be setup correctly:
bnhf_cluster *  docker-container
  bnhf_cluster0 unix:///var/run/docker.sock running                linux/amd64*, linux/amd64/v2, linux/amd64/v3, linux/arm64, linux/riscv64, linux/ppc64le, linux/s390x, linux/386, linux/mips64le, linux/mips64, linux/arm/v7, linux/arm/v6
  rpi6          ssh://pi@raspberrypi6       running                linux/armv7*, linux/arm/v7
  rpi5          ssh://pi@raspberrypi5       running                linux/arm64*, linux/arm/v7, linux/arm/v6

Next, I'll find something new to try out a mutli-arch multi-platform build, as my primary project is all cached by buildx now -- so wouldn't be a good test.
I found this post to be the most helpful in getting multi-arch multi-platform buildx configured:
https://medium.com/@spurin/using-docker-and-multiple-buildx-nodes-for-simultaneous-cross-platform-builds-cee0f797d939

If you use portainer, you should see something like this in your container list on each of your platform specific targets, after the cluster is created:

Edit #2:
Wow, did that work well! I decided to build my primary application with the --no-cache option. The same build that took over 2 hours (with some layers already cached) on an 8th Gen i7 (4 cores, 8 threads, 32GB RAM) running Debian 11 in a WSL2 instance, took 742 seconds.
Sending the arm64 and arm/v7 jobs even to lowly Raspberry Pis is a huge improvement over the emulation offered with Docker Desktop.


text:
Q: Angular nxg-translate with monorepo: merge translation files The project is using NX monorepo structure. Right now there are three apps using three libs. All translation files for ngx-translate package are placed respectively at apps/[app-name]/assets/i18n/[language].json
Now I want to split these app translation files into several files to avoid repeating the translation strings, so there would be this structure:
apps
 |- [app]
       |-i18n
           | [lang].json
       |- assets
           |- i18n [empty at first]

libs
 |- [lib]
       |-i18n
           | [lang].json

The idea is that when an app is being built, a node(?) script would look for specific json files and combine them into one and place it under apps/[app]/assets/i18n so that the ngx-translate loader is still using one source for the app translations.
Also, as soon as a json file has been updated, the script should rewrite the existing file with the newly generated.
How would you proceed?


text:
Q: ModelState.IsValid is false when model has a foreign key I have a MachineSettings entity and this entity has a Machine entity as a foreign key.
public class Machine
{
    [Key]
    public int MachineId { get; set; }

    [Required]
    [Display(Name = "Machine Type")]
    public string MachineName { get; set; }
}

public class MachineSettings
{
    [Key]
    public int MachineSettingId { get; set; }

    [Required]
    public string Password { get; set; }

    [Required]
    public int ReferenceKeyLength { get; set; }

    [Required]
    public virtual Machine MachineId { get; set; }
}

In my controller class, when I created an Edit method as POST:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(MachineSettings machineSettings)
{
        if (ModelState.IsValid)
        {
            db.Entry(objapp).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(machineSettings);
}

On the page I have shown the list of machines in drop down list, when do the changes and select another machine in dropdown and click on save. The Edit method is called with a MachineSetting object. Here my ModelState.IsValid always false.
On checking the object in debug mode, I am getting the MachineId from the drop down, but MachineName is not returned, so how to avoid MachineName checking in this so that ModelState.IsValid property will be true?

A: try to fix the classes
public class MachineSettings
    {
        [Key]
        public int MachineSettingId { get; set; }

        [Required]
        public string Password { get; set; }

        [Required]
        public int ReferenceKeyLength { get; set; }

        [Required]
        public int? MachineId { get; set; }

        public virtual Machine Machine { get; set; }
    }

public class Machine
    {
        [Key]
        public int MachineId { get; set; }

        [Required]
        [Display(Name = "Machine Type")]
        public string MachineName { get; set; }

         public virtual ICollection<MachineSettings> MachineSettings { get; set; }
    }

and create view model for the view
public class MachineViewModel
{
public MachineSettings  MachineSettings {get; set;}
public IEnumerable<SelectListItem> Machines { get; set; }

}

and action
public ActionResult Edit(MachineViewModel viewModel)

A: Maybe you should use a specific class for your ViewModel. ViewModels are for Views(UI) <--> Controller intercommunication, and usually are diferrent classes than the persistance (EF) layer. So your ViewModel doesn't even needs a full Machine property. Could be something like that:
public class MachineSettingsViewModel
{
    public int MachineSettingId { get; set; } // Only if you are using the ViewModel for edit

    [Required]
    public string Password { get; set; }

    [Compare("Password")]
    public string ConfirmPassword { get; set; }

    [Required]
    public int ReferenceKeyLength { get; set; }

    [Required]
    public int MachineId { get; set; }

    public IEnumerable<SelectListItem> Machines { get; set; } // Collection with the options for the machine selector. Must be filled in the controller from query to service or DB
}

The ViewModel may include properties only used in the view, or needed for form validation but not needed in the DB.
In the controller "Get" action, you create and fill the viewmodel, then you pass it yo the view, and in the "Post" method you validate the viewmodel and convert it to a entity to be saved in the DB.
Take a look at What is ViewModel in MVC?. It's a more detailed explanation of ViewModels vs Models.


text:
Q: jquery change attribute declaration using a CMS which is automatically adding ="" to an attribute I have on an  on page save - I am trying to hack a solution in jQuery to remove it... but cant seem to get it to work.
So...
I want the markup to be:
Watch now

But - on save in the CMS the page is saved as below:
Watch now

So,  data-lity is being made data-lity="" and it messing up the jQuery lightbox function....
Is there a way - I can find all instances of data-lity="" post page load and revert them back to data-lity?

A: I hacked the lity.js to add data-lity="" as a valid attribute to allow it to work.
At very end of lity.
//$(document).on('click.lity', '[data-lity]', lity);
$(document).on('click.lity', '[data-lity]', '[data-lity=""]', lity);

This made it work.


text:
Q: How can I get a program to return True for an integer with all odd digits? The question asks to make a program that would return true if a given integer has digits that are all odd within it and false otherwise.
I got something simple working but it only works when the numbers are in a list and not just when they are given as integers.
input:
def test3(n):

  for x in n:
    print (x%2 != 0)

test3([13579])

Output:
True

input:
def test3(n):

  for x in n:
    print (x%2 != 0)

test3(13579)

output:
Traceback (most recent call last):
  File "main.py", line 86, in <module>
    test3(13579)
  File "main.py", line 83, in test3
    for x in n:
TypeError: 'int' object is not iterable

Expected Output:
True

There was a hint that was given for the question as well which is:
Hint:
To extract the lowest digit of a positive integer n, use the expression n % 10. To extract all other digits except the lowest one, use the expression n // 10. Or, if you don't want to be this fancy, first convert the number into a string and work there. (There is a more general and fundamental idea hidden in plain sight in this technique.)```

A: You are messing with integer and string types. For iterating over the digits, we have to turn the integer into a string first, and then reconvert each digit into an integer to check whether it is odd or even. This is kindly ignoring the hint given, but I think it is even more elegant than the way the hint suggests :) (But this is debatable.)
def odd_digits_only(number: int) -> bool:  # this is equal to
# def odd_digits_only(number):
   for digit in str(number):
       if int(digit) % 2 == 0:
           return False
   return True

This could be shortened using list comprehension and all:
def odd_digits_only(number: int) -> bool:
    return all([int(digit) % 2 != 0 for digit in str(number)])


text:
Q: Javascript spread async generator into Array Нello, if I have a generator such as:
let myGen = function*() {
  yield 1;
  yield 2;
  yield 3;
};

I use nifty shorthand to dump generator values into an Array with [ ...myGen() ]:

let myGen = function*(){ yield 1; yield 2; yield 3; };
console.log([ ...myGen() ]);

My question is: is there an equivalent of this for async generators?
For example for this generator:
let myGen = async function*() {
  for (let i = 1; i <= 3; i++) {
    await new Promise(r => setTimeout(r, 100));
    yield i;
  }
}

What is the cleanest way to dump all generator values into an Array?
Here are some attempts:

let myGen = async function*() {
  for (let i = 1; i <= 3; i++) {
    await new Promise(r => setTimeout(r, 100));
    yield i;
  }
};

let attempts = [
  async () => [ ...myGen() ],
  async () => await [ ...myGen() ],
  async () => [ ...(await myGen()) ]
];

(async () => {
  for (let i = 0; i < attempts.length; i++) {
    try {
      console.log(`Attempt ${i + 1} success: ${await attempts[i]()}`);
    } catch(err) {
      console.log(`Attempt ${i + 1} failure (${err.message})`);
    }
  }
})();


text:
Q: JWT verification of signature on each page? I am fairly new to JWT and I need to implement it. We use angular on client and PHP with composer on backend. I already know basics on verification and token forming. So I can form the token and sign it on server side, then send it to cient side for saving in a localStorage or somewhere similar. My question is, on subsequent requests of browser for some page, do I need to check the signature? Seems to be like I do, since merely checking the existence of token on client-side doesn't do much. Please advise? Thanks,

A: Once the Jwt is stored on the client side, on every request made to the server, it has to be checked and verified before serving the page requested.
If the token doesn't exists, the client needs to be authenticated.   If the token exists but doesn't match the signature, the client needs to get a new one, so it needs to re-authenticate.
So token verification is mandatory each time you have to pass through the server.


text:
Q: ms access 2007 SQL "not like" is ignoring blank cells I'm confused by some SQL I am trying to run. Here's a sample dataset
Username ID        Text1
red55   1235342     fdfdf
black   5542121     sdsd
red32   5542145     sffrds
green   5542911
bluee   5333121     ffds

So the SQL would be
SELECT username, ID, Text1
  FROM user_info
 WHERE username NOT LIKE 'red*'
       AND text1 NOT LIKE 'sd*';

So I would expect to see a result set of
Username ID        Text1
green   5542911
bluee   5333121     ffds

But it doesn't work. It seems to ignore the blank values. I would only see the one record (not like the two above). I need my SQL to simply say show me the records which dont start "red" AND also any records which don't start with "sd". Yet it either gets rid of them all AND blanks, or if I use an OR statement, gets rid of none.
Any ideas? I am stuck here!

A: You need to explicitly handle the nulls.  One option would be:
SELECT username, ID, Text1
FROM user_info
WHERE (username Is Null OR username NOT LIKE 'red*')
  AND (text1 Is Null OR text1 NOT LIKE 'sd*')


text:
Q: How do I keep the value when I refresh the browser and move the page while using mobx? We are currently using next.js to ssr. Refreshing or going back on a specific page initializes all stores.
I've been thinking about mobx-persist to solve this problem, but mobx-persist seems to only work in a browser environment.
Here's the question.

*

*Is there a way to keep the value of a particular element in the store whenever I refresh the browser without using mobx-persist?

*Is there a way to get the retained elements of the store from the ssr environment?
Cookies, sessions, mobx-persist were not available in the ssr environment.
Below is the current react setting.
app.js
import React from 'react'
import { Provider } from 'mobx-react'
import { UserStore } from '../stores/userStore'

//_app.js
const App = ({ Component, pageProps }) => {
    const userStore = UserStore(pageProps.initialState)

    return (
        <Provider
            UserStore={userStore}
        >
            <Component {...pageProps} />
        </Provider>
    )
}

export default App

userStore.js
const isServer = typeof window === 'undefined'
useStaticRendering(isServer)

class Store {
    @observable initialData = null
    @observable userId = null
    @observable userPw = null

    // @action...

    hydrate = async (initialState) => { // SSR INIT
        // this.initialState = initialState
    }

    export function initUserStore(initialState = null) {
           this.hydrate(initialState)
        // return store
    })

    export function UserStore(initialState) {
        const store = useMemo(() => initUserStore(initialState), [initialState])
        return store
    }

}

index.js (ssr)
// index.js ssr
export async function getServerSideProps(context) {
    const UserStore = initUserStore() // store init
    // How can I get the value of the element (userId, userPw) of the store when it is in a refresh or server-side environment?
    .
    .
    .
    return {
        // props :{
            // initialState:{

            // }
        }
    }
})

The key issue is to import elements stored in the in the getServerSideProps(ssr) environment without store initialization after refresh.


text:
Q: Python loop for :1/30 + 2/29 + 3/28 Hello everyone I have a noob question.
how do I set up the following code to print:
1/30 + 2/29 + 3/28..........30/1
The numerator is increasing \ denominator decreasing
I have the following:
for i in range(1,31):
    v = i
for j in range(30,0,-1):
    t = j
    print(v/t)

but prints
1.0
1.0344827586206897
1.0714285714285714
1.1111111111111112
1.15384615384.........

how do I get 1/30 + 2/29 + 3/28.....
Thank you for your help and guidance.

A: You only need one loop! The denominator is always 31 minus the numerator.
r = 0
for i in range(1,31):
    r += i / (31 - i)
print(r)

A: What's happening here is that your numbers are being evaluated to a floating-point number before being printed. Since you want to print them without evaluating, you should be inserting them into a string. The following line demonstrates how to insert variables into the output without evaluating them:
print "%d/%d" % (v,t)

See http://docs.python.org/release/2.5.2/lib/typesseq-strings.html for information about how to format strings for the print function.
However, this still puts each result on a separate line, because the print function automatically inserts a new line. You could build a string with the following loop (notice how you can neatly pack it into one loop rather than two because you can get the denominator by subtracting):
string = ''
for i in range(1,31):
    string += "{}/{} + ".format(i, 31-i)
print string

and this will give you "1/30 + 2/29 + ... + 30/1 + ", but this still includes the last plus sign and surrounding spaces. To fix that, change the last line to
print string[:-3]

which removes those last characters.
See http://docs.python.org/2/library/string.html#formatstrings for information about how to use the format function.

A: print (" + ".join(["%s/%s"%(num,denom)for num,denom in zip(range(1,31),range(30,0,-1))]))

I think at least
zipping together (1,2,3...,30) and (30,29,28...,1) results in a new tuple ((1,30),(2,29),...,(30,1))
you then iterate over this putting each numerator and denominator into a string resulting in a list like , we do this with format strings "%s/%s"%numerator,denominator , although it would be better form to use "%d/%d" instead but thats another story
["1/30","2/29",...,"30/1"]
then you simply join this list using ' + ' as the glue

A: I presume you want the strings instead of the numerical values, correct?
s = ''
for j in range(30, 0, -1):
    s += "{}/{} + ".format(31-j, j)
print s[:-2]

Read this documentation to get a grasp of it.  Essentially, it's formatting the string, using the two pairs of curly braces as placeholders, and passing in the value 31-j in the first slot, and j in the second.
Surely there is a more elegant way to do it, but this is the quick and dirty method.

A: I'm not sure exactly what you're trying to do, but you can do it with just a single loop.  Each time through the loop, the denominator is just 31 minus the numerator:
from fraction import Fraction
for num in range(1,31):
    den = 31 - num
    fraction_string = "%d/%d" % (num, den)
    fraction_value = Fraction(num, den)
    quotient = num / den
    #... do stuff with whichever of the above you want

When you're building a result - either adding to a sum, or appending to a string, or outputting something on every iteration - you can do that more succinctly with list comprehensions and list functions.  For example, instead of something like this:
quotientList = []
for n in range(1,31):
    quotientList.append( n / (31 - n) )

You can just do this:
quotientList = [ n / (31 - n) for n in range(1,31) ]

And instead of this:
total = 0
for n in someList:
   total = total + n

You can just do this:
 total = sum(someList)

Putting those concepts together, here are three possibilities I see for what you're trying to do:

*

*Print out the literal string 1/30 + 2/29 + 3/28 +...+30/1:
print( " + ".join( "%d/%d" % (n, 31-n) for n in range(1,31) ) )

*Evaluate that as an arithmetic expression and print the result:
print( sum( n/(31.0-n) for n in range(1,31) ) )

*... but as a fraction instead of a decimal:
from fractions import Fraction
...
print( sum( Fraction(n,31-n) for n in range(1,31) ) )


text:
Q: Adding extra species in a model I am currently working on a model of competition for resources between different species.
I have 6 species competing for 3 resources. The first 3 species start at =0. the 4th species is added at t=1000 days, the 5th species is added at t=2000 days and the 6th species at t=5000.
The first part is going well, but I can't seem to work out how I can get the last 3 species to be added later in the simulation.
Can someone help me with this?
My code:
    (* Basic competition model *)
  (* Ns[i] \[Rule] population abundance of species i *)
  (* R[j] \[Rule] availability of resource j *)

  (* constant equation stuff: *)
  (* growth function of species i considering R of each resource at \
 time t *)
 \[Mu][i_, t_] :=
   Min[(r[[#]]*R[#, t])/(Ks[[#, i]] + R[#, t]) & /@ Range[k]];

 (* differential equations for Ns and R *)
 dNs[i_] := D[Ns[i, t], t] == Ns[i, t]*(\[Mu][i, t] - m[[i]]);
dR[j_] :=
  D[R[j, t], t] ==
   d*(S[[j]] - R[j, t]) -
    Sum[c[[j, i]]*\[Mu][i, t]*Ns[i, t], {i, 1, n}];
(* Initialize parameters: 5 species, 5 resources, chaos *)
n = 6; (* number of species *)
k = 3; (* number of resources *)
tMax = 10000; (* time steps (days) *)
r = ConstantArray[1, n]; (* maximum growth rate of species *)
m = ConstantArray[0.25, n]; (* mortality rate of species *)
S = {6, 10, 14}; (* supply concentration of resources *)
d = 0.25; (* system turnover rate *)
Ks = ( {
   {1, 0.9, 0.3, 1.04, 0.34, 0.77},
   {0.3, 1, 0.9, 0.71, 1.02, 0.76},
   {0.9, 0.3, 1, 0.46, 0.34, 1.07}
   });  (* Subscript[K, ji ]= half saturation constant of resource j \
for species i *)
c = ({
   {0.04, 0.07, 0.04, 0.1, 0.03, 0.02},
   {0.08, 0.08, 0.1, 0.1, 0.05, 0.17},
   {0.14, 0.1, 0.1, 0.16, 0.06, 0.14}
    });  (* Subscript[c, ji] = content of resource j in species i *)
(* Ns and Rs at time t = 0 *)
initNs = (Ns[#, 0] == 0.1 + #/100) & /@ Range[n];

initR = (R[#, 0] == S[[#]]) & /@ Range[k];

(* make a list of n many Ns equations, and k many R equations *)
sysNs = Array[dNs[#] &, n];
sysR = Array[dR[#] &, k];
(* make lists of variables to be solved for *)
resultsNs = Array[Ns[#, t] &, n];
resultsRs = Array[R[#, t] &, n];
sol2 = NDSolveValue[{sysNs, sysR, initNs, initR}, {resultsNs,
    resultsRs}, {t, 0, tMax}];
solNs2 = sol2[[1]];
solR2 = sol2[[2]];
Plot[solNs2, {t, 0, 10000}]


text:
Q: Grails giving me 404 on controller when submitting form I have a basic controller, just like this:
class BookingController {

    def periodCheck(){

    }

    def periodInput(){

    }

Both booking/periodCheck.gsp and booking/periodInput.gsp have been created, and they work if I access typing the URL directly.
However, I have a form in periodInput.gsp that is supposed to send some data to periodCheck, and every time, when I send the form, I get a 404 error, saying that The requested resource (/hoteledison/booking/periodCheck) is not available. The form is defined like this:
<g:form action="periodCheck">
        <!-- here would go the fields -->
        <g:actionSubmit class="btn" value="Comprobar" />
</g:form>

What am I doing wrong? I've also tried defining allowedMethods in the controller, but that does not help.

A: Ok, according to this blog post, there's a difference between using actionSubmit and submitButton. For forms like mine, with just one action, I should have used the later.
Now it's working.


text:
Q: Showing a message from an async task I am doing data fetch from net in an external task.
Now this fetch happens in two steps. So I want to display some message after the first step.
This will happen in the async task not on the UI task.
On the main UI task I already have a progress bar in the preexecute method.
I would like to know if there is a way to display something from the background async task.
I saw handle to be used for threads. Do we have something similar for async task?

A: AsyncTask has an onProgressUpdate method which runs on the UI thread. Couldn't you use that somehow?

A: You have to Override the onProgressUpate Method of your AsyncTask. There you can do the stuff to Display the Text.
To trigger onProgressUpdate you have to call publishProgress() in your doInBackground-Method.


text:
Q: wierd behaviour of unset php I am developing an e-commerce website on which i need to store sessions inside database.I did that by implementing SessionHandlerInterface Class that is provided by the php itself.However it works totally fine and did store sessions inside the database , as well as read them properly.
However I am facing problem when I am using unset  to unset a session variable.Sometimes it does work.Sometimes it doesn't.
For example:If i have a session variable by the name ABC unset might delete it from the database or it doesn't deletes the variable.
<?php
//inc.session.php
require_once 'RemoteAddress.php';

class SysSession   implements SessionHandlerInterface
{
    private $remote_write;
    private $remote_read;
    private $link;
    private $ip_address_write;
    private $ip_address_read;

    public function open($savePath, $sessionName)
    {
        $link = new mysqli("localhost","root","","cakenbake");
        if($link){
            $this->link = $link;
            return true;
        }else{
            return false;
        }
    }
    public function close()
    {
        mysqli_close($this->link);
        return true;
    }
    public function read($id)
    {
        $this->remote_read=new RemoteAddress();
        $this->ip_address_read=$this->remote_read->getIpAddress();
        $stmt=$this->link->prepare("SELECT `Session_Data`,`ip_address` FROM Session WHERE `Session_Id` = ? AND `Session_Expires` > '".date('Y-m-d H:i:s')."'");
        $stmt->bind_param("s",$id);
        $stmt->execute();

        //$result = mysqli_query($this->link,"SELECT Session_Data FROM Session WHERE Session_Id = '".$id."' AND Session_Expires > '".date('Y-m-d H:i:s')."'");
        /*$result=$this->link->prepare("Some query inside")
         * This shows up an error stating prepare method not found
         *
         */
        $res=$stmt->get_result();

        if($row=$res->fetch_assoc()){
            if($this->ip_address_read==$row['ip_address'])
            return $row['Session_Data'];
            else return "";
        }else{
            return "";
        }
    }
    public function write($id, $data)
    {
        $this->remote_write=new RemoteAddress();
        $this->ip_address_write=$this->remote_write->getIpAddress();
        if(!empty($data))
        {
            $DateTime = date('Y-m-d H:i:s');
            $NewDateTime = date('Y-m-d H:i:s',strtotime($DateTime.' + 1 hour'));
            $stmt=$this->link->prepare("REPLACE INTO Session SET Session_Id = ?, Session_Expires = '".$NewDateTime."', Session_Data = '".$data."', ip_address = '".$this->ip_address_write."'");
            $stmt->bind_param("s",$id);

            // $result = mysqli_query($this->link,"REPLACE INTO Session SET Session_Id = '".$id."', Session_Expires = '".$NewDateTime."', Session_Data = '".$data."'");
            if($stmt->execute()){
                return true;
            }else{
                return false;
            }
        }

    }
    public function destroy($id)
    {

        $stmt = $this->link->prepare("DELETE FROM Session WHERE Session_Id =?");
        $stmt->bind_param("s",$id);
        if($stmt->execute()){
            return true;
        }else{
            return false;
        }
    }
    public function gc($maxlifetime)
    {
        $result = $this->link->query("DELETE FROM Session WHERE ((UNIX_TIMESTAMP(Session_Expires) + ".$maxlifetime.") < UNIX_TIMESTAMP(NOW()))");
        if($result){
            return true;
        }else{
            return false;
        }
    }
}
$handler = new SysSession();
session_set_save_handler($handler, true);
?>

The above code stores and read sessions from the database.
Structure of the session table.
What could be the possible reason for this weird behaviour. Do i have to implement unset function as well?.
How should i resolve this problem?
If you could suggest me someother already written code for storing in database.That would work as well but i dont need any frameworks such as codeigniter and Yii2.
If you need more information regarding this problem.I will update my question.
Thanks in advance!

A: The problem is not with the unset function but with your write function.The write function is responsible for any updates that are made to the specific session id.
The wierd behiviour is not with the unset but it is with the write funciton you have implemented.
See ,the !empty constraint checks if your data is empty or not.What i can guess is that your database for that specific id must be empty after the removal of the specific variable .So the write tries to update your row with an empty value but with that constraint it isn't able to do so.
Just remove the !empty tag and it will work like a charm.


text:
Q: Earth man sent by superior to distant empire, dueling, caste by height and strength, honorary military post An Earth man is picked (or sent by his boss/superior) on a one way trip to a distant empire (their emperor had some mad daydream visions, which everyone chose to ignore, for fear of being seen as admitting the emperor's sickness).
The dominant class's main trait was their height and enhanced capabilities (velocity, strength, intelligence).
The nobleman/tall aliens duel often (using some kind of rings??)
The Earthling is given a military honorary post (if I'm not mixing my stories). In time the Earthling climbs the nobleman value ladder and uncovers a threat to the emperor and is rewarded with his return back to Earth.
He returns with a female nobleman love interest (which I believe it was less tall than the other members of the ruling class being perceived because of that as inferior by them).

A: This sounds a great deal like Gordy Dickson's "Wolfling" which is also the answer to this question: Spy from Earth studies Galactic Empire nobility and prevents plot to depose Emperor.  I will copy the answer mostly from that.
See http://www.baen.com/wolfling.html
Baen's blurb says:

When the first expedition from Earth reaches Alpha Centurai III, it makes a starling discovery: all life, including humankind, is governed by the Throne World. The Earth is a mere outpost in a vast star empire.
Jim Keil was a superman on Earth, but on the Throne World he is nothing more than a "wolfling," a trained pet whose sole purpose is to entertain the High-Born. But Jim Keil will show the High-Born that the people of Earth aren't so easily tamed.

Earth is a Lost Colony.  When Earth rediscovers the Empire, Jim Keil is selected to try to penetrate the nobility and learn enough for Earth's survival. Keil is an anthropologist who is selected for that and also for his superb physical shape. He's trained a a bull fighter to put on a display of bull fighting -- Earth's unique physical art -- for the Empire's nobility. He's adopted (somewhat as a pet) by the Princess Afuan and gets to see the cutthroat, decadent politics of the high empire from the inside.  The Emperor himself turns out to be such a refined genetic superman that he's an unstable superman.
Jim turns out to be a throwback to the nobility who were also on Earth when it was lost and manages to out maneuver Empire politics and go back to Earth with the message that Earth need only be patient -- the Empire was doomed to fall soon.


text:
Q: How Do I Exclude a Particular Package Version with SBT Right now, in my build.sbt I have a libraryDependencies that has something like
"some.package" %% "package-name" % "[1.4.2, 1.5["

as one of its elements.
Now let's say version 1.4.6 introduces some bug that's fixed in 1.4.7. How can I rewrite my dependency string to include all versions from 1.4.2 up to (non-inclusive) 1.5 except for version 1.4.6?

A: Didn't try but Ivy's version matchers may help.
You can specify Ivy configuration with matcher:
 externalIvySettings()

 externalIvyFile(Def.setting(baseDirectory.value / "Ivy.xml"))

Settings.xml
<pattern-vm>
  <match revision="foo" pattern="..." matcher="..." />
</pattern-vm>

Ivy.xml
<dependency org="acme" name="tool" rev="foo()" />


text:
Q: ASP.NET CheckBoxList DataBinding Question Is it possible to DataBind an ASP.NET CheckBoxList such that a string value in the data becomes the label of the check box and a bool value checks/unchecks the box?
On my asp.net webform I have a CheckBoxList like this:
<asp:CheckBoxList runat="server" ID="chkListRoles" DataTextField="UserName" DataValueField="InRole" />

In the code behind I have this code:
var usersInRole = new List<UserInRole>
{
  new UserInRole { UserName = "Frank", InRole = false},
  new UserInRole{UserName = "Linda", InRole = true},
  new UserInRole{UserName = "James", InRole = true},
};

chkListRoles.DataSource = usersInRole;
chkListRoles.DataBind();

I was kinda hoping that the check boxes would be checked when InRole = true. I've also tried InRole = "Checked". The results were the same. I can't seem to find a way to DataBind and automagically have the check boxes checked/unchecked.
Currently I solve the problem by setting selected = true for the appropriate items in the DataBound event. Seems like there's a cleaner solution just beyond my grasp.
Thank You

A: It's not possible using markup. What you can do is to bind the checkboxlist like you wanted it to work - with the bool in the DataValueField, and then simply add this as OnDataBound event.
protected void myCheckBoxList_DataBound(object sender, EventArgs e)
    {
        foreach (ListItem item in myCheckBoxList.Items)
        {
            item.Selected = bool.Parse(item.Value);
        }
    }

The difference between this solution and the one proposed by Jose Basilio is that this one works with all kind of databinding methods. For example binding with a SelectMethod using the new ModelBinding feature in v4.5.

A: EDIT: There's no way to do this through the Markup. The DataValueField does not determine whether the checkbox item is check or not. It retrieves or stores the value to be used in postbacks. The DataValueField is common across CheckBoxLists, RadioButtonLists, ListControl, etc.
This is about the only way to pre-select the checkboxes as you already found out.
chkListRoles.DataSource = usersInRole;
chkListRoles.DataBind();

foreach(ListItem item in chkListRoles.Items)
 item.Selected = usersInRole.Find(u => u.UserName == item.Text).InRole;

A: I made a custom control for this, after getting tired of the OnItemDataBound-binding.
It will let you bind the Selected attribute. You can easily make the same control for RadioButtonList by changing what the custom control derives from.
To use this, simply add the DataCheckedField attribute when you create the control in your markup. Remember to reference the custom controls in your web.config file.
Markup
<myControls:SimpleCheckBoxList runat="server" ID="chkListRoles"
                               DataCheckedField="InRole"
                               DataTextField="UserName"
                               DataValueField="UserId" />

Code for the control
public class SimpleCheckBoxList : System.Web.UI.WebControls.CheckBoxList
{
    public string DataCheckedField
    {
        get
        {
            string s = (string)ViewState["DataCheckedField"];
            return (s == null) ? String.Empty : s;
        }
        set
        {
            ViewState["DataCheckedField"] = value;
            if (Initialized)
                OnDataPropertyChanged();
        }
    }

    protected override void PerformDataBinding(IEnumerable dataSource)
    {
        if (dataSource != null)
        {
            if (!this.AppendDataBoundItems)
                this.Items.Clear();

            if (dataSource is ICollection)
                this.Items.Capacity = (dataSource as ICollection).Count + this.Items.Count;

            foreach (object dataItem in dataSource)
            {
                ListItem item = new ListItem()
                {
                    Text = DataBinder.GetPropertyValue(dataItem, DataTextField).ToString(),
                    Value = DataBinder.GetPropertyValue(dataItem, DataValueField).ToString(),
                    Selected = (DataCheckedField.Length > 0) ? (bool)DataBinder.GetPropertyValue(dataItem, DataCheckedField) : false
                };
                this.Items.Add(item);
            }
        }
    }
}

A: Using a DataList could be another option
<asp:DataList ID="dataListRoles" runat="server">
    <ItemTemplate>
        <asp:CheckBox runat="server" Text='<%# Eval("UserName ") %>' Checked='<%# Eval("IsInRole") %>' />
    </ItemTemplate>
</asp:DataList>

A: I would think you would have to tell the control what property to bind it to...in this case "InRole".
I played around with it and seems like there is noway to bind to the selection of the checkbox, you have to do it yourself.  I was able to bind to the text and values of the checklist which only seem to deal with the label of each checkbox in the list.


text:
Q: Using d3.js to create a heatmap, having issues with color Hi i have a heatmap here that im trying to give color to. Right now its all over red but I want to use the d3.interpolateRdYlBu, i want my values that are lower to be the blue and the higher be the red so i would like it to gel nicely. I know that its reading correctly since i get the red and no other errors in my console but Im not doing something right that it doesnt take my value into account and do accordingly. Any help would be appreciated!
<!DOCTYPE html>
<meta charset="utf-8">

A: In your colour scale, you've set the domain as [0,100]. Your values however are between 0 and 1.5, and you want them reversed
so, this should fix it:
  // Build color scale
  var myColor = d3.scaleSequential()
     .interpolator( d3.interpolateRdYlBu)
     .domain([1.3,0])

To be even more thorough, you can use the d3.max and d3.min functions to work out the max in min for you:
  var myColor = d3.scaleSequential()
    .interpolator( d3.interpolateRdYlBu)
    .domain([d3.max(data, d=>d.value),d3.min(data, d=>d.value)])

Heres a jsFiddle with this working: https://jsfiddle.net/x8zyud5t/


text:
Q: How do you handle 'require( ..., bail)' statements with ARC? I'm looking through some of the sample code for the Square Cam in Apple's sample code. I want to replicate some of it's functionality in a modern project using ARC. However, there are a ton of require statements such as:
BOOL success = (destination != NULL);
require(success, bail);

Which generates the compiler error:

Goto into protected scope.

My question is -- what is the appropriate way to handle such statements in a project using ARC?

A: Apparently bail is in a scope with one or more __block variables; this is not allowed. See http://clang.llvm.org/compatibility.html#blocks-in-protected-scope for more. The solution proposed there is to limit the scope of the __block variable(s), by putting them in brace-delimited blocks. This may not work always; YMMV.

A: I had the same problem (with the same sample code). The code looked like this:
BOOL success = (destination != NULL);
require(success, bail);

//Initialise some variables

bail:
//Deal with errors

I added braces around the block with the declarations to make their scope clear:
BOOL success = (destination != NULL);
require(success, bail);
{
    // *** Initialise some variables ***
}
bail:
{
    //Deal with errors
}

And it solved the problem for me. Through looking at this I also learned you can sometimes expand build errors to get more detail.

A: I am adding some description for @Lewis42 answer.
If you don't put variable in its own scope, you bypass the initialisation of all variable after goto, and when ARC tries to clean it up, it will end up trying to release some random bit of memory.
If you don't want to put variables in their own scope make sure that any variable should not be declared below goto keyword.
Jumps to within __block variable scope

__block require special runtime initialization. A jump into the scope of a __block variable bypasses this initialization, leaving the
  variable's metadata in an invalid state.


text:
Q: Is it possible to forge HttpRequest attributes for a Django server I am writing a web app using Django. I am trying to allow a user to see its profile and only his own.
if(not request.user.id == request.GET.get('user_id', '')):
    raise PermissionDenied

My question is: is it safe to check this way or is it possible for a smart kid to somehow alter the value in request.user.id to match the user_id of anyone?
The user must be logged in before accessing this page using this:
user = LDAPBackend().authenticate(username=username, password=password)
if(user is not None):
    login(request, user)

A: request.user is set using AuthenticationMiddleware for each request:

Adds the user attribute, representing the currently-logged-in user, to every incoming HttpRequest object.

If a user is not logged in then request.user is set to Anonymous User. Have a look at Authentication in Web requests.
So, I am not sure how would a smart kid alter the id of the logged-in user.
Mostly, there is a one-to-one relation between the user and its profile. If that's the case you can modify the queryset to get the profile for request.user directly.

A: Yes it should be safe.
request.user get's only populated when authentication with session cookies. Unless and until someone steals the cookie or token it should be no issue.
One thing i don't understand is why do you need user_id parameter here to be explicitly passed.
if you are putting logged in compulsory to view the page. there are two way i can see this.

*

*/profile
Directly get user profile corresponding to the request.user

*/<username>
Query the profile corresponding to the username and compare it with request.user.id

A: request.user is already an object about the current user who send the request to get the page. You can use login_required or  to only allow user login to access (2 solutions : decorator or Mixin).
And then you can use your condition to load the page in the function. Example:
=> url.py:
url(r'^profile/$', login_required(app.views.profile), name='profile'),

=> views.py :
def profile(request):
try:
    myProfile = User.objects.get(username=request.user.username)
except ObjectDoesNotExist:
    return render(request, "error.html", {'message' : 'No Profile Found'})
return render(request, "app/profile.html",
              {'myProfile': myProfile})

Like this you can only display YOUR profile (user who send the request) AND you need to be logged.
EDIT: if you don't want "try and catch" you can use get_object_or_404(User, username=request.user.username)


text:
Q: how to bind click event to a clone button in jQuery I am working on an application which provides the facility of downloading couple of file from a jqGrid.
the jqGrid has several columns and one column which will display the download button for each row.
the user has to click on it and then the download will begin.
 for this download button i have used an
html input tag in jsp as below,
<input type="button" id="download" height="30px" width="100px" value="Download">

and in my jqgrid code i am trying to clone this button as below.
{
  name:'click to download',
  index:'click to download',
  width:50,
  formatter: function(cellvalue, options, rowObject){
    var button = $("#download").clone(true);
    button.addClass(".button");
    $("body").on("click",".button",function(){
      alert("hello");
    });
    return button[0].outerHTML;
  },
  sortable: false
}

I want to write a  function separately for this cloned button on its click event and pass the parameter to that function such as rowId and cellvalue.
anyone please help me on this, I have tried creating function on this event button but they are not getting called. after which i tried to create a buttons manually instead of cloning but the click function still doesn't get called.
any help is greatly appreciated.

A: you should use jquery "on" function because "on" keeps watching the click event in the dom, the simple click do not recognize the element that you just cloned
syntaxe:
$( "body" ).on( "click", ".your_element", function() {
   // your code here
});

NOTE: use classes instead of IDs.

A: In your code, try changing this:
button.addClass(".button");
to this (remove the prefixing period):
button.addClass("button");


text:
Q: How to sum up different property weights? I am trying to get two properties sum (with weight) and combine them finally into a combined weight.
So, first the separate queries, so you can see the correct sum weights

*

*Language = French, Proficiency over 6 (scale 1-10):
MATCH (User)-[Speaks]->(Language)
WHERE Language.language = 'French' AND Speaks.proficiency >=6
RETURN User.name, SUM(
CASE
    WHEN Language.language='French'  THEN Speaks.proficiency*3
    END )*0.1 AS TOTAL_Language
ORDER BY TOTAL_Language DESC

User.name    TOTAL_Language
   David        3
   Marion       1.8

*Skill = Finance,Banking,IT,Marketing   Weight =1 (of 1):
MATCH (User)-[IsSkilledIn]->(Skill)
WHERE  Skill.skill IN ['Finance','Banking','IT','Marketing']
RETURN User.name, SUM(
CASE
    WHEN Skill.skill='Finance' THEN IsSkilledIn.weight*10
    WHEN Skill.skill='Banking' THEN IsSkilledIn.weight*5
    WHEN Skill.skill='IT' THEN IsSkilledIn.weight*8
WHEN Skill.skill='Marketing' THEN IsSkilledIn.weight*1
END )*0.1 AS TOTAL_Skill
ORDER BY TOTAL_Skill DESC

User.name   TOTAL_Skill
Eric            1.5
Marion          0.9
David           0.8
Hans            0.8

So now, I tried to combine these Queries into this:

*French >=6 AND Skills Finance,Banking,IT,Marketing:
MATCH (User)-[Speaks]->(Language) , (User)-[IsSkilledIn]->(Skill)
WHERE Language.language = 'French' AND Speaks.proficiency >=6 AND Skill.skill IN ['Finance','Banking','IT','Marketing']
RETURN User.name, SUM(
CASE
    WHEN Language.language='French'  THEN Speaks.proficiency*3
    END )*0.1 AS TOTAL_Language,
SUM(
CASE
    WHEN Skill.skill='Finance' THEN IsSkilledIn.weight*10
    WHEN Skill.skill='Banking' THEN IsSkilledIn.weight*5
    WHEN Skill.skill='IT' THEN IsSkilledIn.weight*8
    WHEN Skill.skill='Marketing' THEN IsSkilledIn.weight*1
END )*0.1 AS TOTAL_Skill
ORDER BY TOTAL_Skill DESC

Now I got these results:
 User.name  TOTAL_Language  TOTAL_Skill
 Marion          3.6            0.9
 David       3                  0.8

The TOTAL_Language of Marion is twice as high as the first answer.
So I checked what could be wrong and it must be in the WHERE-Clause, But I don't know what's wrong.
How can I sum up the two results in the end?

A: Ah, I see the problem. You're ending up with two results instead of one, because your match matches two skill records. What you'll need to do is WITH the two queries together, so the sums are calculated separately.
MATCH (User)-[Speaks]->(Language)
WHERE Language.language = 'French' AND Speaks.proficiency >=6
WITH User, SUM(
CASE
    WHEN Language.language='French'  THEN Speaks.proficiency*3
    END )*0.1 AS TOTAL_Language
MATCH (User)-[IsSkilledIn]->(Skill)
WHERE  Skill.skill IN ['Finance','Banking','IT','Marketing']
RETURN User.name, TOTAL_Language, SUM(
CASE
    WHEN Skill.skill='Finance' THEN IsSkilledIn.weight*10
    WHEN Skill.skill='Banking' THEN IsSkilledIn.weight*5
    WHEN Skill.skill='IT' THEN IsSkilledIn.weight*8
    WHEN Skill.skill='Marketing' THEN IsSkilledIn.weight*1
END )*0.1 AS TOTAL_Skill
ORDER BY TOTAL_Skill DESC

A: Another option is to do it still with one query, but collect the skills for a person, and sum the collection of skill weight as opposed to sum the rows,
MATCH (User)-[Speaks]->(Language), (User)-[IsSkilledIn]->(Skill)
WHERE Language.language = 'French'
 AND Speaks.proficiency >=6
 AND Skill.skill IN ['Finance','Banking','IT','Marketing']
WITH User.name as userName,
     (CASE WHEN Language.language='French'
           THEN Speaks.proficiency*3 END) as languageProficiency,
      collect(CASE
              WHEN Skill.skill='Finance' THEN IsSkilledIn.weight*10
              WHEN Skill.skill='Banking' THEN IsSkilledIn.weight*5
              WHEN Skill.skill='IT' THEN IsSkilledIn.weight*8
              WHEN Skill.skill='Marketing' THEN IsSkilledIn.weight*1
              END) as skillWeightCollection
RETURN userName,
       sum(languageProficiency)*0.1 as TOTAL_Language,
       reduce(totalSkill = 0, skillWeight in skillWeightCollection |
              totalSkill + skillWeight) * 0.1 as TOTAL_SKILL


text:
Q: How can I programmatically retrieve the alter view script for a view in SQL Server 2005 We allow our uses to alter certain views for reports and what not based on some application field meta data that we keep track of in our application.  These fields can be created at run time.  I have a standard process in place to alter the views when a field is added or removed.  I now need to do this programmatically however, which means I need to be able to pull the current Alter view script, make my modifications, and then execute it against the database.  The last two steps are easy enough, but the first part is giving me some trouble.
Design decisions aside (as they are out of my hands in this particular instance).  I would like to know how to retrieve the Alter view script that Sql server management studio uses for the View->Edit command.
I require the exact same output as that command because I have comment hooks in my scripts that allow my edits to occur.
Related questions, but not quite what I am looking for.
How do I programmatically retrieve SQL Server stored procedure source that is identical to the source returned by the SQL Server Management Studio gui?
In MSSQL, how do I generate a CREATE TABLE statement for a given table?

A: SSMS uses SMO under the covers. The Scripter can retrieve the definition of any SQL object.
If you want a T-SQL based approach, then use sys.sql_modules, it contains the T-SQL definition of every non-encrypted object in the database, including views.

A: SELECT [definition]
FROM sys.sql_modules
WHERE [object_id] = OBJECT_ID('dbo.' + @ViewName);

-- you don't need the type check if you are passing in the name of a view
-- you can do the schema check using OBJECT_ID instead of an extra join

-- if you want to reference system_sql_modules it is unlikely they
-- will have dbo schema, if you want to support this use a separate query IMHO

A: You can get the View create script from the Information_Schema.Views table:
SELECT VIEW_DEFINITION FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME='<view name>'

From there you can alter it to build your ALTER however you need.

A: I think I have the answer to this finally.  Poking around the SQL profiler I came across a query that I modified to the following.
DECLARE @ViewName VARCHAR(255)

SET @ViewName = N'vwMyView'

SELECT
    ISNULL(smv.definition, ssmv.definition) AS [Definition]
FROM
    sys.all_views AS v
    LEFT OUTER JOIN sys.sql_modules AS smv ON smv.object_id = v.object_id
    LEFT OUTER JOIN sys.system_sql_modules AS ssmv ON ssmv.object_id = v.object_id
WHERE
    (v.type = 'V') and (v.name = @ViewName and SCHEMA_NAME(v.schema_id) = N'dbo')

This returns my view script as a 'Create View' ddl statement complete with comments.  It is on one line however, so I have to insert newlines after any comments.  We will have to see how feasible this turns out to be.


text:
Q: Error with Magento\Eav\Model\Entity\Attribute how to fix? I have this error,
1 exception(s):
Exception #0 (Exception): Item (Magento\Eav\Model\Entity\Attribute) with the same ID "87" already exists.

it seems to me that there must be a duplicate row ?
But what Table as I cant find one.
Thanks.

A: Some migration or system that populates the database which caused the duplication of IDs.
Magento core predicts a data created by its self, so this kind of error could be solved without stopping the system but it was not implemented yet (e.g. Github issue in the reference session).
Solution

*

*Recreate the attribute or remove the attribute

*Change the attribute ID through the database

*Create a core patch to skip attribute with error to not show or show it unfilled in the product page to edit as below (creating a module):

// file: vendor/magento/framework/Data/Collection.php

    public function addItem(\Magento\Framework\DataObject $item)
    {
        $itemId = $this->_getItemId($item);

        if ($itemId !== null) {
//            if (isset($this->_items[$itemId])) {
//                throw new \Exception(
//                    'Item (' . get_class($item) . ') with the same ID "' . $item->getId() . '" already exists.'
//                );
//            }
            $this->_items[$itemId] = $item;
        } else {
            $this->_addItem($item);
        }
        return $this;
    }


text:
Q: foreign key assignment for child object I have a very simple question which I am not able to get my head around. I have following models
class Parent(models.Model):
     id = models.AutoField(primary_key=True)
     title = models.CharField(max_length=64)

class Child(models.Model):
      boardid = models.ForeignKey(Parent,on_delete=models.CASCADE,related_name="child")
      id = models.AutoField(primary_key=True)
      title = models.CharField(max_length=128)

Serializers
class ParentSerializer (serializers.ModelSerializer):
    class Meta:
        model = Parent
        fields = ('__all__')

class ChildSerializer (serializers.ModelSerializer):

    class Meta:
       model = Child
       fields = ('id','title')

and simple createAPIview for the children
class ChildCreateView(CreateAPIView):
      queryset= Child.objects.all()
      serializer_class = ChildSerializer

When I call this url
                    /api/parent/1/child/create
  I want to pre populate the foreign key board id with the id 1 and create child object with rest of the information which I will be providing in the body . How is this possible to achieve

A: Initially, add boardid field to the ChildSerializer,
class ParentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Parent
        fields = '__all__' # no need of "()"

class ChildSerializer(serializers.ModelSerializer):
    class Meta:
        model = Child
        fields = ('id', 'title', 'boardid')
Then, use the below json payload to create the instance.
{
    "title":"child title",
    "boardid":123,
    ... other data
}


text:
Q: AddDbContextPool together with AddInterceptors problem I have used AddDbContext() method to register my EF DbContext classes using DI. It works well, and I can also add an interceptor like this:
        services.AddDbContext<TContextService, TContextImplementation>((provider, opt) =>
        {
            opt.EnableSensitiveDataLogging(enableSensitiveLogging);
            opt.AddInterceptors(provider.GetRequiredService<AzureAdAuthenticationDbConnectionInterceptor>());
        });

Note the first parameter in the optionsAction being a provider. This allows me to add an interceptor like above.
However, now I'd like to use the AddDbContextPool instead. The optionsAction no longer gives me the provider.
        services.AddDbContextPool<TContextService, TContextImplementation>(opt =>
        {
            opt.EnableSensitiveDataLogging(enableSensitiveLogging);
            opt.AddInterceptors(???.GetRequiredService<AzureAdAuthenticationDbConnectionInterceptor>());
        });

..and at this stage I cannot 'new' up an instance of my interceptor. And I don't want to call services.BuildServiceProvider() here either.
So, long story short: how can I achieve the same thing with AddDbContextPool as I can with AddDbContext()?
I guess I can inject an IServiceProvider in some class and do a late resolve, but wanted to check if anyone else has faced this challenge?

A: The AddDbContextPool extension method has an overload that passes both an IServiceProvider and a DbContextOptionsBuilder argument via the optionsAction.
public static IServiceCollection AddDbContextPool<TContextService,TContextImplementation> (
    this IServiceCollection serviceCollection,
    Action<IServiceProvider, DbContextOptionsBuilder> optionsAction,
    int poolSize = 1024
)
where TContextService : class
where TContextImplementation : DbContext, TContextService

Your code would look like below
services.AddDbContextPool<TContextService, TContextImplementation>((serviceProvider, opt) =>
{
    opt.EnableSensitiveDataLogging(enableSensitiveLogging);
    opt.AddInterceptors(serviceProvider.GetRequiredService<AzureAdAuthenticationDbConnectionInterceptor>());
});


text:
Q: Netzke with file uploads, preferably carrierwave I have a model with a single field with carrierwave for file upload.  I searched the google group but don't find a straightforward way to add file uploads to netzke component.  I will be happy with doing it in a panel view with a regular browser file upload, i don't need anything fancy.
I just saw one of the demos has a file upload, the Paging form with custom layout.  I think I still need guidance how to put it into the Basepack Grid

A: File upload field should first be added into Basepack::Form (which then can be tested independently):
class AttachmentForm < Netzke::Basepack::Form
  def configure(c)
    super
    c.model = "Attachment"
    c.items = [{xtype: :fileuploadfield, name: 'attachment'}]
  end
end

Then your grid should be configured to use this form instead of the built-in one:
class AttachmentGrid < Netzke::Basepack::Grid
  def configure(c)
    super
    c.model = 'Attachment'
    c.force_fit = true
    c.columns = [:link]
    c.bbar = [:add_in_form, :del]
  end

  def preconfigure_record_window(c)
    super
    c.form_config.klass = AttachmentForm
    c.width = 600
    c.height = 150
  end
end

For reference, here's also the Attachment model:
class Attachment < ActiveRecord::Base
  mount_uploader :attachment

  # this is a virtual column referred to from `AttachmentGrid`;
  # can be moved over to grid itself using `getter` in case
  # you object putting HTML into the model
  def link
    "#{attachment.file.try(:identifier)}"
  end
end


text:
Q: pandas HDFStore.append data_columns after append operation I am new to data analysis and python and have virtually no experience with numpy, pytable, pandas etc.
I am reading a csv file to a dataframe chunk by chunk and appending it to an HDFStore as the entire data cannot fit in memory. In my append operations, I am passing a list of data columns via the data_columns parameter so that I can perform out-of-core filtering via HDFStore.select passing conditions to the where parameter.
Is it possible to specify the data columns after the table has been appended?
The reason is that the time to perform chunk by chunk appends to HDFStore tables are increase exponentially on each write. I am guessing that each time an append is made to HDFStore with new data, the index in data columns is recalculated. It would be much more efficient if the data is placed entirely in the store and data columns are specified after creation so that the index is calculated just once.
Appreciate your thoughts and assistance.
UPDATE 1
The following is roughly the code that I am running. Please not I had to sanitize the code to avoid unnecessary disclosure and not provided the entire column list in the following 3 lines of code as there are > 100 columns:
I have determined the dtypes to be read from csv and declared them like this:
csv_dt = {'COL1': dtype('O'), 'TAX': dtype('float64'), 'COL2': dtype('O'), ... }

The following is dtype declaration for the table that is going to be written. Notice I have added the calculated field 'REVENUE' which is not in the original csv.
t_dt = [('COL1', 'S20'), ('COL2', 'S3'), ('COL3', 'f8'), ('TAX', 'f8'), ('REVENUE','f8') ... ]

Determined the max string length of each column to be passed to min_itemsize. This is only for columns with dtype('O')
str_len = {'COL1': 3, 'COL2': 3, ...}

Here's the code for chunking:
f = HDFStore('FLN2.h5')

for num, chunk in enumerate(read_csv('FLN.csv',dtype=csv_dt, iterator=True, chunksize=250000, parse_dates=True)):
    print str(now()),str(num), "Started new chunk"

    chunk['MTH'] = to_datetime(chunk.MTH)
    chunk.TAX = chunk.TAX.fillna(0)
    chunk['REVENUE'] = chunk.NET - chunk.TAX
    print str(now()),str(num), "Completed Revenue Calculation"
    if num == 0:
        f.append('df', chunk, dtype=t_dt, min_itemsize=str_len, dtype=t_dt, data_columns = ['DC1', 'DC2'], expectedrows=42000000)
    else:
        f.append('df', chunk)
    print str(now()),str(num), "Completed writing chunk"
    f.flush()
f.flush()
f.close()

This code was running fine yesterday when the chunksize for reading the csv was set to 50000. However, today when I am trying to run the code I get the following error:
Exception: tables cannot write this data -> rows parameter cannot be converted into a recarray object compliant with table '/df/table (Table(0,))
For the life of me, I can't figure out what happend.
Info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 250000 entries, 0 to 249999
Columns: 122 entries, COL1 to REVENUE
dtypes: datetime64[ns](1), float64(40), int64(13), object(68)

Note the above is only from one chunk written to disk.


text:
Q: Kendo MVC date filter customization I have a MVC kendo grid date head filter
part of my date column filter--
.Filterable(filterable => filterable.Extra(true).UI("customDateFilter")
.Operators(operators => operators
.ForDate(date => date.Clear()
.IsGreaterThanOrEqualTo("Is greater than or equal to")
.IsLessThanOrEqualTo("Is less than or equal to")
.IsEqualTo("Is equal to");

and my js custom function--
function customDateFilter(element) {
    element.kendoDatePicker({
        format: "MM/yyyy",
        dateInput: true,
        start: "year",
        parseFormats: ["MM/yyyy"],
        depth: "year",
        min: new Date(2000, 01, 01)
    });
}

I'm currently using MM/yyyy format in my grid, so the search date option should also be MM/yyyy. However, because of this, if I search "greater than OR equal to 09/2020",
it omits 09/2020 and returns 10/2020 and so on. I noticed that if I change the search date format to MM/dd/yyyy and select 09/01/2020 then "greater than OR equal to 09/2020" includes 09/2020.
Is there a way IsGreaterThanOrEqualTo and IsLessThanOrEqualTo to work with using the format MM/yyyy?


text:
Q: Aggregating over two columns (sum and min) Given is the following dataframe:
name    item        price   timestamp
______________________________________
Elliot   a            10        12312
Sara     b            20        45654
Elliot   a            30        15000
Tom      a            5         43423

Elliot, for example, consumed item 'a' twice, and now I want to aggregate over all such cases such that in the end I have only a single occurrence of 'name-item' pair, but such that the 'price' is summed and the 'timestamp' corresponds to the minimum found:
name    item        price   timestamp
______________________________________
Elliot   a            40        12312
Sara     b            20        45654
Tom      a            5         43423

How can this be done efficiently?

A: You can use groupby.agg which takes a dictionary with your column names as keys and operations as values.
calcs = {'item':'first','price':'sum','timestamp':'min'}
df.groupby('name').agg(calcs).reset_index()

which prints:
     name item  price  timestamp
0  Elliot    a     40      12312
1    Sara    b     20      45654
2     Tom    a      5      43423

You can also use Named.Agg where you control the output names with different aggregations per column, as below:
>>> df.groupby('name').agg(
    total_price_per_customer=pd.NamedAgg(column='price', aggfunc='sum'),
    minimum_timestamp_per_customer=pd.NamedAgg(column='timestamp', aggfunc='min'))

        total_price_per_customer  minimum_timestamp_per_customer
name
Elliot                        40                           12312
Sara                          20                           45654
Tom                            5                           43423


text:
Q: discord bot adding roles I'm trying to make a discord bot in python and I want to figure out how to give a role to myself, without notifying anything besides a conformation in the console.

import discord
import os

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content == '':
      # i want to give myself a role right here
      print('adding admin role to', message.author)
    print(message.author,message.content)

try:
    client.run(os.getenv("TOKEN"))
except discord.HTTPException as e:
    if e.status == 429:
        print("The Discord servers denied the connection for making too many requests")
        print("Get help from https://stackoverflow.com/questions/66724687/in-discord-py-how-to-solve-the-error-for-toomanyrequests")
    else:
        raise e

A: Get the role, using either utils.get on its name:
role = discord.utils.get(message.guild.roles, name=some_name)

or its ID:
role = message.guild.get_role(12345)

Then you can add the role to the member.
await message.author.add_roles(role)

(Also, please don't randomly give people admin if they send a specific message. That's going to end up being abused in some way.)


text:
Q: from QCamera or QVideoWidget get video bytes How can I get an ARRAY OF BYTES (frame) from QCamera or QVideoWidget?
I successfull capture video from camera and audio from microphone and now I want send them to socket TCP channel for creating a simple video/audio call software.
What I've tried:

*

*I have reimplemented QAbstractVideoSurface methods, but "present" method isn't invocked. What is wrong?

*How Can I use this class with QCameraViewfinder?
Here is my code:

#include <QtMultimedia/QAbstractVideoSurface>
class QMyAbstractVideoSurface :
    public QAbstractVideoSurface
{
    Q_OBJECT
public:
    explicit QMyAbstractVideoSurface(QObject* parent = 0);
    ~QMyAbstractVideoSurface();

    QList<QVideoFrame::PixelFormat> supportedPixelFormats(QAbstractVideoBuffer::HandleType handleType) const;

    bool present(const QVideoFrame& frame);

    bool start(const QVideoSurfaceFormat& format);

    void stop();
};

#include "QMyAbstractVideoSurface.h"
#include <QDebug>

QMyAbstractVideoSurface::QMyAbstractVideoSurface(QObject* parent) {
}

bool QMyAbstractVideoSurface::start(const QVideoSurfaceFormat& format) {
    return QAbstractVideoSurface::start(format);

}

void QMyAbstractVideoSurface::stop() {
    QAbstractVideoSurface::stop();
}

bool QMyAbstractVideoSurface::present(const QVideoFrame& frame) {

    QVideoFrame cloneFrame(frame);
    QByteArray a((char*)cloneFrame.bits());

    qDebug() << "present";
    qDebug() << a.toBase64();

    return true;
}

QList<QVideoFrame::PixelFormat> QMyAbstractVideoSurface::
supportedPixelFormats(QAbstractVideoBuffer::HandleType handleType) const
{
    Q_UNUSED(handleType);
    return QList<QVideoFrame::PixelFormat>()
        << QVideoFrame::Format_ARGB32
        << QVideoFrame::Format_ARGB32_Premultiplied
        << QVideoFrame::Format_RGB32
        << QVideoFrame::Format_RGB24
        << QVideoFrame::Format_RGB565
        << QVideoFrame::Format_RGB555
        << QVideoFrame::Format_ARGB8565_Premultiplied
        << QVideoFrame::Format_BGRA32
        << QVideoFrame::Format_BGRA32_Premultiplied
        << QVideoFrame::Format_BGR32
        << QVideoFrame::Format_BGR24
        << QVideoFrame::Format_BGR565
        << QVideoFrame::Format_BGR555
        << QVideoFrame::Format_BGRA5658_Premultiplied
        << QVideoFrame::Format_AYUV444
        << QVideoFrame::Format_AYUV444_Premultiplied
        << QVideoFrame::Format_YUV444
        << QVideoFrame::Format_YUV420P
        << QVideoFrame::Format_YV12
        << QVideoFrame::Format_UYVY
        << QVideoFrame::Format_YUYV
        << QVideoFrame::Format_NV12
        << QVideoFrame::Format_NV21
        << QVideoFrame::Format_IMC1
        << QVideoFrame::Format_IMC2
        << QVideoFrame::Format_IMC3
        << QVideoFrame::Format_IMC4
        << QVideoFrame::Format_Y8
        << QVideoFrame::Format_Y16
        << QVideoFrame::Format_Jpeg
        << QVideoFrame::Format_CameraRaw
        << QVideoFrame::Format_AdobeDng;
}

QMyAbstractVideoSurface::~QMyAbstractVideoSurface()
{}

A: You are probably looking for a QVideoSink: https://doc-snapshots.qt.io/qt6-dev/qvideosink.html.
The QVideoSink class can be used to retrieve video data on a frame by frame basis from Qt Multimedia.
It is supposed to be set on the QMediaCaptureSession: https://doc-snapshots.qt.io/qt6-dev/qmediacapturesession.html#setVideoSink.
For Qt5 you have QAbstractVideoSurface https://doc.qt.io/qt-5/qabstractvideosurface.html or QVideoProbe https://doc.qt.io/qt-5/qvideoprobe.html.


text:
Q: about ngspice models and libraries I'm learning ngspice , read almost it's whole documentation but still confused about libraries and models , here are my questions :

*

*where are the default models and libraries that comes built-in with ngspice? (to view and use them)

*what exactly are libraries for ? is adding a model the same as adding library ? if I added a new model should I make a library for it?

*if I want to edit a model would it add a modified copy of it or will it replace it?

*can I add a folder to ngspice in which all my own libraries , models and sub-circuits are located for the simulator to automatically use in my future projects ? or should I always include them to my new design ?

thanks a lot

A: I found good answers to my question nad I want to share it here to anyone that may ask the same question , follow those links for it's irrespectable of me to copy paste others ansewrs/articles:
an article I found on the web:
https://resources.pcb.cadence.com/blog/2019-being-prepared-for-circuit-simulation-with-spice-model-libraries
a discussion on ngspice page on sourceforge:
https://sourceforge.net/p/ngspice/discussion/120973/thread/3743fd00cd/#5c21/29b5
best wishes.


text:
Q: Menu Accordion horizontal Bootstrap 3.3.6 I need help. I'm doing a demo in which I am using an accordion. The problem with this is that I need accordion on one line. In the following example I step looks good on desktop mode "that's how I have to do it" but when in mobile mode, the 3 lines are placed below each other and that's what I do not. I put a float:left in each <LI> but its content disturbs me.
Code:
http://bootsnipp.com/user/snippets/l06gQ
As is to be seen:

The content in mobile mode should be centered on the left when you go opening tabs.
Any solution?

A: If I understand correctly what you want then bootstrap.css is overriding it on lower screen sizes.
Try adding the following.
.nav>li{display:inline-block}

Or you may want to set it for mobiles only with.
@media (max-width: 768px) {
    .nav>li{display:inline-block}
}

Or if you wanted to apply it just to that menu and not others
#menuEstatic .nav>li {display:inline-block}

You can also use float:left as an alternative to display:inline-block if you prefer.


text:
Q: logstash configuration to execute a command to elastic search i am running an ELK stack in 3 docker containers through host machine ubuntu 16.04
the problem is after configuring the logstash.conf file to execute a command like "ifconfig" or "netstat -ano"i get an error. my logstash.conf file is:

input {
  exec {

    command => "netsat -ano"
    codec => "json"
    interval => 5
  }
}
output{
  elasticsearch { hosts => ["elasticsearch:9200"]}
}
 i get this error after entering this command ( docker run -h logstash --name logstash --link elasticsearch:elasticsearch -it --rm -v "$PWD":/config-dir logstash -f /config-dir/logstash1.conf)

14:29:30.703 [[main]<exec] ERROR logstash.inputs.exec - Error while running command {:command=>"netsat -ano", :e=>#<IOError: Cannot run program "netsat" (in directory "/"): error=2, No such file or directory>, :backtrace=>["org/jruby/RubyIO.java:4380:in `popen'", "/usr/share/logstash/vendor/bundle/jruby/1.9/gems/logstash-input-exec-3.1.2/lib/logstash/inputs/exec.rb:76:in `execute'", "/usr/share/logstash/vendor/bundle/jruby/1.9/gems/logstash-input-exec-3.1.2/lib/logstash/inputs/exec.rb:75:in `execute'", "/usr/share/logstash/vendor/bundle/jruby/1.9/gems/logstash-input-exec-3.1.2/lib/logstash/inputs/exec.rb:40:in `inner_run'", "/usr/share/logstash/vendor/bundle/jruby/1.9/gems/logstash-input-exec-3.1.2/lib/logstash/inputs/exec.rb:34:in `run'", "/usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:443:in `inputworker'", "/usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:436:in `start_input'"]}

can anyone help please thanks in advance !

A: You will need to provide a full path for those commands, as the one Logstash runs with doesn't contain those directories.
input {
  exec {
    command => "/bin/netsat -ano"
    codec => "json"
    interval => 5
  }

}


text:
Q: Unable to run jmeter script with HTTP Cookie Manager with maven Recently I'm working with test automation. The goal is to get quicker feedback so we decided to use maven-jmeter-plugin, jmeter scripts and Hudson.
I have wrote some example jmeter scripts templates and they are working fine (just a quick smoke test for accessing pages).
The problem is that script I have to complete requires 'HTTP Cookie Menager' to run correctly.
Here is dummy script I'm using at the moment trying identify what is wrong.
Test Plan
 |-> Thread Group
      |-> HTTP Cookie Menager
      |-> Loop Controler
          |-> HTTP request

I use the same configuration as in other working examples I have prepared (jmeter.properties, update.properties, system.properties - in the last file I keep values used by script like number of users, loop count, host, etc).
When I run it with mvn clean verify it returns following output:
mvn -e clean verify
+ Error stacktraces are turned on.
[INFO] Scanning for projects...
[WARNING]
        Profile with id: 'development,hudson' has not been activated.

[INFO] ------------------------------------------------------------------------
[INFO] Building com.cybercom.test::peformance-test-mvn
[INFO]    task-segment: [clean, verify]
[INFO] ------------------------------------------------------------------------
[INFO] [clean:clean {execution: default-clean}]
[INFO] Deleting directory C:\Hudson\data\jobs\peformance-test-mvn\workspace\trunk\target
[INFO] [site:attach-descriptor {execution: default-attach-descriptor}]
[INFO] [jmeter:jmeter {execution: jmeter-tests}]
[INFO] Executing test: C:\Hudson\data\jobs\peformance-test-mvn\workspace\trunk\src\test\jmeter\temp.jmx
Error in NonGUIDriver java.lang.NullPointerException
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] There were test errors
[INFO] ------------------------------------------------------------------------
[INFO] Trace
org.apache.maven.BuildFailureException: There were test errors
        at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:715)
        at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:55
6)
        at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:535)
        at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.jav
a:387)
        at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348)
        at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
        at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
        at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
        at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
        at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Caused by: org.apache.maven.plugin.MojoFailureException: There were test errors
        at org.apache.jmeter.JMeterMojo.checkForErrors(JMeterMojo.java:115)
        at org.apache.jmeter.JMeterMojo.execute(JMeterMojo.java:102)
        at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490)
        at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694)
        ... 17 more

The same script without HTTP Cookie Menager works perfectly well, but as I mentioned this is just dummy script to investigate what is wrong.
I assume that pom file might be useful as well here it is:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>test</groupId>
    <artifactId>peformance-test-mvn</artifactId>
    <name>${groupId}::${artifactId}</name>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.jmeter</groupId>
                <artifactId>maven-jmeter-plugin</artifactId>
                <version>1.0</version>
                <executions>
                    <execution>
                        <phase>verify</phase>
                        <id>jmeter-tests</id>
                        <goals>
                            <goal>jmeter</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <reportDir>target/jmeter-reports</reportDir>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <pluginRepositories>
        <pluginRepository>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
                <checksumPolicy>fail</checksumPolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
                <updatePolicy>never</updatePolicy>
                <checksumPolicy>warn</checksumPolicy>
            </snapshots>
            <id>nexus</id>
            <url>XXXX</url>
            <name>YYYY</name>
            <layout>default</layout>
        </pluginRepository>
    </pluginRepositories>
</project>

What am I missing??
Thanks in advance
Pawel

A: Problem solved.
commons-logging dependency was missing in maven-jmeter-plugin-1.0.pom
Adding following lines
<dependency>
   <groupId>commons-logging</groupId>
   <artifactId>commons-logging</artifactId>
   <version>1.1.1</version>
</dependency>

Solved problem.


text:
Q: Как создать контроллер в slim 4? В официальной документации slim 4 написано

Container Resolution You are not limited to defining a function for
  your routes. In Slim there are a few different ways to define your
  route action functions.
In addition to a function, you may use:
container_key:method Class:method Class implementing __invoke() method
  container_key This functionality is enabled by Slim's Callable
  Resolver Class. It translates a string entry into a function call.
  Example:
$app->get('/', '\HomeController:home');
Alternatively, you can take advantage of PHP's ::class operator which works well with IDE lookup systems and produces the same result:

$app->get('/', \HomeController::class . ':home');
In this code above we are defining a / route and telling Slim to execute the home() method on the HomeController class.

Slim first looks for an entry of HomeController in the container, if
  it's found it will use that instance otherwise it will call it's
  constructor with the container as the first argument. Once an instance
  of the class is created it will then call the specified method using
  whatever Strategy you have defined.
Registering a controller with the container Create a controller with
  the home action method. The constructor should accept the dependencies
  that are required. For example:
<?php

class HomeController
{
    protected $view;

    public function __construct(\Slim\Views\Twig $view) {
        $this->view = $view;
    }

    public function home($request, $response, $args) {
      // your code here
      // use $this->view to render the HTML
      return $response;
    }
}

Create a factory in the container that instantiates the controller
  with the dependencies:
$container = $app->getContainer();
$container->set('HomeController', function (ContainerInterface $c) {
    $view = $c->get('view'); // retrieve the 'view' from the container
    return new HomeController($view);
});

This allows you to leverage the container for dependency injection and
  so you can inject specific dependencies into the controller.

Но к сожалению, повторив всё это, я получаю ошибку

"Callable \HomeController does not exist"

A: Ошибка возникает из-за того, что Ваш контроллер находится в контейнере под ключом HomeController, а приложение ищет обработчик по ключу \HomeController.
Попробуйте указать одинаковые значения в роутинге и инициализации контейнера.
$container->set(\HomeController::class, function (ContainerInterface $c) {
    $view = $c->get('view'); // retrieve the 'view' from the container
    return new HomeController($view);
});

// ...

$app->get('/', \HomeController::class . ':home');