text:
Q: Keyerror in partial update using django-rest-framework I am trying to do partial updates (patches) on my endpoint, but I find keyerror "profile". The creation and update part is ok. But the patch does not.
My Serializer:
class UserProfileSerializer(
    serializers.ModelSerializer
):

    class Meta:
        model = Profile
        exclude = ("user", )

class UserSerializer(
    serializers.ModelSerializer
):
    profile = UserProfileSerializer(partial=True)

    def create(self, validated_data):
        profile = validated_data.pop('profile')
        user = super(UserSerializer, self).create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        user.profile.company = profile["company"]
        user.profile.save()
        return user

    def update(self, instance, validated_data):
        profile = validated_data.pop('profile')
        user = super().update(instance, validated_data)
        user.set_password(validated_data['password'])
        user.save()
        user.profile.company = profile["company"]
        user.profile.save()
        return user

    class Meta:
        model = User
        exclude = ("groups", "user_permissions", )

My view:
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    model = User

As I said above, the create and update part is ok.
One way I tried was to create a partial_update method in the view, but it didn't work out. Here the example:
    def partial_update(self, request, *args, **kwargs):
        user = User.objects.get(**kwargs)
        profile = Profile.objects.get(user=user)
        serializer = UserSerializer(user.profile, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response("OK")
        return Response("Nop")

The serializer is invalid.
Without using this method, when I use the patch (using postman) I get the error:
KeyError at /api/v1/user/79/
'profile'

More info for @ToniSredanović
My patch request:
{
 "username": "insomnia77"
}

My traceback:
Traceback:

File "/home/joey/PycharmProjects/backend/.venv/lib64/python3.7/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/home/joey/PycharmProjects/backend/.venv/lib64/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "/home/joey/PycharmProjects/backend/.venv/lib64/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/joey/PycharmProjects/backend/.venv/lib64/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/home/joey/PycharmProjects/backend/.venv/lib64/python3.7/site-packages/rest_framework/viewsets.py" in view
  103.             return self.dispatch(request, *args, **kwargs)

File "/home/joey/PycharmProjects/backend/.venv/lib64/python3.7/site-packages/rest_framework/views.py" in dispatch
  483.             response = self.handle_exception(exc)

File "/home/joey/PycharmProjects/backend/.venv/lib64/python3.7/site-packages/rest_framework/views.py" in handle_exception
  443.             self.raise_uncaught_exception(exc)

File "/home/joey/PycharmProjects/backend/.venv/lib64/python3.7/site-packages/rest_framework/views.py" in dispatch
  480.             response = handler(request, *args, **kwargs)

File "/home/joey/PycharmProjects/backend/.venv/lib64/python3.7/site-packages/rest_framework/mixins.py" in partial_update
  84.         return self.update(request, *args, **kwargs)

File "/home/joey/PycharmProjects/backend/.venv/lib64/python3.7/site-packages/rest_framework/mixins.py" in update
  70.         self.perform_update(serializer)

File "/home/joey/PycharmProjects/backend/.venv/lib64/python3.7/site-packages/rest_framework/mixins.py" in perform_update
  80.         serializer.save()

File "/home/joey/PycharmProjects/backend/.venv/lib64/python3.7/site-packages/rest_framework/serializers.py" in save
  209.             self.instance = self.update(self.instance, validated_data)

File "/home/joey/PycharmProjects/backend/frontend_api/v1/serializers/core.py" in update
  45.         profile = validated_data.pop('profile')

Exception Type: KeyError at /interface/v1/user/79/
Exception Value: 'profile'
Request information:
USER: joey

GET: No GET data

POST: No POST data

FILES: No FILES data

COOKIES: No cookie data


text:
Q: How to pass a value from bash into expect? I've got a really simple bash script which requires expect.
I need to pass a value from bash into expect and I'm not trying to ssh into another server or anything (cause I only seem to find questions regarding logging into another server via ssh).
The idea is simply something like this:
#!/usr/bin/env bash

echo "Please enter your password: "
read PASSWD

x=$(expect -c '
    spawn su -c 'whoami'
    expect "Password:"
    send "$PASSWD\r"
    interact
')

So this doesn't work. The expect shell doesn't recognize the $PASSWD variable.
How may this be accomplished?
Thank you.

A: Variables within single quotes are not expanded by the shell, that's why in this case $PASSWD remains the literal string $PASSWD.
Try changing the quotes:
#!/usr/bin/env bash

echo "Please enter your password: "
read PASSWD

x=$(expect -c "
    spawn su -c 'whoami'
    expect 'Password:'
    send '$PASSWD\r'
    interact
")

One more note: you should be aware that this could pose a security risk, as the password will be visible in plaintext in the process list while the command is running.

A: Another option would be to store the PASSWD in the environment and let expect pick it up there:
read -p "Your password: " passwd
export passwd

expect -c '... ; send "$env(passwd)\r"; ...'

Probably the best choice security-wise is have expect prompt for the password: then, the password will not show up on the command line nor in the environment.
expect -c <<'END'
    stty -echo
    send_user "Your password: "
    expect_user -re "(.*)\n"
    send_user "\n"
    set passwd $expect_out(1,string)
    stty echo

    # your script starts here
    ...
    send "$passwd\r"
    ...
END

redpajama_set_name: RedPajamaStackExchange


text:
Q: which.max not functioning as expected I am trying to create a table that includes the value of y for when x is equal to or less than a certain value, by group. Below is my code using the iris data set.
For "<=2.5", I expect to get 4.5, 5.0, or 5.8 for the virginica group, since these are the values of Petal.Length associated with a Sepal.Width of 2.5 for virginica. But instead, I get 6.0. Any ideas of where I went wrong? (My actual data set does not have duplicates of the variable analogous to Sepal.Width for the same group, so choosing among those is not an issue for me.)
data(iris)

my.table <- iris %>%
  group_by(Species) %>%
  summarise("<=2.5" = Petal.Length[which.max(Sepal.Width[Sepal.Width<=2.5])],
            "<=3" = Petal.Length[which.max(Sepal.Width[Sepal.Width<=3])],
            "<=3.5" = Petal.Length[which.max(Sepal.Width[Sepal.Width<=3.5])],
            "<=4" = Petal.Length[which.max(Sepal.Width[Sepal.Width<=4])])

This is related to the question Create a table with values from ecdf graph

A: The problem is that you are first subsetting the Sepal.Width. Consequently, the index returned by which.max applies to that sub-vector, and no longer corresponds to the indices of the whole Petal.Length vector.
To fix this, you also need to subset Petal.Length correspondingly, e.g.
…
`<=2.5` = Petal.Length[Sepal.Width <= 2.5][which.max(Sepal.Width[Sepal.Width <= 2.5])],
…

… of course this gets rather verbose and repetitive. It might be better to perform the subsetting in a separate step. However, this means creating new columns for every threshold value.
Incidentally, this is unrelated to dplyr.

A: To make it more scalable, using double loop:
myCuts <- c(2.5, 3, 3.5, 4)

res <- sapply(split(iris, iris$Species), function(i)
  sapply(myCuts, function(j){
    x <- i[ i$Sepal.Width <= j, ]
    x$Petal.Length[ which.max(x$Sepal.Width) ]
  }))

rownames(res) <- paste0("<=", myCuts)
res
#       setosa versicolor virginica
# <=2.5    1.3        3.9       4.5
# <=3      1.4        4.2       5.9
# <=3.5    1.4        4.5       5.6
# <=4      1.2        4.5       6.7

A: Here's another way to get the same data. Create a group variable according to Sepal.Width values. Then within each group, select the row with the top Sepal.Width value. It is in a different "shape", but you can always pivot_wider if you want all the values as columns instead of rows.
iris %>%
  group_by(Species,
           Sepal.Width_grp = case_when(Sepal.Width <= 2.5 ~ '<=2.5',
                                       Sepal.Width <= 3 ~ '<=3',
                                       Sepal.Width <= 3.5 ~ '<=3.5',
                                       Sepal.Width <= 4 ~ '<=4',
                                       TRUE ~ '> 4')) %>%
  top_n(1, -Sepal.Width) %>%
  select(Species, Sepal.Width_grp, Top.Sepal.Width = Sepal.Width, Petal.Width)
# # A tibble: 25 x 4
# # Groups:   Species, Sepal.Width_grp [12]
#    Species Sepal.Width_grp Top.Sepal.Width Petal.Width
#    <fct>   <chr>                     <dbl>       <dbl>
#  1 setosa  <=3.5                       3.1         0.2
#  2 setosa  <=4                         3.6         0.2
#  3 setosa  <=3                         2.9         0.2
#  4 setosa  <=3.5                       3.1         0.1
#  5 setosa  <=4                         3.6         0.2
#  6 setosa  <=3.5                       3.1         0.2
#  7 setosa  > 4                         4.1         0.1
#  8 setosa  <=3.5                       3.1         0.2
#  9 setosa  <=4                         3.6         0.1
# 10 setosa  <=2.5                       2.3         0.3
# # ... with 15 more rows

Edit: A little simpler if you use cut
iris %>%
  group_by(Species,
           Sepal.Width_grp = cut(Sepal.Width, c(0, 2.5, 3, 3.5, 4, Inf))) %>%
  top_n(1, -Sepal.Width) %>%
  select(Species, Sepal.Width_grp, Top.Sepal.Width = Sepal.Width, Petal.Width)
# # A tibble: 25 x 4
# # Groups:   Species, Sepal.Width_grp [12]
#    Species Sepal.Width_grp Top.Sepal.Width Petal.Width
#    <fct>   <fct>                     <dbl>       <dbl>
#  1 setosa  (3,3.5]                     3.1         0.2
#  2 setosa  (3.5,4]                     3.6         0.2
#  3 setosa  (2.5,3]                     2.9         0.2
#  4 setosa  (3,3.5]                     3.1         0.1
#  5 setosa  (3.5,4]                     3.6         0.2
#  6 setosa  (3,3.5]                     3.1         0.2
#  7 setosa  (4,Inf]                     4.1         0.1
#  8 setosa  (3,3.5]                     3.1         0.2
#  9 setosa  (3.5,4]                     3.6         0.1
# 10 setosa  (0,2.5]                     2.3         0.3
# # ... with 15 more rows


text:
Q: Modify Ace Editor Gutter div Is it possible to modify the gutter and add a custom div inside the gutter lines div?
Example :

A: no, normally you html inside gutter div will be overwritten by gutter.


text:
Q: Remove duplicated dots from file name I have a dir with tons of files inside which have been named in malformed such as file..txt ,file2..txt ,etc...
So how to easily remove this second . from file names?
Any applicable method is appreciated including awk,sed,grep,etc...

A: Using rename (as per heemayl's suggestion I narrowed down the globbing only to filenames ending exactly with ..txt):
rename -n 's/(.*)\./$1/' *..txt

This will match the filename until the last dot and replace the match with everything but the last dot.
If the result is the expected one, remove the -n option:
rename 's/(.*)\./$1/' *..txt

A: I have a working solution, still working for better one:
for f in *; do mv $f ${f%.txt}txt; done

Thank to @heemayl note:

Rather than using *, use *..txt to get the files as only * will cause
  problem when you have any file without . and with only one

So becomes:
for f in *..txt; do mv $f ${f%.txt}txt; done

A: Another rename variant:
rename 's/\Q.././' *..txt

using \Q avoids escaping the dots (See http://perldoc.perl.org/perlretut.html)

A: You may try the reverse order. This works if the filename contains newline characters.
rename 's/\.([^.]+)$/$1/' *..txt

A: The very simple way to do this just run the following command inside the directory which contains the filenames in the format u mentioned above
rename 's/\.+txt/\.txt/' *

A: Filenames can contains a newline character, therefore:
find . -maxdepth 1 -type f -print0 | while read -d $'\0' f; do mv "$f" "${f%.txt}txt"; done

Example
$ find -exec  printf "%s ---" {} \;
. ---./foo
..txt ---./foo..txt ---

$ find . -maxdepth 1 -type f -print0 | \
    while read -d $'\0' f; do mv "$f" "${f%.txt}txt"; done

$ find -exec  printf "%s ---" {} \;
. ---./foo
.txt ---./foo.txt ---

A: This works quite well if there's no single-dot files:
for file in *; do mv "$file" "${file%%.*}${file#*.}"; done


text:
Q: C# class and Graphics Continuation of thread: C# Invalidate troubles. I created the class but now I get an Error 2   Embedded statement cannot be a declaration or labeled statement. And I am trying to create the "Car" by Car aCar = new Car(50,100); that is where I am getting the error.
Thanks for the suggestions.
  class Car
    {
     private Pen pen1 = new Pen(Color.Blue, 2F);
     private Pen pen2 = new Pen(Color.Green, 2F);
     int cost = 0;
      int x, y;
      Graphics g;

public Car(int x, int y)
{
    this.x = x;
    this.y = y;
}

public void printCar()
{

    g.DrawEllipse(pen1, x, y, 30, 30);
    g.DrawEllipse(pen1, x + 100, y, 30, 30);
    g.DrawRectangle(pen2, x - 5, y + 50, 140, 50);
    g.DrawLine(pen2, x + 15, y + 50, x + 30, y + 90);
    g.DrawLine(pen2, x + 30, y + 90, x + 90, y + 90);
    g.DrawLine(pen2, x + 90, y + 90, x + 110, y + 50);
    // Create string to draw.
    String drawString = "Price: " + (cost).ToString("C");
    // Create font and brush.
    Font drawFont = new Font("Arial", 16);
    SolidBrush drawBrush = new SolidBrush(Color.Black);
    // Create point for upper-left corner of drawing.
    PointF drawPoint = new PointF(50, 95);
    // Draw string to screen.
    g.DrawString(drawString, drawFont, drawBrush, drawPoint);

}

public partial class Form1 : Form
    {
    private Pen pen1 = new Pen(Color.Blue, 2F);
    private Pen pen2 = new Pen(Color.Green, 2F);

    private double cost ;
    private int days = 0;
    private double air;
    private double automatic;
    int count;
    int m = 50;
    Car aCar = new Car(50, 60);

    public Form1()
    {

        InitializeComponent();

        days = int.Parse(textBox1.Text);

    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (comboBox1.SelectedItem.ToString() == "Van")
        {
            cost = 110;
            label1.Text = "The Cost of van per day" + (cost).ToString("C");
            textBox1.Text = "1";
            textBox1.Focus();
        }
        else if (comboBox1.SelectedItem.ToString() == "Car")
        {

            cost = 85.20;
            label1.Text = "The Cost of car per day" + (cost).ToString("C");
            textBox1.Text = "1";
            textBox1.Focus();
        }
        else
        {
            cost = 135;
            label1.Text = "Van" + (cost).ToString("C");
            textBox1.Text = "1";
            textBox1.Focus();
        }

    }

    private void button1_Click(object sender, EventArgs e)
    {
        count++;
        button1.Text = "Move";
        pictureBox1.Invalidate();
        if(count == 2)
            button1.Text = "Reset";
        if (count == 3)
        {
            textBox1.Text = "0";
            count = 0;
            comboBox1.Text = "select type of vehical";
            checkBox1.Checked = false;
            checkBox2.Checked = false;

        }
    }
    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
       e.Graphics.Clear(Color.White);

       if (count == 1)

       aCar.printCar();

      if (count == 2)

}
    private void Form1_Load(object sender, EventArgs e)
    {

    }

A: The end of your picturebox1_Paint method opens an if statement but doesn't actually contain a body.  That is illegal:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
   e.Graphics.Clear(Color.White);

   if (count == 1)

   aCar.printCar();

   if (count == 2)  // <-- This is illegal since the if statement is just dangling
}

A: You have to pass the Graphic object you are getting from the Paint event:
Public void printCar(Graphic g)
{
  // etc, etc
}

So that when you call it:
aCar.printCar(e.Graphics);


text:
Q: What is the difference between cycles and NextCycles in InstrStage in LLVM tablegen? I'm trying to learn LLVM tablegen. Right now I'm trying to understand how to define an instruction stage. I found a following comment in llvm/include/llvm/Target/TargetItinerary.td:
// Instruction stage - These values represent a non-pipelined step in
// the execution of an instruction.  Cycles represents the number of
// discrete time slots needed to complete the stage.  Units represent
// the choice of functional units that can be used to complete the
// stage.  Eg. IntUnit1, IntUnit2. NextCycles indicates how many
// cycles should elapse from the start of this stage to the start of
// the next stage in the itinerary.  For example:
//
// A stage is specified in one of two ways:
//
//   InstrStage<1, [FU_x, FU_y]>     - TimeInc defaults to Cycles
//   InstrStage<1, [FU_x, FU_y], 0>  - TimeInc explicit
//

What is the difference between cycle and NextCycle? It looks to me they are the same thing. What am I missing?
Any help is appreciated.


text:
Q: How can I get a sequence of dates in bash? In Z shell there is a command called dseq which produces consecutive dates.  For example:
$ dseq 5
2022-05-08
2022-05-09
2022-05-10
2022-05-11
2022-05-12

Is there a similar command in bash?  I tried the following which gets me close to the desired output.
$ seq -f "2022-05-%g" 5
2022-05-1
2022-05-2
2022-05-3
2022-05-4
2022-05-5

Two issues:

*

*how can I pad the days with 0 so the output contains two-digit days?

*how can I start the sequence from today versus the first of the month?

Desired output should match output of $ dseq 5 above.

A: You can have something like:
$ for i in {1..5}; do date -d "20220507+$i day" +%Y-%m-%d; done
2022-05-08
2022-05-09
2022-05-10
2022-05-11
2022-05-12

A: If you are on MacOS and don't want to install GNU date (which is what provides the nonstandard -d option which you'll find in most answers to related questions) you will need to perform relative date calculations yourself. Perhaps like this:
base=$(date +"%s")
for((i=0; i<5; ++i)); do
    date -r $((i * 24 * 60 * 60 + base)) +%Y-%m-%d
done

This avoids any complex date manipulations; if you need them, they are somewhat unobvious, and less versatile than the GNU date extensions - see, for example, How to convert date string to epoch timestamp with the OS X BSD `date` command?
For what it's worth, GNU date (and generally GNU userspace utilities) are the default on most Linux platforms.
With GNU date you could do date -d @timestamp +format where MacOS/BSD uses date -r timestamp +format.
If you need a portable solution, POSIX is not much help here, but a reasonably de facto portable solution is to use e.g. Perl. For inspiration, perhaps review What is a good way to determine dates in a date range?
perl -le 'use POSIX qw(strftime);
    $t = time;
    for $_ (1..5) {
        print strftime("%Y-%m-%d", localtime($t));
        $t += 24 * 60 * 60 }'

Demo (on Linux): https://ideone.com/WkAoib
In case it's not obvious, both these solutions get the current time's epoch (seconds since Jan 1, 1970) and then add increments of 24 hours * 60 minutes * 60 seconds to jump ahead one day at a time.


text:
Q: Run jQuery event handler only once I try to use a jquery event only once, and I have the following function:
function usrPlay() {
    var flag = true;
    while (flag === true) {
        $(".pincha").click(function() {
            console.log($(this).attr("value"));
            flag = false;
        });
    }
}

But...it seems that that makes an infinite loop, but I can`t see why.
Any help? Thank you!!

A: jQuery has a function named by .one() for this.
You can use the code below for your problem.
$(".pincha").one( "click", function(){
    console.log($(this).attr("value"));
});

For further information about .one()
http://api.jquery.com/one/

A:
But...it seems that that makes an infinite loop, but I can`t see why.

This is because you only attach event inside the loop, event handler is not executed inside loop so flag will not change to false. And you will probably need global flag var instead of local var because event handler will not be executed in scope of usrPlayfunction. Try this:
function usrPlay(){
  window.flag = true;
  $(".pincha").click(function(){
     if (window.flag === true){
       console.log($(this).attr("value"));
       window.flag = false;
     }
  });
}


text:
Q: Mockery to define multiple possible values to an expectation I am trying to declare an expectation that has two possible values as a parameter, based on the value I want the return value to be different.
Here is what I tried
$mock = m::mock('FooBar\ClassA');
$mock->shouldReceive('has')->with('foo')->andReturn(false);
$mock->shouldReceive('has')->with('bar')->andReturn(true);

I get this error

Mockery\Exception\NoMatchingExpectationException: No matching handler
  found for Mockery_2__FooBar_ClassA::has("bar")

I read through http://docs.mockery.io/en/latest/reference/expectations.html
but I am unable to find the answer. I am trying to resort to solving the problem with andReturnUsing which is straight-forward. Is there a way to solve the problem without using andReturnUsing?
$mock->shouldReceive('has')->andReturnUsing(function ($value) {
    switch ($value) {
    case 'foo': return false;
    case 'bar': return true;
    }
});

I also read Mockery specifying expected arguments for multiple calls
But that's the same thing I have tried, it forces validation on parameter type.

A: ok i found the answer
$mock->shouldReceive('has')->withArgs(['foo'])->andReturnValues([false]);
$mock->shouldReceive('has')->withArgs(['bar'])->andReturnValues([true]);

since withArgs is just a wrapper around with i think it is also possible to use with, but i think the param has to be inside an array


text:
Q: Create array from arrays of "tags" Say I have an a array like this:
Array (
  [0] => "bananas, apples, pineaples"
  [1] => "bananas, show cones"
  [2] => ""
  [3] => "apples, santa clause"
..
)

From that array I want to create a new array, holding each "tag", and the number of times it occuredd in the first array, preferebly sorted alphabetically,like this:
Array (
  [apples] => 2
  [bananas] => 2
..
)

or
array (
  [0] => [apples] => 2
..
)

A: // array to hold the results
$start = array( "bananas, apples, pineaples", "bananas, show cones", "", "apples, santa clause" );
// array to hold the results
$result = array();

// loop through each of the array of strings with comma separated values
foreach ($start as $words){

    // create a new array of individual words by spitting on the commas
    $wordarray = explode(",", $words);
    foreach($wordarray as $word){
        // remove surrounding spaces
        $word = trim($word);
        // ignore blank entries
        if (empty($word)) continue;

        // check if this word is already in the results array
        if (isset($result[$word])){
            // if there is already an entry, increment the word count
            $result[$word] += 1;
        } else {
            // set the initial count to 1
            $result[$word] = 1;
        }
    }
}
// print results
print_r($result);

A: assume your first Array as $array, and your result array as $tagsArray
foreach($array as $tagString)
{
    $tags = explode(',', $tagString);
    foreach($tags as $tag)
    {
        if(array_key_exists($tag, $tagsArray))
        {
           $tagsArray[$tag] += 1;
        }
        else
        {
           $tagsArray[$tag] = 1;
        }
    }

}

A: You can try using array_count_values
$array = Array(
        0 => "bananas, apples, pineaples",
        1 => "bananas, show cones",
        2 => "",
        3 => "apples, santa clause");

$list = array();
foreach ($array as $var ) {
    foreach (explode(",", $var) as $v ) {
        $list[] = trim($v);
    }
}
$output = array_count_values(array_filter($list));
var_dump($output);

Output
array
  'bananas' => int 2
  'apples' => int 2
  'pineaples' => int 1
  'show cones' => int 1
  'santa clause' => int 1


text:
Q: regular expression php tags I am usually pretty good to write simple regular expressions, but this time I cannot figure this out.
I need a regular expression that catches all the possible options:
<?php echo [^$]
<?php print [^$]
<? echo [^$]
<? print [^$]
<?echo [^$]
<?print [^$]
<?= [^$]
<?=[^$]

the [^$] stands for "non a $ character"
In other words I want to catch all the times that a print is done not using a variable.
I came up with something like this:
preg_match('/<\?[\s*|=|php]?\s*[echo\s|print\s]?\s*[^\$]/i',$content);

it doesn't work, can't figure out what would be the way to write it..

A: This is because regular expressions in the short form are line noise.  No one should have to try to program them, and especially no one should have to try to read them.
Try using the extended flag /x so you can use white space and add comments, both for others and for your future self.
This could be improved by someone better at regular expressions, but it gives you an example of how to start:
/
<\?                 # bracket and question mark
\s*                 # 0 to any white space
(php|echo|print|=)  # php or echo or print or equal sign
\s*                 # optional white space
(echo|print)*       # optional echo or print
\s*                 # optional white space
(\{|\[)             # curly brace or square bracket
\^                  # caret
\$                  # $
]                   # square bracket
/gx

Also, an online tool can help you build it up and see the results step by step:
http://gskinner.com/RegExr/
You can see a more detailed example of how to do this in php at the nettuts+ article on Advanced Regular Expressions Tips and Techniques.

A: <\?(((php)?\s*(echo|print))|=)\s*((\[|\{)\^\$])

where:

*

*<\? - starts with <?
then followed by either:

*

*(php)? - either has the php intro or not

*(echo|print) - either echo or print
or:

*

*= - a short hand echo

then followed by your [^$] or {^$]

A: Not entirely sure what you want. but this /<\?(php|=)?\s*?(echo|print)?\s*?(\{|\[)\^\$\]/i regex matches against everything in the options (I think, I created it using a Java based regex tester and then modified it to work in PHP tester, the results seem to be useful though, but not sure what you want, it does return true).


text:
Q: Error al filtrar consulta SQL Se supone que esta consulta tiene que filtrar por todas las condiciones que están después del where o bien combinar las condiciones pero, al momento de yo poner un rango de fecha, un nombre y un título de interacción, los datos no se filtran como deberían.
SELECT DISTINCT cl.first_name as Nombre, cl.last_name as apellido,cl.id_personal as Cedula, cl.phone as phone,it.title as interacion, fecha
FROM (SELECT interactions.create_date as fecha FROM interactions WHERE interactions.create_date BETWEEN '2017-10-23' AND '2017-10-23') sa, clients_profile cl left join interactions it ON cl.id = it.id_client_profile
WHERE   cl.first_name = '' OR
        cl.last_name =  '' OR
        cl.phone = '' OR
        cl.id_personal ='' OR
        it.title = '';

este es un ejemplo del resultado que me da al intentar filtrar por los 2 campos, lo que sucedes es que busco lograr un query donde filtre los datos mediante los parametros y si no envia uno que filtre por al menos 1 que, en este caso seria las fechas

A: Tu consulta (simplificada) es
SELECT DISTINCT
   cl.first_name as Nombre,
   cl.last_name as apellido,
   cl.id_personal as Cedula,
   cl.phone as phone,
   it.title as interacion,
   fecha
FROM clients_profile cl
left join interactions it ON cl.id = it.id_client_profile
WHERE   cl.first_name = 'delvin' OR
        it.create_date BETWEEN '2017-10-23' AND '2017-10-23'

Está pidiendo todos los registros donde el nombre sea 'delvin' O la fecha esté entre las dos fechas que pusiste. El resultado te va a dar todas las interacciones de 'delvin' en toda la eternidad, y todas las interacciones del resto de las personas en el rango de fecha.
Si envías los dos parámetros, entonces la condición debiera ser un AND en vez de un OR


text:
Q: how to work with Vagrant with github repository? Someone please describe how to work with vagrant? what i have done so far
I have installed Virtual Machine
Installed Vagrant
run few command and now Ubuntu 32 bit is installed in virtual machine

I have my project on github.
I make clone of the repository on my desktop ( D:)
created clone on my desktop
now my question is how to work with this repository code and associate vagrant?
Clearly no idea what this Vagrant actually is?

A: I think you have web project written in php. First you need to define vagrant folder. Clone your repository to the folder from your host machine. For folder in guest machine , let apache  know where is you host. This is the step you need to do.
But I wanna suggest you to learn how vagrant work first. If you don't know the concept, it will not be ok. And you can use https://puphpet.com/ for vagrant configuration.


text:
Q: 3G + GPS shield for Arduino Tracker i bought this shield.
My project is to make a tracker using the gps and upload the data to server
this is the code im using
int8_t answer;
int onModulePin= 2;
char gps_data[100];
int counter;

char aux_str[50];

char server[ ]="***.***.net";
char port[ ]="80";

void setup(){

pinMode(onModulePin, OUTPUT);
Serial.begin(115200);

Serial.println("Starting...");
power_on();

delay(5000);

// starts GPS session in stand alone mode
answer = sendATcommand("AT+CGPS=1,1","OK",1000);
if (answer == 0)
{
Serial.println("Error starting the GPS");
Serial.println("The code stucks here!!");
while(1);
}

//sendATcommand("AT+CPIN=5512", "OK", 2000);
//delay(3000);

while( (sendATcommand("AT+CREG?", "+CREG: 0,1", 500) ||
sendATcommand("AT+CREG?", "+CREG: 0,5", 500)) == 0 );

// sets APN, user name and password
sendATcommand("AT+CGSOCKCONT=1,\"\",\"jawalnet.com.sa\"", "OK", 2000);
sendATcommand("AT+CSOCKAUTH=1,1,\"\",\"\"", "OK", 2000);

}
void loop(){

answer = sendATcommand("AT+CGPSINFO","+CGPSINFO:",1000); // request info from GPS
if (answer == 1)
{

counter = 0;
do{
while(Serial.available() == 0);
gps_data[counter] = Serial.read();
counter++;
}
while(gps_data[counter - 1] != '\r');
gps_data[counter] = '\0';
if(gps_data[0] == ',')
{
Serial.println("No GPS data available");
}
else
{
Serial.print("GPS data:");
Serial.println(gps_data);
Serial.println("");

sprintf(aux_str, "AT+NETOPEN=\"TCP\",%s", port);
answer = sendATcommand(aux_str, "Network opened", 20000);

if (answer == 1)
{
Serial.println("Network opened");
sprintf(aux_str, "AT+TCPCONNECT=\"%s\",%s", server, port);
answer = sendATcommand(aux_str, "Connect ok", 20000);
if (answer == 1)
{
Serial.println("Socket opened");
sprintf(aux_str, "AT+TCPWRITE=%d", strlen(gps_data));
answer = sendATcommand(aux_str, ">", 20000);
if (answer == 1)
{
sendATcommand(gps_data, "Send OK", 20000);
}
sendATcommand("AT+NETCLOSE", "OK", 20000);
}
else
{
Serial.println("Error opening the socket");
sendATcommand("AT+NETCLOSE", "OK", 20000);
}
}
else
{
Serial.println("Error opening the nertwork");
sendATcommand("AT+NETCLOSE", "OK", 20000);
}

}

}
else
{
Serial.println("Error");
}

delay(5000);
}

void power_on(){

uint8_t answer=0;

// checks if the module is started
answer = sendATcommand("AT", "OK", 2000);
if (answer == 0)
{
// power on pulse
digitalWrite(onModulePin,HIGH);
delay(3000);
digitalWrite(onModulePin,LOW);

// waits for an answer from the module
while(answer == 0){
// Send AT every two seconds and wait for the answer
answer = sendATcommand("AT", "OK", 2000);
}
}

}

int8_t sendATcommand(char* ATcommand, char* expected_answer1, unsigned int timeout)
{

uint8_t x=0, answer=0;
char response[100];
unsigned long previous;

memset(response, '\0', 100); // Initialize the string

delay(100);

while( Serial.available() > 0) Serial.read(); // Clean the input buffer

Serial.println(ATcommand); // Send the AT command

x = 0;
previous = millis();

// this loop waits for the answer
do{

if(Serial.available() != 0){
response[x] = Serial.read();
x++;
// check if the desired answer is in the response of the module
if (strstr(response, expected_answer1) != NULL)
{
answer = 1;
}
}
// Waits for the asnwer with time out
}
while((answer == 0) && ((millis() - previous) < timeout));

 Serial.println(response);

return answer;
}

i don't know why its not connecting to the server !
this is on serial monitor
    AT+NETOPEN="TCP",80

    Network opened

    AT+TCPCONNECT="malik.basalamah.net",80

    Connect ok
    Socket opened
    AT+TCPWRITE=55

    >
    2124.751744,N,03946.686557,E,010314,154812.0,267.0,0,0

    ted

AT+TCPWRITE=55 to /index.html not supported.

    +IPCLOSE: 255, 1, 173.236.148.10, 80

    +IPCLOSE: 255, 2, 173.236.148.10, 80
    html>
    <title>501 Method NotStarting...

this is the php script < im just trying to get response from server >
<?php
 var_dump($_REQUEST["gps_data"]);
?>

please help me !

A: You are opening TCP connection and trying to read it as HTTP, it wont work this way. If you want to get data in PHP, you have to open HTTP connection instead.


text:
Q: F# Feliz.Bulma dropdown/combobox My question is very simple - how to create combobox (dropdown) in SAFE project (using Feliz.Bulma) and populate it programmatically.
In the docs there is no such component. This is the only example (Fulma) I found and can not incorporate it in my project.

A: For a simple dropdown you can use Bulma.select in combination with Html.option:
let dropDownValues = [
    0, "Zero"
    1, "One"
    2, "Two" ]

let dropDown =
    Bulma.select [
        prop.onChange (fun (v: int) -> dispatch ...)
        prop.children [
            for (value, text) in dropDownValues do
                Html.option [
                    prop.value value
                    prop.text text ] ] ]

A: I end up using Fulma code:
let createManufacturerDropdown (dispatch: Msg2 -> unit) =
let cases = FSharpType.GetUnionCases typeof<Manufacturer>
Dropdown.dropdown [ Dropdown.IsHoverable
                     ] [
    Dropdown.trigger [] [
        Button.button [] [
            span [] [ str "Select Maker" ]
            Icon.icon [ Icon.Size IsSmall ] [
                Fa.i [ Fa.Solid.AngleDown ] []
            ]
        ]
    ]
    Dropdown.menu [  ] [
        Dropdown.content [] [
            for m in cases ->
             Dropdown.Item.a [  Dropdown.Item.Props[  OnClick (fun _ -> SelectedManufacturerName m.Name |> BikeScreenMsg |> dispatch)  ] ]
                 [
                 str m.Name
             ]
        ]
    ]
]


text:
Q: C# DataSet GetChanges() throw exception I have a DataSet where the GetChanges() return this:

An unhandled exception of type 'System.Data.ConstraintException' occurred in System.Data.dll
      Additional information: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.

How can I tell in what table the problem is?
It happens before I save the tables. If I skip the Getchanges(), the save is OK.
Thanks


text:
Q: Are sets internally sorted, or is the __str__ method displaying a sorted list? I have a set, I add items (ints) to it, and when I print it, the items apparently are sorted:
a = set()
a.add(3)
a.add(2)
a.add(4)
a.add(1)
a.add(5)

print a
# set([1, 2, 3, 4, 5])

I have tried with various values, apparently it needs to be only ints.
I run Python 2.7.5 under MacOSX. It is also reproduced using repl.it (see http://repl.it/TpV)
The question is: is this documented somewhere (haven't find it so far), is it normal, is it something that can be relied on?
Extra question: when is the sort done? during the print? is it internally stored sorted? (is that even possible given the expected constant complexity of insertion?)

A: This is a coincidence. The data is neither sorted nor does __str__ sort.
The hash values for integers equal their value (except for -1 and long integers outside the sys.maxint range), which increases the chance that integers are slotted in order, but that's not a given.
set uses a hash table to track items contained, and ordering depends on the hash value, and insertion and deletion history.
The how and why of the interaction between integers and sets are all implementation details, and can easily vary from version to version. Python 3.3 introduced hash randomisation for certain types, and Python 3.4 expanded on this, making ordering of sets and dictionaries volatile between Python process restarts too (depending on the types of values stored).


text:
Q: High CPU Utilization of Influx DB 2.0 We are using influxdb2.0.6 as a K8s Pod in our environment.
We are continuously facing a lot of CPU Utilization by influx service.
How can I resolve this issue and minimize the CPU Utilization.


text:
Q: Proxy in development mode of React won't redirect I'm building an app with create-react-app.
I have local Apache server running on port 80 to execute my backend API PHP scripts.
I have added
"proxy": "http://localhost:80" to my package.json,
but on this axios requests:
 getAllCategories = () => {
      const url = process.env.PUBLIC_URL+`/api/api/categories/categories.php`;
      axios.get(url)
        .then(res => {
        const categories = res.data.data;
        this.setState({ categories });
      }).catch(err => {
        console.log('Axios fetch error:',err);
      })
    }

My request are directed to
Request URL: http://localhost:3000/api/api/categories/categories.php

according to Chrome Devtools and I'm not getting the data required.
In the build mode on remote server everything works fine with those paths indicated.
How can I configure proxy in dev mode to access my API files?

A: Have you tired path like this?
axios.get(`/api/api/categories/categories.php`)
...

A: If you are using create-react-app install http-proxy-middleware  as a dev dependency and in your src folder create a file called setupProxy.js (it must be spelt exactly like that).
In that file:
const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(proxy('/api', { target: 'http://localhost:80' }));
};

You will need to restart the app for it to take effect.
Your api calls should not need the process.env


text:
Q: Subsonic 3.0.0.4 views not working I went over to the subsonic website and downloaded the version 3.0.0.4. My project setup went well without errors. I then added the following to access two views in my DB
const string TABLE_SQL=@"SELECT *
    FROM  INFORMATION_SCHEMA.TABLES
    WHERE TABLE_TYPE='BASE TABLE'
    UNION
    SELECT TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME, 'View' TABLE_TYPE
    FROM INFORMATION_SCHEMA.VIEWS";

In Visual Studio 2010 I am seeing the views were generated, however when I do the following to test
MsgBox(Accounting.vwVendor.All().Count().ToString())

I get no data. If I run the same for other generated tables, it works fine. I do see the following in VS Immediate Window

A first chance exception of type
  'System.InvalidOperationException'
  occurred in SubSonic.Core.dll

Am I missing something for accessing SQL Server views via SubSonic?
UPDATED: I changed the target framework from Framework 4.0 Client Profile to Framework 3.5 Client Profile, build the solution, changed back the target framework to 4.0, build the solution and it worked!

A: The modification you list is all that should be needed to access Views with SubSonic.  I have even tested it in a new project, and had no issues.
If you post more details about the exception (like the stack trace), perhaps something will stand out.


text:
Q: How to get list of child elements of an element in Appium? I'm working with native iOS app through Appium.
I have the following structure:
UIAApplication ->
                  UIAWindow ->
                              UIATextBox
                              UIALabel
                  UIAWindow ->
                              SomethingElse

I have found a way to get the first UIAWindow and I'd like to get the list of all elements in that window. How do I do that?
I'd like to get UIATextBox and UIALabel from first UIAWindow but NOT SomethingElse element.
How do I do list of child elements in general?
  @Test
  public void testListWindows() {
      List<MobileElement> windows = driver.findElementsByClassName("UIAWindow");
      List<MobileElement> elements = windows.get(0).?????
  }

A: You're almost there. What you have is giving you a list of all UIAWindows when what you want is a list of all the elements of the first UIAWindow. I'd suggest using Xpath with a wildcard.
This will get you every element that is a direct child of the first UIAWindow:
List<MobileElement> elements = driver.findElements(MobileBy.xpath("//UIAWindow[1]/*");

And this will get you every child and sub-child and sub-sub-child etc. of the first UIAWindow:
List<MobileElement> elements = driver.findElements(MobileBy.xpath("//UIAWindow[1]//*");

An extra tip: If you're automating for iOS, I assume that means you have access to OS X, where you can install the Appium dot app and use inspector. The inspector is a great tool to test out xpath queries before putting them into your code.

A: You can also find textfield and label by its class for iOS app in Appium.  findElementsByClassName method will return all elements on current screen that matches that class.
List<MobileElement> textFields = driver.findElementsByClassName("UIATextField");
MobileElement textField = textFields.get(0);

List<MobileElement> labels = driver.findElementsByClassName("UIAStaticText");
MobileElement label = labels.get(0);


text:
Q: How can we know arithmetical axioms are consistent? If we assume both distributivity and the opposite of the law of signs (ie, that $-1\times-1 = -1$) for the relative integers, then we can derive that two different numbers are actually equal.
$$-2(5+-3) = -2\times2 = -4$$
but,
$$-2(5+-3) = -2\times5 + -2\times-3 = -10 + -6 = -16$$
The axioms that are conventionally assumed for the integers are simply the ring axioms. My question is, if the set of "axioms" described above turns out to be inconsistent, how can we be so sure that the ring axioms aren't inconsistent as well?
I'm aware of this question. On the one hand, I'm asking if you really need to venture that deeply into proof theory just for this (seemingly simple) special case. But if you do, could you provide an example of how to apply that technique to prove this special case?

A: The ring axioms are consistent because we can form models of these axioms; this is the content of the so-called soundness property of first-order logic: is a set of axioms has a model, then it is consistent.  For an easy example (noted by Henning Makholm in his comment), we can construct the two-element ring without extra assumptions, and show that it satisfies the ring axioms; of course, this ring is usually denoted $\mathbb Z / 2 \mathbb Z$, but we do not have to first construct the integers to create this ring.
(The opposite property, that every consistent set of axioms has a model, is the heart of Gödel's Completeness Theorem.)
On the other hand, the axiom system you have devised is also consistent: it will also hold in $\mathbb{Z} / 2 \mathbb{Z}$.  All you have noticed is that $\mathbb Z$ is not a model of this set of axioms.

A: We know there are no contradictions in the relative integers because we can simply define their operations like so (where $a, b \in \Bbb N$ and we assume $a-b$ is defined for $b \leq a$):
$$\begin{align}(+a) + (+b)&=+(a+b)\\\\
(+a) + (-b)&=\begin{cases}+(a-b) & \mathrm{if}\ b\leq a \\\\  -(b-a) & \mathrm{if}\ b> a\end{cases}\\\\
(-a) + (+b)&=(+b)+(-a)\\\\
(-a)+(-b)&=-(a+b)\end{align}$$
And similarly for multiplication. Note that for any given pair of relative integers, there is only one possible rule that could tell you how to add them together. Thus, given any expression involving relative integers, there is only one answer that you could possibly come to, as long as you rigorously apply the above rules.
Think of this in terms of the formal definition of an operation: a set of pairs of the form $((a,b), c)$, where $c$ is the result of applying the operation to $a$ and $b$. The answers to what any given expression is equal to are fixed, pre-determined, and there can't be any "contradictions" because each pair is associated with one and only one value.
Adding in distributivity as an axiom is so disastrous because we have no guarantee that it's true of our fixed, predetermined system. Given the above rules for relative integer addition, if we wanted to evaluate $(+5)+(-8)$. Currently, the third rule is the only one that fits the form of this expression, so that gives you the only possible answer. But imagine we were to add a new rule to our system:
$$(+a)+(-b)=(-b)+(+a)$$
i.e. we assume (a restricted form of) commutativity. Then there would be two possible ways to evaluate $(+5)+(-8)$, since two different rules would now fit the form of the expression. We have no guarantee that these rules will produce the same answer, which is why we can only have one rule for any possible expression.
Now, once we have the rules in place - one and only one rule for every form of expression - we can prove things like commutativity and distributivity, but we absolutely can not assume them as axioms.
So if it's so easy to see that the rules are consistent, what's all the fuss about with proof theory? Well in general, it's not so easy to see that a set of axioms is consistent. It happens to be easy with ones like the rules for addition I gave above, since each rule clearly applies to a different subset of input values. I'd like to emphasize this again, because it's key: as long as each rule applies to a distinct form of expression, you can't obtain any contradictions. You can't add in rules like distributivity, because they would overlap with the other rules, and it might not agree with them where they overlap.
Seen in this light, $-1\times-1=-1$ is no longer such an ugly thing. You could indeed define that rule, and again none of your rules would overlap, so no worries. The structure obtained wouldn't be distributive, that's all.
This is a major reason why formal construction of the various number systems isn't just mathemasturbation, it serves to fix the rules of the game and show that you won't run into any contradictions. Complex numbers can be constructed in much the same way, of course.


text:
Q: Listview overlay and highlighting listview items I have a ListView wrapped in Grid on top of which I have a panel overlay( How to make overlay control above all other controls?). I would like to highlight a listview item that is under even when the cursor is not directly over it.

I would like to have a highlight like this when the cursor is over the red rectangle.

<Grid Name="grid">
    <ListView Name="timeSpansListBox" SelectionMode="Extended" HorizontalAlignment="Left" Width="{Binding ElementName=timePanel, Path=ActualWidth}">
      ...
    </ListView>
    <!-- our overlay -->
    <MyPanel Name="timePanel" Panel.ZIndex="999">
      ... items (rectangles you can see on the image)
    </MyPanel>
</Grid>

How could I do this?
Similar issue: How to get control with lower zindex when mouse clicked in wpf?
I could set IsHitTestVisible to false but I need panel items to remain clickable so it's not an option.
If only there is some way to set IsMouseOver programmatically...

A: Set the vertical and horizontal alignment to stretch for the overlay panel
<MyPanel Name="timePanel" Panel.ZIndex="999"
         HorizontalAlignment="Stretch"
         VerticalAlignment="Stretch">
    ... items (rectangles you can see on the image)
</MyPanel>


text:
Q: Cant access localhost/xampp to change root password I cannot get onto localhost/xampp to change the password for root as I keep getting the error in php about root not having a password.
I've tried command line, changing password in phpadmin which ends up ruining everything and having to reinstall xampp.
tried localhost/xampp
local../8080
local../80


text:
Q: Unable to reach the Spark cluster manager to request for executors I have a Spark Standalone setup in my Docker Swarm cluster (1 manager node, 2 worker nodes). I also have a livy container that is colocated with the Spark master container in the manager node.
When initializing livy sessions, the dynamic allocation works as intended. But if you leave the session idling for a few minutes then execute codes again, it won't be able to get more executors and will be stuck with the minimum number of executors.
Inspecting the session logs in the livy UI, I found this:
Caused by: java.io.IOException: Failed to send RPC RPC 8079653042324188410 to master/10.0.2.97:7077: java.nio.channels.ClosedChannelException
    at org.apache.spark.network.client.TransportClient$RpcChannelListener.handleFailure(TransportClient.java:362)
    at org.apache.spark.network.client.TransportClient$StdChannelListener.operationComplete(TransportClient.java:339)
    at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:507)
    at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:481)
    at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:420)
    at io.netty.util.concurrent.DefaultPromise.tryFailure(DefaultPromise.java:122)
    at io.netty.channel.AbstractChannel$AbstractUnsafe.safeSetFailure(AbstractChannel.java:987)
    at io.netty.channel.AbstractChannel$AbstractUnsafe.write(AbstractChannel.java:869)
    at io.netty.channel.DefaultChannelPipeline$HeadContext.write(DefaultChannelPipeline.java:1316)
    at io.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)
    at io.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)
    at io.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)
    at io.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1081)
    at io.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1128)
    at io.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1070)
    at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
    at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:403)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:463)
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
    at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138)
    ... 1 more
Caused by: java.nio.channels.ClosedChannelException
    at io.netty.channel.AbstractChannel$AbstractUnsafe.write(...)(Unknown Source)
20/05/27 06:41:41 WARN spark.ExecutorAllocationManager: Unable to reach the cluster manager to request 2 total executors!

What's weird is when I ping master inside the livy container, it was able to resolve the master hostname just fine.
I am actually lost on how to resolve this. Already tried messing with the spark-defaults.conf networking parameters but it seems I am not able to change the right config that would solve this.


text:
Q: Is there a name for the unit "Ampere meter"? Motivation: I'm doing a homework problem involving a rod sliding freely down a pair of parallel conducting rails.  I've got a quantity of unit $\mathrm{A \cdot m}$ and want to know what I should name and call it.
Is there a conventional letter for that quantity (like $q$ for charge) or a conventional name for that unit. (I'm thinking "charge velocity" - as in "the charge velocity is $1.0\,\mathrm{A \cdot m}$" - would be a good name, but am hesitant to "coin a unit" as part of my homework problem.)
RE comment: The problem is to calculate the terminal velocity of said rod when it is placed on a 15-degree inclined plane, given the resistance of the loop is 15 ohms.  I found the emf using black magic Faraday's Law, obtained the current, and multiplied by the length vector of the rod to get a vector quantity in Ampere-meters, and took the cross product of this with the B field to get the drag on the rod.

A: Such a quantity does not have a commonly-used name. See https://en.wikipedia.org/wiki/SI_derived_unit

A: The units of H-field (magnetic field strength, or magnetic field intensity) are A/m.
So Ampere metres could represent a flux of H-field.
Unlike the B-field, there can be "sources" and "sinks" of H (we call them magnetic poles), and so the total H-field flux into or out of a closed volume can be positive or negative, but would be zero in vacuum.
I'm not really sure how this applies to the problem at hand.

A: As others have stated, there is no common word for your quantity. As Rob Jeffries pointed out, it does have units of flux, but what you're describing is not a flux. I can, however, give you some intuition about the quantity. This is just one way of thinking about it:
You mentioned that you're getting this term from the Lorentz force law for a test wire in a magnetic field, $\vec{F}_\text{wire} = I\vec{L}\times\vec{B}$. You can read this equation as $I\left| L \right| \left|B\right|$ for the components of $I$ that are orthogonal to $B$. Using an analogy with gravity, the force on a test mass in a gravitational field is $m\vec{G}$, where $m$ is the gravitational charge (the mass of the test body).
Using this analogy, you can see that your term is something akin to a magnetic charge. Notice that the magnetic charge has two weird properties: It has a direction, and it's direction effects the force it feels in a magnetic field.


text:
Q: What did I do wrong with parsing MNIST dataset with BinaryReader in C#? I'm parsing MNIST datasets in C# from: http://yann.lecun.com/exdb/mnist/
I'm trying to read the first Int32 from a binary file:
FileStream fileS = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fileS);
int magicNumber = reader.ReadInt32();

However, it gives me a non-sense number: 50855936.
If I use File.ReadAllBytes()
buffer = File.ReadAllBytes(fileName);

and then look through the bytes, it works fine(the first four bytes now represents 2049), what did I do wrong with BinaryReader?
The file format is as follows (I'm trying to read the first magic number):
All the integers in the files are stored in the MSB first (high endian) format used by most non-Intel processors. Users of Intel processors and other low-endian machines must flip the bytes of the header.

TRAINING SET LABEL FILE (train-labels-idx1-ubyte):
[offset] [type]          [value]          [description]
0000     32 bit integer  0x00000801(2049) magic number (MSB first)
0004     32 bit integer  60000            number of items
0008     unsignebyte     ??               label
0009     unsigned byte   ??               label
........
xxxx     unsigned byte   ??               label
The labels values are 0 to 9.d

A: 50855936 == 0x03080000.  Or 0x00000803 when you reverse the bytes, required on almost any machine since little-endian has won the egg war.  Close enough to 2049, no great idea what explains the offset of 2.  Here's an extension method to help you read it:
  public static class BigEndianUtils {
      public static int ReadBigInt32(this BinaryReader br) {
          var bytes = br.ReadBytes(sizeof(Int32));
          if (BitConverter.IsLittleEndian) Array.Reverse(bytes);
          return BitConverter.ToInt32(bytes, 0);
      }
  }

Add additional methods if the file contains more field types, just substitute Int32 in the snippet.

A: It seems that your problem is somewhere else. Could you post a minimal compilable snippet that doesn't work as expected?
For example, this snippet works exactly as expected - it creates a binary file of 8 bytes, which are two big-endian Int32s. The reader then correctly reads the data as the two integers.
using (var str = File.Create("C:\\Test.dat"))
    using (var wr = new BinaryWriter(str))
    {
        wr.Write(2049);
        wr.Write(60000);
    }

using (var str = File.Open("C:\\Test.dat", FileMode.Open))
    using (var rdr = new BinaryReader(str))
    {
        rdr.ReadInt32().Dump();
        rdr.ReadInt32().Dump();
    }

However, the endianness is fixed. If you need to use MSB first, you need to read the bytes and convert them to integers yourself (or, you could of course invert the byte order using bitwise operations, if you're so inclined).


text:
Q: How to count/sum the number of text cells in a row I have a simple modell that stores text values. I like to count how many text cells I have in a single row where the result is not "nincs".
In this case I like to have (kap_bar_01 + kap_bar_02 + kap_bar_03 + kap_bar_04 + kap_bar_05) and the result I need is 3.

I tried this but it works not:
SELECT (kap_bar_01 + kap_bar_02 + kap_bar_03 + kap_bar_04 + kap_bar_05) FROM mymodell

Result is 0.
Thank you in advance!

A: Assuming the columns are not nullable, you can sum boolean expressions:
SELECT (kap_bar_01 <> 'nincs') +
       (kap_bar_02 <> 'nincs') +
       (kap_bar_03 <> 'nincs') +
       (kap_bar_04 <> 'nincs') +
       (kap_bar_05 <> 'nincs') AS result
FROM mymodell;

If they are nullable, use also COALESCE():
SELECT (COALESCE(kap_bar_01, '') <> 'nincs') +
       (COALESCE(kap_bar_02, '') <> 'nincs') +
       (COALESCE(kap_bar_03, '') <> 'nincs') +
       (COALESCE(kap_bar_04, '') <> 'nincs') +
       (COALESCE(kap_bar_05, '') <> 'nincs') AS result
FROM mymodell;


text:
Q: Why use PostalAddress property in Gql?
Possible Duplicate:
Why Email, Username, PostalCode, etc as entities in GAE Datastore

App Engine Data store has this property "PostalAddress" but what is the purpose of using it?
Here it is in the docs: https://developers.google.com/appengine/docs/python/datastore/typesandpropertyclasses#PostalAddress
I have addresses that I want to store and I was thinking if I ever wanted to get the cities or zip codes I'd be able to easily query them if I stored them in different column fields. Or is there a way to extract the zip code or city/state or street line from the postal address property without having to use regex on it...
Anyone know how use this property?

A: It's basically just a String property. No validation is performed or any kind of structure is assumed. They probably used it in order to support the gd:postalAddress element.
https://developers.google.com/gdata/docs/1.0/elements?hl=el#gdPostalAddress


text:
Q: Rails: sortable has_and_belongs_to_many relationships Given this relationship:
class Doc < ActiveRecord::Base
  has_and_belongs_to_many :articles
end

and
class Article < ActiveRecord::Base
  has_and_belongs_to_many :docs
end

How would you approach sorting the articles in the Doc with jQuery UI? I was following this tutorial, which was all well and good until it came time to run this migration:
rails g migration add_position_to_faqs position:integer

because it seems like doubling-up when I already have a relationship table, thus:
create_table "articles_docs", :id => false, :force => true do |t|
  t.integer "article_id"
  t.integer "doc_id"
end

add_index "articles_docs", ["article_id", "doc_id"], :name => "index_articles_docs_on_article_id_and_doc_id", :unique => true

Any thoughts at all? Not really understanding the relationship table isn't helping me figure this out.

A: Use has_many :through instead of has_and_belongs_to_many. That will give you an intermediary model to hold the position column, and you'll sort those rather than sorting the articles.


text:
Q: What is rules in firebase? & What $ mean in the value incode? What does $uid mean in the code ?
is $uid a column name or key name?
{
    "rules": {
        "users": {
            "$uid": {
                ".write": "$uid === auth.uid"
            }
        }
    }
}

A: as in document

A wildcard path used to represent ids and dynamic child keys.

more detail , let say you have this data
{
   users : {
      "SOME_KEY_1" : {"name" : 'test 1' , "private" : {...}} ,
      "SOME_KEY_2" : {"name" : 'test 2' , "private" : {...}} ,
      "SOME_KEY_3" : {"name" : 'test 3' , "private" : {...}} ,
   }
}

and these rule
{
   "rules" : {
       "users" : {
           "$uid" : {
                "private" : "auth != null && auth.uid === $uid"
           }
       }
   }
}

you cannot know the keys of users node but you need to prevent other users to private node except their own so you put $uid to represent dynamic child keys

in your case you just allowing user to write to their own data


text:
Q: using backslash to break lines into multiple lines for readability I am very bothered by the fact I can't do something like this in Python.
df['File name'].replace(False, attachment_name, inplace=True) \
               .replace(True, np.nan, inplace=True)

instead of this
df['File name'].replace(False, attachment_name, inplace=True)
df['File name'].replace(True, np.nan, inplace=True)

Can someone brighter than me correct me

A: In Python, putting a backslash at the end of the line creates a line continuation, which means "ignore the newline character and the next line's indent". So, the code:
object.do_something(False) \
      .do_something(True)

will be interpreted as
object.do_something(False).do_something(True)

Now, this may actually be what you want to do. It's often what you want to do with line continuation - you want to break one line for the machine into several lines for a human reader. So, what your code actually does is:

*

*Call the replace() method of df, with the specified parameters, and hold onto the value returned by replace.

*Call the replace() method of whatever the return value was, with the specified parameters.

So, this depends on the workings of df.replace. Given the name and parameters, I am going to assume that df is a pandas.DataFrame object. The documentation for pandas.DataFrame.replace says that it returns the caller (i.e. df) and the inplace parameter doesn't mention changing the return value. However, testing this out in an interactive shell, we see:
>>> df=pandas.DataFrame()
>>> df.replace()
Empty DataFrame
Columns: []
Index: []
>>> df.replace(inplace=True)
>>> type(df.replace())
<class 'pandas.core.frame.DataFrame'>
>>> type(df.replace(inplace=True))
<class 'NoneType'>

So, when we get to the second line, we aren't calling the replace method of a DataFrame, we are attempting to call the replace method of None - but None does not have a replace method, so Python throws an exception. There's a variety of reasons to do this, but they definitely should have documented that inplace=True will change the return value.
How do we get what you want then? Well, the easiest way is to make sure that df.replace returns a value with a replace method, which we can call and make sense of. Luckily, we have already found a way to do this - by not using inplace!
df = df.replace(False, attachment_name) \
       .replace(True, np.nan)

With the default inplace=False, we get a return value of type pandas.DataFrame, which has a replace method which will accept these parameters as valid. However, we do not assign anything to df now - so we have to add that in.
You may be tempted to set inplace=True on the final replace. This will not work, because the final replace is not being called on df - it's being called on the return value of df.replace, which is a different object. It won't raise an exception, but it will fail to change the value of df.

A: You can do it like that if you don't replace the values inplace
df['File name'] = df['File name'].replace(False, attachment_name).replace(True, np.nan)


text:
Q: Does anyone have a realistic theory to why Wolverine can't regenerate his memory? I watched the X-men movies and read some of the comics but I couldn't understand how he couldn't just regenerate his brain to get his memories? I thought things associated with his Nervous Systems could be the problem, but I want someone more scientific to help. And yes I read some of the other post and they did not explain in enough detail.

A: He can regenerate brain tissue, but if the original memories 'written' on that brain tissue are gone, say through a gunshot wound, as in the X-Men: Origins film, then simply regenerating the tissue will not bring them back.
To use a metaphor: it's like burning a piece of paper. Wolverine's power enables him to re-grow that piece of paper, but any writing or drawings on it are irretrievable.

A: Unfortunately there is no real world or in-world logic that would explain it. While each continuity handles it differently, they all have the same result; whatever damage was done to erase Wolverine's memories is permanent and cannot be undone easily.
Earth-199999, the MCU, is the simplest, as it shows when, where and how Logan lost his memories. An adamantium bullet shot through the skull scrambled his brains. His implicit memories (behavior, language, skills) are intact, but explicit memories are lost. Except they are not. Professor X is able to find and tries to unlock those memories. And Logan remembers some memories from before (WW2 prisoner of war during Little Boy). So the memories are repressed or inaccessible through normal means.
Earth-616 is so very convoluted its hard to keep track of. Decades of comic history can do that. Wolverine regenerates from being flattened by a steamroller and complete nuclear annihilation without memory loss. Other people with the same powers also don't suffer from memory loss. Deadpool for one, regularly blows his own brains out or other cranial damage, and is good to go. His memory loss stems from constant cancer growths and healing power fixing it. In 616, Wolverine goes through memory conditioning and reprogramming in the Weapon X project. Brainwashed to become an assassin, and that's where he loses most of his memories. False memories implanted via fake scenes and actors. Very technical, practical applications. I've read there were also telepaths or psychics involved. The memories are there, just buried.
In the end, the reason the Wolverine in the movie can't regenerate his memories are because the movies stick to some basic tenants of the comic character. Comic Wolverine has no memories, so neither should Movie Wolverine. Any reason given has to take that into account. In real life, physical damage to memory cells completely disconnect those memories with 0% chance of recovery through modern science. Some physical trauma causes memory loss, while mental trauma can cause repression of memories as a survival instinct (shock), two different causes with the same result. Amnesia simply means Memory Loss after all.

A: The answer is found in a story from Marvel called, "Origin". Wolverine was actually born James Howlett in late 19th century Alberta, Canada. But rather than go on through the twisted drama that actually lead to the manifestation of Wolverine's powers, we can use the aftermath to explain his memory loss. This was the first of many traumatic events Wolverine would find himself in, which afterwards he would start to have almost immediate amnesia.
Wolverine's mind treats traumatic memories as a psychic injury. Bringing back his memories would be the opposite of what his healing factor is trying to do, it would be like Wolverine's healing factor reopening wounds instead of closing them.
As a comparison, Sabretooth has a similar healing factor, but he's cruel and violent. His mind dances in unison with the rage, and therefore he doesn't believe anything he's done as traumatic. Thus, there is no need to "heal" his memories in the same way. Another comparison is Deadpool, who's healing factor is off the charts, but his mind is in constant flux because of it, which is often pointed as the reason for his "insanity/fourth wall breaking antics".
So no, there's no real life reason as to why Wolverine has memory loss. It's actually a tragic point that few talk about related to his healing factor.

A: Memories are like signals and if you have done something you have done before, your brain recreates those signals. If a well placed bullet lodges itself into Wolverines brain, then he would regenerate, but lose all his feelings and memories.


text:
Q: Why does some unicode characters appear as a box in the visual studio property grid? I can't type in certain special Unicode characters in the properties window for a control in Visual Studio 2017. The magnifying glass character (⌕) appears in the code just fine, but in the design mode for a file and the text property of the property grid for that item, it appears as a black box.
I've looked and googled around but I can't find any specific examples on adjusting this. I'm also not sure how to change the font in Visual Studio's property grid either.
I want to be able to see the magnifying glass, because the control displays the square box at runtime instead of a proper Unicode character.
In the image below – at the text property – you can see it is a black box, even though I typed/copied over the Unicode character. To the left is that control, and it shows the box character instead of a proper magnifying glass character.


text:
Q: Linear Layout UI Design
Hi, I'm a newbie to Android Development and am only 15.  I have been trying to produce a UI design like the one above with the red boxes being image buttons.  I have experimented with weight etc. but it cuts off the edge of the image every time.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearlayout_01"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linearlayout_02"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1" >

        <ImageButton
            android:id="@+id/squads"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:layout_weight="2"
            android:src="@drawable/squad" />

        <ImageButton
            android:id="@+id/results"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="10dp"
            android:layout_weight="2"
            android:src="@drawable/results" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearlayout_03"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1" >

        <ImageButton
            android:id="@+id/highlights"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:layout_weight="4"
            android:src="@drawable/highlights" />

        <ImageButton
            android:id="@+id/fixtures"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="10dp"
            android:layout_weight="4"
            android:src="@drawable/fixtures" />
    </LinearLayout>

</LinearLayout>

A: Don't use ImageButtons if you just need clickable images use ImageView with clickable="true" . Using ImageView you can try different scaleType property values to achieve what you need.

A: try this layout structure,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearlayout_01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<LinearLayout
    android:id="@+id/linearlayout_02"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    >

    <ImageButton
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:src="@drawable/ic_launcher" />
</LinearLayout>

<LinearLayout
    android:id="@+id/linearlayout_03"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    >

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:src="@drawable/ic_launcher" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="10dp"
        android:layout_weight="2"
        android:src="@drawable/ic_launcher" />
</LinearLayout>

<LinearLayout
    android:id="@+id/linearlayout_04"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
     >

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:layout_weight="2"
        android:src="@drawable/ic_launcher" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:src="@drawable/ic_launcher" />
</LinearLayout>

 <LinearLayout
    android:id="@+id/linearlayout_05"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    >

    <ImageButton
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:src="@drawable/ic_launcher" />
</LinearLayout>

here, default images are taken as ic_launcher.


text:
Q: Declare method unavailable since a specific version of iOS in swift 5 I wish to achieve something like that:
@unavailable(iOS 11.0, *)
func oldWay() {
    ...
}

@available(iOS 11.0, *)
func newWay() {
    ...
}

I've tried things like @available(iOS 11.0, unavailable, *) but it does not compile.
My problem is that I'm conforming to an Objective-C protocol with optional methods. Some of them are only available since iOS 11, my app is available since iOS 10 and I don't want to have both methods implemented for a given platform.
For instance if I do this:
func oldWay() {
    ...
}

@available(iOS 11.0, *)
func newWay() {
    ...
}

Both methods are implemented on all platforms since iOS 11... That's not what I'm looking for.
So if anyone has an idea...

A: You can use the deprecated: argument (and potentially message: as well), because that seems to be what's happening here:
@available(iOS, deprecated: 11.0, message: "Please use 'newWay'")
func oldWay() {

}

@available(iOS 11.0, *)
func newWay() {

}

This will produce a warning if you try to use the old way. If you want an error instead, replace deprecated with obsoleted.


text:
Q: Ideals in $C^*$-tensor products Let $A,B$ be $C^*$-algebras and assume that at least one of the two is nuclear, so $A\odot B$ admits a unique $C^*$-norm. Let $J\triangleleft A\otimes B$ be a closed, two-sided ideal in $A\otimes B$.
What I am trying to prove is this: for every $x\in J$ and any $\varepsilon>0$ we can find $z\in A\odot B$, say $z=\sum_{j=1}^na_i\otimes b_i$ such that $\|x-z\|<\varepsilon$ and every elementary tensor $a_i\otimes b_i$ belongs to $J$.
The thing is that I have no idea where to get started with this. For example, if $A,B$ are unital, then $A\otimes B$ contains canonical copies of $A$ and $B$ ($A\cong A\otimes\mathbb{C}1_B$, $B\cong\mathbb{C}1_A\otimes B$). The ideal $J$ then induces ideals $J_A\triangleleft A$ and $J_B\triangleleft B$ (through the above identifications) and these satisfy $J_A\otimes J_B\subset J$. The question is the same as showing the reverse inclusion. I believe something similar can be done for the non-unital case, probably by passing to the unitization. On the other hand, given any pair of ideals $I_1\triangleleft A$ and $I_2\triangleleft B$, we obtain an ideal $I_1\otimes I_2\triangleleft A\otimes B$.
This argument shows that our question is more or less the same as asking whether the ideals of $A\otimes B$ correspond to pairs of ideals in $A$ and $B$.
I think this is implied in a proof I'm studying but I have no reference. Does anyone know how to prove this or know where I should be looking for a proof?


text:
Q: webmail.example.com throws 404 for HTTPS only on hosted server I have a several web sites running on a shared hosted server.
Every site except one I can enter in my browser https://webmail.example.com or http://webmail.example.com and they both work and resolve to the secure or insecure pages accordingly.
On the one site the page resolves correctly for regular http but I get a "404 Not found" error when I try https for the webmail subdomain of that site. https://myexample.com does work for all pages on that site (without the webmail subdomain).
All of the DNS settings are the same for all of the sites. There is a CNAME record webmail.example.com --> examplecom. None of the sites have a "proper" subdomain setup where the subdoman points to a directory, just the DNS setting. The SSL Status reports that the SSL cert for the webmail subdomain is valid.
Im not sure what else to check or how webmail ultimately get pointed  to the webmail page.


text:
Q: Issue with Swift 2.2 generics (Xcode 7.3) I've got a frustrating situation with Swift 2.2 (Xcode 7.3). To simulate it, just create a variable in a user defined, generic class, and reference that class from someplace else. For example:
class A<T> {
    let genVar = 1
}

class MyViewController: UIViewController {
    let myVar = A<Int>() // crash is here
}

If you will run this code on a device running iOS 7 (iPhone 4, in my case), it will crash on the attempt of creating a variable of generic type. Here are the first lines of the device crash log:
Exception Type:  EXC_BAD_ACCESS (SIGBUS)
Exception Subtype: KERN_PROTECTION_FAILURE at 0x00298910
Triggered by Thread:  0

Thread 0 Crashed:
0   libswiftCore.dylib              0x006b1d64 0x4bd000 + 2051428
1   Phone                           0x001c76ec 0xab000 + 1165036
2   libswiftCore.dylib              0x006b307c 0x4bd000 + 2056316
3   libswiftCore.dylib              0x006b2f70 0x4bd000 + 2056048
4   libswiftCore.dylib              0x006b0f24 0x4bd000 + 2047780
5   libswiftCore.dylib              0x006b107c 0x4bd000 + 2048124
6   Phone                           0x0014e730 0xab000 + 669488
7   Phone                           0x00129390 0xab000 + 517008
8   UIKit                           0x31e9d9c4 -[UIClassSwapper initWithCoder:] + 188

On iOS 8 and 9 simulators/devices, the code above works okay.
Is Swift support for iOS 7 going to be dropped in the near future?

A: I've been tripped up by what appears to be two bugs with Swift generics in iOS 7. Here's how to fix them.
Bug #1 - you must define a generic as the first property in your class before any others.
Example - this code fails:
public class TestIOS7<T> {

    private var x: Int?
}

let x = TestIOS7<String>()

But here's the workaround:
public class TestIOS7<T> {

    private var kludge: T?
    private var x: Int?
}

let x = TestIOS7<String>()

Bug #2: Class constraints seem completely broken.
Example - this code fails:
class ClassA<B: ClassB> { }

class ClassB { }

let x = ClassA <String>()

I have not found any workaround aside from removing the "ClassB" constraint and rewriting all the code to deal with the fact that basically, this language feature no longer exists. This is particular painful when you need to call an initializer of ClassB from ClassA - I had to rewrite that block with hardwired if/then/else for all my ClassB subclasses until Apple fixes this.
If someone does find a workaround to Bug #2 please let me know!

A: As this bug suggests, you have following possible workarounds:

*

*make class non-generic

*remove value property

*swap object and value properties declarations

*initialize object in init
Probably the best workaround is to initialize object in init:
class A<T> {
    let genVar: Int
    init() {
       genVar = 1
    }

}

class MyViewController: UIViewController {
    let myVar = A<Int>() // no crash
}

A: We faced the same issue.
A work-around was discovered though that would at least let us support iOS7 without a significant rewrite.
It looks like all subclasses must also be generic so that the parent generic works correctly in iOS7.
The subclass's generic type does not matter and it does not need to be the parent's generic type.
I also posted this answer on the bug discussion simpleBob linked.
Example:
// This heavily pollutes the codebase, so let's keep track of it but using a common meaningless generic value so we can find and destroy later when we no longer support iOS7
protocol iOS7SwiftGenericFixProtocol {}
struct iOS7SwiftGenericFixType: iOS7SwiftGenericFixProtocol {}

class GenericClass<T> {
    var value: T?
    let attribute = 0
}

class GenericSubclass<Element: iOS7SwiftGenericFixProtocol>: GenericClass<Int> {
    let otherAttribute = 0
}

let _ = GenericSubclass<iOS7SwiftGenericFixType>()

A: With Xcode 7.3.1, the only problem with my generic class was that it was inheriting from NSObject. Removing the inheritance was enough, the order of property declaration didn't matter.


text:
Q: Input onchange checker if data exist in JSON data I have a user requirement when adding a form it should check if the name of the form is already exist. How can I do that in es6? I'm using AntDesign and ReactJS.
Here's my code
<Form.Item label="Form Name">
  {getFieldDecorator('formName', {
   rules: [formConfig],
  })(<Input name="formName" onChange={onChange} />)}
</Form.Item>

const handleChange = e => {
  const { name, value } = e.target;

   setState(() => ({
     ...state,
     [name]: value,
   }));

   let isExist = [...formDataSource];
    let foundExistItem = isExist.filter(
      item => item.formName === formName
    );
 };

A: If you want dynamically query the form fields, you should wrap your form with Form.create.
It injects useful functionalities like onFieldsChange listener:
const onFieldsChange = (_, changedFiels) => {
  const { username } = changedFiels;
  if (username) {
    // Make your API checks
    console.log(`Now changing ${username.name}`);
  }
};

const ValidatedFields = Form.create({ onFieldsChange })(App);

Note: You should keep your Form.Items uncontrolled using getFieldDecorator therefore avoiding onChange while collecting form data.
If you still insist to make form items controlled, you should use getFieldValue:
const handleChange = e => {
  const { name, value } = e.target;
  const { getFieldValue } = form;

  setState(() => ({
    ...state,
    [name]: value
  }));

  // or use getFieldValue for a single query
  const values = getFieldsValue(['formName',...more fields]);

  if (values.length) {
    // API CALL
  }
};


text:
Q: Draft Knowledge article not accessible via apex I have a user without "knowledge user" permission and he is able to access draft article via UI however when trying to access from a VF page , in debug logs we are getting error :-
System.QueryException: Insufficient access rights: you cannot access draft articles.
Checking "Knowledge user" will imply license usage which we want to avoid, also if salesforce is allowing article accessibility via UI then why not via Apex.
When I check "knowledge user" VF page works fine and does not give any error but why to check that if without checking for that user he can access article from UI.
Not sure what else I can try before expecting a response from someone here. Any suggestion will be appreciated.


text:
Q: Change v-text-field text position when a certain condition is met I am using vue js with vuetify. Came across an interesting scenario .
So i have three options (radio-buttons)

*

*Left

*Center

*Right

And i have a v-text-field with a certain text as value and readonly .
Now i want to change the position of that text inside v-text-field when option is changed/selected.
So for instance, upon option 1(left) text should be at moved at left inside v-text-field. Upon option 2(centre) text should be moved at center. And goes on.
Any suggestions for that. Also guide if you have a better approach

A: You can use class or style bindings from vue
data() {
  return {
    activeAlignment: 'center'
  }
}

And just bind activeAlignment to your radio buttons model

A: You can create classes and bind them:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    text: 'some text',
    align: ''
  })
})
.left .v-text-field__slot textarea, .left .v-text-field__slot input {
  text-align: left;
}
.center .v-text-field__slot textarea, .center .v-text-field__slot input {
  text-align: center;
}
.right .v-text-field__slot textarea, .right .v-text-field__slot input {
  text-align: right;
}
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@6.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">

  <v-app>
    <v-main>
      <v-container>
        <v-btn-toggle
          v-model="align"
          tile
          color="deep-purple accent-3"
          group
        >
          <v-btn value="left">Left</v-btn>
          <v-btn value="center">Center</v-btn>
          <v-btn value="right">Right</v-btn>
        </v-btn-toggle>
        <v-textarea
          :class="align"
          v-model="text"
          label="text"
        ></v-textarea>
        <v-text-field
          v-model="text"
          label="text"
          :class="align"
        ></v-text-field>
      </v-container>
    </v-main>
  </v-app>


text:
Q: JAVA SAX DefaultHandler startCDATA() not firing I am trying to parse and detect the start of the CDATA within a tag like:
<child><![CDATA[data goes here]]></child>
I have a class that extends the Default handler
class MyXmlDoc extends DefaultHandler{
with methods for startElement() and endElement() that fire correctly but the startCDATA() never fires. My characters() method picks up the 'data goes here' so it appears that the CDATA 'wrapper' is detected but ???
Thanks for any insight!

A: CDATA is a lexical event. Regular handlers (content handler, error handler) do not process these events. You need to set a lexical handler for your reader, if it supports having one. Lexical handler is a SAX2 extension so Java XMLReader uses setProperty method for setting it.
See: http://download.oracle.com/javase/6/docs/api/org/xml/sax/XMLReader.html#setProperty%28java.lang.String,%20java.lang.Object%29 and http://download.oracle.com/javase/6/docs/api/org/xml/sax/ext/LexicalHandler.html

A: Is your data getting escaped in there? how are you writing the xml doc?
This may help you:
How to output a CDATA section from a Sax XmlHandler
This is pretty verbose too:
http://www.coderanch.com/t/127987/XML/read-cdata-sax-parser


text:
Q: Google Play games Unity plugin error: "Invalid classname" I'm getting an error when I try to setup the Google Play Games in Unity.
Google Play Games plugin version: 0.10.12
I have two versions of a single game project. One is with Unity version 2019.4.15f1. Other is with 2021.3.2f1.
The new version has some changes and fixes to the game and different ads provider, so I can't just use the older version just for the Google Play Games plugin.
When I use this plugin with Unity version 2019, I am able to save the configuration, but when I use the same plugin with Unity version 2021, I keep getting this error:
Invalid classname: Object reference not set to an instance of an object

I tried downgrading to 0.9.53 but that causes the same issue in 2021, and I also tried upgrading to 0.11.01 which seems to save the configuration, but doesn't have the option to sign out of google play games which is necessary for me.

A: I also got that error but now I solved it.
Using Unity version "2020.3.23f1.
It will be okay.
If you do, the error comes out then reboot your computer.


text:
Q: clear my Flex Queries I just started learning Flex these days.. I just had one doubt: below is the code:
Main.mxml
 <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">

        <s:layout>

            <s:VerticalLayout paddingLeft="10" paddingTop="10"/>
        </s:layout>

        <fx:Style source="Styles.css" />

        <fx:Script>
            <![CDATA[
                import components.NameDisplay;

                import spark.skins.spark.DefaultComplexItemRenderer;
                import spark.skins.spark.DefaultItemRenderer;

                private function rendererFunction(item: Object): ClassFactory
                {
                    if(item is String)
                        return new ClassFactory(NameDisplay);
                    else
                        return new ClassFactory(DefaultComplexItemRenderer);
                }
            ]]>
        </fx:Script>

        <fx:Declarations>

            <s:ArrayList id="employeeList">
                <fx:String>Samuel Ang</fx:String>
                <s:BitmapImage source="images/sang.jpg"/>

                <fx:String>Athena Parker</fx:String>
                <s:BitmapImage source="images/aparker.jpg"/>

                <fx:String>Saul Tucker</fx:String>
                <s:BitmapImage source="images/stucker.jpg"/>

                <fx:String>Alyssa Le</fx:String>
                <s:BitmapImage source="images/ale.jpg"/>
            </s:ArrayList>

        </fx:Declarations>

        <s:Label text="Employee Portal: Employee Directory"
                 styleName="titleHeader"/>

        <s:DataGroup dataProvider="{employeeList}"
                     itemRendererFunction="rendererFunction">

            <s:layout>
                <s:VerticalLayout paddingLeft="15" paddingTop="15"/>
            </s:layout>

        </s:DataGroup>

    </s:Application>

NameDisplay.mxml
 <?xml version="1.0" encoding="utf-8"?>
    <s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
                    xmlns:s="library://ns.adobe.com/flex/spark"
                    xmlns:mx="library://ns.adobe.com/flex/mx"
                    autoDrawBackground="true">
        <fx:Declarations>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>

        <s:Label text="{data}"
                 width="74" height="30"
                 backgroundColor="#000000"
                 color="#FFFFFF"
                 textAlign="center"
                 verticalAlign="middle" />

    </s:ItemRenderer>

My Doubts:
1) How does my 'rendererFunction' code returns a ItemRenderer at end? I mean how does ClassFactory returns a ItemRenderer object? I checked ClassFactory.as code, I have seen newInstance() method (which was implemented from IFactory interface), so how does ClassFactory calls automatically newInstance() method (actually, iam guessing that iam getting ItemRenderer object via newInstance() method)
2) Inside DisplayName.mxml code: <s:Label text="{data}" , I found that this 'data' coming from DataRenderer.as , BUT i didnt understood how does it getting value, from where??
3) I heard from many people saying that Flex developed from Java, Is that correct? If yes, why I didnt found not even a single java file inside Flex Source code?
4) now Curretnly, Apache is owner of Flex, so then why does Flex API still showing as 'Adobe'? (asked this just to know myself)
Sorry, if they're stupid queries!
Waiting for replies!

A:
1) How does my 'rendererFunction' code returns a ItemRenderer at end?
  I mean how does ClassFactory returns a ItemRenderer object?

I'm not sure what your really asking here, but I'll try.  I believe it happens like this:
1) The DataGroup needs an itemRenderer to display some data
2) The DataGroup checks to see if an itemRendererFunction exists.  if it does; it calls the function.  The function returns a ClassFactory
3) The ClassFactory is used inside the DataGroup to create a new instance.  I would assume that the newInstance() method is called; but I am not reviewing the code to write this.
4) The DataGroup sets the data property on the new renderer instance.  I assume it also stores the renderer instance somewhere.
5) The renderer instance is added as a child of the DataGroup
At the end of the day; you'll have to delve into the Flex Framework code to figure out the answers to your questions.

2) Inside DisplayName.mxml code:

The DataGroup will set the data property on the renderer.  It relates to an item from the DataGroup's dataProvider.

3) I heard from many people saying that Flex developed from Java, Is
  that correct? If yes, why I didnt found not even a single java file
  inside Flex Source code?

The Flex compiler is built in Java.  The Flex Framework is all ActionScript.

4) now Curretnly, Apache is owner of Flex, so then why does Flex API
  still showing as 'Adobe'? (asked this just to know myself)

For backward compatibility reasons primarily.  I believe the Apache Flex SDK includes new classes which are not in an Adobe namespace.


text:
Q: Traveling salesman-like optimization problem - better heuristic required I have an optimization problem and I am looking for an algorithm that performs better than the naive method I have.
The problem
Consider a graph, G(N, E), where N is the set of nodes and E is the set of edges. Each node n_i in N has an associated state s_i. I've used a dictionary D to store this with nodes as keys and the corresponding state as the value. Adjacent nodes may swap states using a swap manouever. Specifically, a swap manouever is defined as
def swap(G, D, n_i, n_j):
    if n_i not in neighbors(G, n_j):
         print('Cannot swap between disconnected nodes')
    else:
         s_i = D[n_i]
         s_j = D[n_j]
         D[n_i] = s_j
         D[n_j] = s_i
    return D

Each state must now "visit" a list of other states in a given order, where visiting means both states must be on any pair of adjacent nodes on G(N, E). For example s_1 must visit [s_3, s_5, s_2], s_2 must visit [s_1, s_3], s_3 must visit [s_1, s_2, s_4] and so on. The order of visits must be preserved. However, states are allowed to be on adjacent nodes without marking that as a visit. For instance, if s_1 starts off adjacent to s_5, then it must first become adjacent to s_3, mark that visit as done and then become adjacent to s_5 again. The visitor lists are such that if s_i must visit s_j, then that also means that s_j must visit s_i i.e. everything is self-consistent.
Typical sizes
The graph is usually around 20-30 nodes, each node is typically connected to 2-4 others. The visit list has no length restriction in principle but in practice doesn't exceed 10.
The goal
The goal is to complete the list of visits while minimizing the total number of swap manouvers. What is an efficient algorithm/heuristic for this problem?
My naive solution
My current algorithm does the simplest thing one can do. I first see which vists are (0,0) visits according to the following function i.e. both states must visit each other before visiting anyone else.
def interaction_priority(s1, s2):
    if s2 in visitors_of_s1:
       b = visitors_of_s1.index(s2)
       a = visitors_of_s2.index(s1)
    return (a, b)

For these states, I get the current nodes and find the shortest path between those nodes on G using a networx function. I perform swaps till they are adjacent. Let us assume the previous function returned (0,0) for s_1 and s_3. Then I find the shortest path between the current nodes of s_1 and s_3
inv_D = {s : n for n, s in D.items()} #Invert the dictionary of nodes and states
def get_shortest_path(s1, s3):
    n1 = inv_D[s1]
    n3 = inv_D[s3]
    path_nodes = get_shortest_path(G, n1, n3)
    return path_nodes

Now, I perform swaps along this path
if len(path_nodes)> 0:
    for i in path_nodes:
         D = swap(G, D, n1, i)

visitors_of_s1.remove(s3)
visitors_of_s3.remove(s1)

I'm aware that I can probably optimize things a bit e.g. make the last method symmetric and so on but the fundamental idea is still not very clever. Is there a cleverer algorithm that optimizes how the states move about the graph but still complete all their visits.