text:
Q: How can I fix the issue of objects being stored twice in Django database? I am using the YouTube Data API to create an object, but when I create a single object, it creates two objects - one with the proper details and one that is blank. How can I resolve this issue?
before creating object

after creating single object

I am trying with the following code.
view.py
class VideoCreateView(CreateView):
    model = Video
    form_class = VideoForm
    template_name = "videos/video_form.html"
    def form_valid(self, form):
        video = Video()
        video.url = form.cleaned_data['url']
        parse = urllib.parse.urlparse(video.url)
        video_id = urllib.parse.parse_qs(parse.query).get('v')
        if video_id:
            video.youtube_id =video_id[0]
            response = requests.get(f'https://youtube.googleapis.com/youtube/v3/videos?part=snippet&id={video_id[0]}&key={YOUTUBE_API_KEY}')
            json = response.json()
            items = json["items"]
            assert len(items) <= 1
            if len(items):
                title = items[0]["snippet"]["title"]
                video.title = title
                video.save()
            else:
                title = "N/A"
        return super().form_valid(form)

models.py
class Video(models.Model):

    title = models.CharField(max_length=255)
    url = models.URLField()
    youtube_id = models.CharField(max_length=255)
    slug = models.SlugField(blank=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("videos:video_detail", kwargs={"slug":self.slug})

def video_pre_save_reciever(sender,instance,*args, **kwargs):
    if not instance.slug:
        instance.slug = unique_slug_generator(instance)

pre_save.connect(video_pre_save_reciever,Video)

if more code is require than tell me in comment , i will update my question with that information.

A: The view VideoCreateView inherits CreateView. CreateView inherits ModelFormMixin which defines form_valid method.
def form_valid(self, form):
    """If the form is valid, save the associated model."""
    self.object = form.save()
    return super().form_valid(form)

You save the video object and call the super form_valid which saves the form(in turn creating a model object) again. Hence, causing a double creation. I suggest modifying the form and passing it to super instead of manually saving it.
Another option is to inherit the View with django.views.generic.View. This would avoid form save.
I suggest you follow the first approach.

A: I have solve this my problem by removing all the form_valid code from the views and add that inside the model
class Video(models.Model):

    title = models.CharField(max_length=255)
    url = models.URLField()
    youtube_id = models.CharField(max_length=255)
    slug = models.SlugField(blank=True)

    def save(self,*args,**kwargs):

        parse = urllib.parse.urlparse(self.url)
        video_id = urllib.parse.parse_qs(parse.query).get('v')
        if video_id:
            self.youtube_id =video_id[0]
            response = requests.get(f'https://youtube.googleapis.com/youtube/v3/videos?part=snippet&id={video_id[0]}&key={YOUTUBE_API_KEY}')
            json = response.json()
            title = json["items"][0]["snippet"]["title"]
            self.title = title
        super(Video,self).save(*args,**kwargs)


text:
Q: Colors for Python (seaborn): colors without adding to DataFrame slov = {'People': {0: 'Ivan', 1: 'John', 2: 'Peter', 3: 'Ming'}, 'Country':{0: 'Russia', 1: 'USA', 2: 'USA', 3: 'China'},\
    'Height': {0: 181, 1: 175, 2: 174, 3: 173}}

I'd like to see this picture

But I don't know how to do it. I mean I want to have a red color for Russian people, Green color for USA people and yellow color for Chines.
My attemp to find solution:
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
sns.set(style="white")

slov = {'People': {0: 'Ivan', 1: 'John', 2: 'Peter', 3: 'Ming'}, 'Country':{0: 'Russia', 1: 'USA', 2: 'USA', 3: 'China'},\
'Height': {0: 181, 1: 175, 2: 174, 3: 173}}

obj = pd.DataFrame(slov)

palette=["g", "b", "r"]
obj['Color']='r'

row_index = obj.Country == 'Russia'
obj.loc[row_index, 'Color'] = 'r'

row_index = obj.Country == 'USA'
obj.loc[row_index, 'Color'] = 'g'

row_index = obj.Country == 'China'
obj.loc[row_index, 'Color'] = 'y'

g = sns.factorplot(x="People", y="Height",  data=obj, kind='bar', palette=obj['Color'])

plt.show()

And maybe my solution is not very good. I added color to DataFrame. Maybe we can write this better. Maybe I don't need to add color to my DataFrame (It seems not very correct.). But How can I solve my task without adding these colors to my DataFrame?

A: You can use map by dict:
d = {'Russia':'r', 'USA':'g','China':'y'}
g = sns.factorplot(x="People",
                   y="Height",
                   data=obj,
                   kind='bar',
                   palette=obj['Country'].map(d))

plt.show()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error on an IF function format SQL: Error Not Supported BOOL, STRING, BOOL, only IF(BOOL, ANY, ANY) I'm trying to write an IF statement in SQL, and it's throwing an error about the supported format

SQL_ANALYSIS_ERROR: No matching signature for function IF for argument types: BOOL, BOOL, STRING. Supported signature: IF(BOOL, ANY, ANY)

Code:  IF(field1 = 'string_1', field2 , 'string_2') AS field_name
This should meet the requirement of BOOL, ANY, ANY....but for whatever reason it's not. Anyone have suggestions? Or am I missing something?

A: I think with you confuse. the function is IIF.
EX:
SELECT IIF('string_1' = 'string_1', 'OK' , 'string_2')
https://learn.microsoft.com/en-us/sql/t-sql/functions/logical-functions-iif-transact-sql?view=sql-server-ver15

A: The SQL standard for conditional logic is CASE:
(CASE WHEN field1 = 'string_1' THEN field2 ELSE 'string_2' END) AS field_name

I recommend this over bespoke functions such as if.
In this case, the problem is that field2 is BOOLEAN, so it needs to be converted.  BigQuery requires explicit conversion in most cases, so:
(CASE WHEN field1 = 'string_1' THEN CAST(field2 AS STRING) ELSE 'string_2' END) AS field_name


text:
Q: while (sqlite3_step(statement)==SQLITE_ROW) its not executed and not entered in loop? I am creating Address book. its save group name in sqlite. but its not working. its not entering in loop.?  please check my code. what is the problem in my code?
-(void) selectGroup
{
ssArray = [[NSMutableArray alloc]init];

NSString *selectStmt=[NSString stringWithFormat:@"select GroupName from AddGroup;"];

NSLog(@"the selet statement is :%@",selectStmt);

const char *cSelectStmt=[selectStmt UTF8String];

sqlite3_prepare_v2(database, cSelectStmt, -1, &statement, NULL);

while (sqlite3_step(statement)==SQLITE_ROW) {

    const unsigned char *cName = sqlite3_column_text(statement, 0);

    NSString *name=[NSString stringWithUTF8String:(const char *)cName];

    [self.ssArray addObject:name];
}
sqlite3_finalize(statement);

NSLog(@"Array from database is  :%@",ssArray);
}


text:
Q: How to configure pfsense to use LAN ports as local switched ports? I have a pfsense box with 6 LAN ports. I'd like to use one as the WAN port, and 5 as local LAN ports, just like a home gateway/router.  How to setup the LAN ports so that they are all in the same subnet?  It seems that the bridging function only wants to bridge between WAN and LAN?

A: Three major steps are required for this:
1) Assign and enable all the additional interfaces. These will show up by default as OPTn interfaces. You can rename them to whatever you like (maybe LANn instead?) - just be sure to enable them as well. Here is a screenshot of my interfaces:

2) Create a new bridge that has the original LAN interfaces and all of the LANn as members.

3) Add a firewall rule to allow traffic across each interface of the bridge. I would suggest starting with a rule like "Protocol: any, Source: LAN subnet, Destination: LAN subnet". Depending on your needs you may also want to add a rule to allow internet access as well.


text:
Q: Combing two lists from regex using Python I am using regular expression to grab values from a log file using python. The code is as follows:
with open(logFile, 'r') as logfile_read:
    for line in logfile_read:
        line = line.rstrip()
            if 'Time' in line:
            iteration_time = re.findall(r'^Time = ([0-9]+)', line)

            if 'cumulative' in line:
                contCumulative_0 = re.search(r'cumulative = (-?[\d|.]+)', line)
               if contCumulative_0:
                  cumvalue = contCumulative_0.groups(1)
               merge = zip(iteration_time, cumvalue)
               print merge

The output with the above code is:
[('1', '0.00142109')]
[('2', '0.00354587')]
[('3', '0.00166678')]
[('4', '-0.00477095')]
[('5', '-0.00814067')]
[('6', '-0.00854863')]
[('7', '-0.00710546')]
[('8', '-0.00715775')]
[('9', '-0.00580527')]
[('10', '-0.0061622')]

I would like the output to be as below so that I can write to a file and plot it.
1   0.00142109
2   0.00354587
3   0.00166678

and so on. I am struggling converting the above tuple to strings.

A: Add an extra for loop.
>>> l = [('1', '0.00142109')]
>>> for (x,y) in l:
...     print(x,y)
...
1 0.00142109

OR
>>> for (x,y) in l:
...     print(x+"\t"+y)
...
1   0.00142109

A: use join and map as below:
merge = ' '.join(map(double,merge[0]))

as you are writing to file, converting to double is optional:
merge = ' '.join(merge[0])

A: You'll want to use Python's .join() function to join a list/tuple of strings. For example:
>>> tup = ('1', '0.00142109')
>>> print '\t'.join(tup)
1   0.00142109


text:
Q: Obtener propiedad de un objeto dentro de un array de objetos en Javascript Tengo el siguiente json

lo converti a array con Object.values(this.ArrayUserAuth);
y quedo de esta manera↓
ArrayUserAuth = [
0:{avatar
:
"https://reqres.in/img/faces/2-image.jpg"
email
:
"janet.weaver@reqres.in"
first_name
:
"Janet"
id
:
2
last_name
:
"Weaver"},

1:{
text: "To keep ReqRes free, contributions towards server costs are appreciated!"
url:
"https://reqres.in/#support-heading"}
]

Necesito acceder solo al objeto 0 y a el valor de la propiedad email.
Intenté con for each o en template con *ngFor pero nada.
o puedo acceder desde el json original a dicho valor?

A: Si deseas entrar al mismo por su propiedad en un objeto quedaría de la siguiente manera:

UserAuth = {
  0: {
    avatar: "https://reqres.in/img/faces/2-image.jpg",
    email: "janet.weaver@reqres.in",
    first_name: "Janet",
    id: 2,
    last_name: "Weaver",
  },
  1: {
    text: "To keep ReqRes free, contributions towards server costs are appreciated!",
    url: "https://reqres.in/#support-heading",
  },
};

console.log(UserAuth[0].email)
//Se usa bracket notation para acceder al objeto por ser un numero la clave en este caso.

Otra opción podría ser tener un array e ingresar por su posición, entonces quedaría de la siguiente manera:

const ArrayUserAuth = [
  {
    avatar: "https://reqres.in/img/faces/2-image.jpg",
    email: "janet.weaver@reqres.in",
    first_name: "Janet",
    id: 2,
    last_name: "Weaver",
  },

  {
    text: "To keep ReqRes free, contributions towards server costs are appreciated!",
    url: "https://reqres.in/#support-heading",
  },
];

console.log(ArrayUserAuth[0].email)

A: Podrías almacenar los objetos en una constante y luego acceder a ella:

// Definimos al objeto en una constante.
const ArrayUserAuth = {
  0: {
    avatar: 'https://reqres.in/img/faces/2-image.jpg',
    email: 'janet.weaver@reqres.in',
    first_name: 'Janet',
    id: 2,
    last_name: 'Weaver',
  },

  1: {
    text: 'To keep ReqRes free, contributions towards server costs are appreciated!',
    url: 'https://reqres.in/#support-heading',
  },
};

// Ingresamos al objeto, de la posición 0, la propiedad email.
console.log(ArrayUserAuth[0].email)


text:
Q: Proof of a change of variables formula in integrals The proof of following version of the Change of Variables Theorem in Integrals is not difficult:
"Let $\phi\colon [a,b]\to [\phi(a),\phi(b)]$ be a differentiable function such that $\phi'$ is integrable and $\phi(a)< \phi(b)$ and $f\colon [\phi(a),\phi(b)]\to\mathbb{R}$ be continuous on $[\phi(a),\phi(b)]$; then $(f\circ \phi)\phi '$ is integrable on $[a,b]$ and $\int_{[a,b]}(f\circ \phi)\phi'=\int_{[\phi(a),\phi(b)]}f$"
but I'm curious about the proof of the following version, where $f$ is assumed to be just integrable and not continuous:
"$\phi:[a,b]\to [\phi(a),\phi(b)]$ differentiable monotone increasing function such that $\phi '$ is Riemann integrable; $\ f\colon [\phi(a),\phi(b)]\to\mathbb{R}$  Riemann integrable function on $[\phi(a),\phi(b)]$. Then $(f\circ\phi)\phi '\colon [a,b]\to\mathbb{R}$ is Riemann integrable on $[a,b]$, and $\int_{[a,b]}(f\circ\phi)\phi '=\int_{[\phi(a),\phi(b)]}f.$".
I read this last version on a real analysis book where the proof of this is given as a corollary of other theorems whose proofs span several pages and involve also the notion of Riemann-Stieltjes integral, so I'm wondering: does anyone know of a more elementary (i.e. not involving the notion of Riemann-Stieltjes integral but just the "usual" properties/theorems of Riemann integration)/shorter/etc. proof of this last theorem?


text:
Q: Any benefits when constraining views both ways? Im new to using constraintlayouts and i was wondering why sometimes i see people constraining their views both ways and some don't.
What is the purpose and are there any benefits?
app:layout_constraintBottom_toTopOf="@id/permissions_storage"/>

app:layout_constraintTop_toBottomOf="@id/permissions_state_info"/>

My code
<TextView
        android:id="@+id/permissions_state_info"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:fontFamily="@font/archivo_narrow"
        android:text="@string/permission_state_info"
        android:textColor="@color/white"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/permissions_state"
        app:layout_constraintBottom_toTopOf="@id/permissions_storage"/>

    <TextView
        android:id="@+id/permissions_storage"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:fontFamily="@font/archivo_narrow"
        android:text="@string/permission_storage"
        android:textColor="@color/white"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/permissions_state_info"/>

A: It depends on the individual layout and what the constraints for that view need to be.
For example if you need a view contrained to just the top then you could
`constraintTop_toTopOf="parent" (and same goes for the bottom)
But if you need the live vertically between 2 views then you set the constraints accordingly (top to bottom of one above, bottom to top of one below).

A: It will always constraints the current view between the mentioned views.


text:
Q: PHP Form Only Updates Bottom Input for MySQL DataBase Table I'm having a problem with my PHP Form that is supposed to update my MySQL Database Table's column for a person's age. The column is called Age. The problem I am getting is when I try to update an age it will not update and displays
UPDATE Persons SET Age=Array WHERE FirstName ='Array'
array(13) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" [3]=> string(0) "" [4]=> string(0) "" [5]=> string(0) "" [6]=> string(0) "" [7]=> string(0) "" [8]=> string(0) "" [9]=> string(0) "" [10]=> string(0) "" [11]=> string(0) "" [12]=> string(3) "544" } Cannot update

on the bottom of my page. You can view my page at http://thetotempole.ca/phptester/editpage.php
All the code for my page:
<?php
    $hostname = "";//host name
    $dbname = "";//database name
    $username = "";//username you use to login to php my admin
    $password = "";//password you use to login

    //CONNECTION OBJECT
    //This Keeps the Connection to the Databade
    $conn = new MySQLi($hostname, $username, $password, $dbname) or die('Can not connect to database')
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>

<?php

//$id=$_GET['FirstName'];

//Create a query
$sql = "SELECT * FROM Persons";
//submit the query and capture the result
$result = $conn->query($sql) or die(mysql_error());
$query=getenv(QUERY_STRING);
parse_str($query);
?>

Update Record <?php echo $sql;?>

Click Here to see the Table Data
<?php $counter = 0; ?>
<form action="" method="post">
<?php

while ($row = $result->fetch_assoc()) {?>

Age:
<?php echo $row['Age'][$counter];?>
<?php echo $row['FirstName'];?>
<input type="text" name="Age[]">
<input type="text" name="FirstName[]" value="<?php echo $row['FirstName'];?>" />

<INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit">

<?php
$counter++;   }
?>
</form>

<?php
if(isset($_POST['Submit'])){//if the submit button is clicked
$age = $_POST['Age'];
$id = $_POST['FirstName'];

$sql="UPDATE Persons SET Age=$age WHERE FirstName ='$id'";
echo $sql."
";
var_dump($_POST[Age]);
$conn->query($sql) or die("Cannot update");//update or error
}
?>

I updated the code to my current code.

A: You can use arrays:
<input type="text" name="person[<?php echo $row['FirstName'];?>]">

and:
if(isset($_POST['Submit']))
foreach ($_POST['person'] as $id => $age)
{
  $sql="UPDATE Persons SET Age='".$age."' WHERE firstname ='".$id."'";
  $conn->query($sql) or die("Cannot update");//update or error
}

Also, don't forget mysql string escaping and html entities in FirstName in form input name.

A: Here are the contents of that phpfiddle for easier access:
<?php
if(isset($_POST['Submit'])){ //if ANY submit button has been clicked
    if (is_numeric($_POST['Age'])) {
        $age = (int) $_POST['Age'];
    } elseif ($age == '') {
        $age = (string) 'NULL';
        die('Please go back and enter a valid age.');
    } else {
        die('Please go back and enter a valid age.');
    }
    $id = mysqli_real_escape_string($conn,$_POST['FirstName']);
    $sql="UPDATE Persons SET Age=$age WHERE FirstName ='$id'";
    $conn->query($sql) or die("Cannot update"); //update or error
}
$sql="SELECT * FROM Persons";
$conn->query($sql) or die("Cannot update"); //update or error
while ($row = $result->fetch_assoc()){
    $age = (int) $row['Age'];
    $id = mysqli_real_escape_string($conn,$row['FirstName']);
?>
    <form action="" method="post">

                Age:
                <?php echo $age;?>
                <?php echo $id;?>
                <input type="text" name="Age">
                <input type="text" name="FirstName" value="<?php echo $id;?>"><?php echo $id;?></input>

                <INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit">

    </form>
<?php
}
?>

if your variable is numeric, then you don't need single quotes for the update statement.  I only corrected Age because I'm not sure about firstname.  Also, PHP doesn't require concatenation of variables into strings surrounded by double quotes.
Hope this helps.
Edit: When you do escape your strings, be sure to use the mysqli version of the function rather than mysql as the latter is deprecated.


text:
Q: Python subprocess exhibits different behavior in command line and GUI console while streaming ouput I am using subprocess of python27 lib to run a big python file(execute.py) from another python file(sample.py).
If I run the sample.py (which has subprocess statements) in windows command line,it is running properly and streaming the live output well.
But in the python GUI console,when I run the GUI python file(has same subprocess statements) the GUI window is Not responding for some minutes after some time the output is printing as whole(not streaming).
Here is the snippet:
cmdlist = ["python", "execute.py","name","xyz"]
proc = subprocess.Popen(cmdlist, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

for line in iter(proc.stdout.readline, ""):
        self.output.write(line)

self.output.write("\n Finished process\n")

Hitting my head for a week and could not find any solution so far.

A: When you run script in command line: the output will send directly to the terminal.
The Python GUI console(IDLE) base on tkinter tool kit so when you run the script:
the output will send to the buffer. The GUI tool take a bit of time to show the buffer to screen. Therefore the time to show the output will be longer when running with command line. If your script print too much, the buffer will be overflow then the "Not responding" occurs.

A: Do not set stdout or stderr if you want them to go to an outer (controlling) process.
cmdlist = ["python", "execute.py","name","xyz"]
proc = subprocess.Popen(cmdlist)
# do other stuff here if you like
self.output.write(
  "\n Finished process (%s)\n" % proc.wait()  # wait until process has finished; process will stream to stdout/stderr while we wait
)

If you set stdout or stderr to subprocess.PIPE your current (python) process creates a new pipe by which it communicates with the subprocess. Basically, your own process will buffer the subprocess' output.
Even if you don't explicitly buffer anything, python itself will do some buffering. This especially applies when you redirect stderr and write it to your own stdout - stdout is buffered by default, while stderr would not have been. Many programs also write to the same line and reset the cursor, thus doing proc.stdout.readline() will buffer, waiting for the line to finish.
Now, if you don't set stdout and stderr, the subprocess will inherit your stdout and stderr. This means it can write directly to the outer, controlling process.


text:
Q: Change url of a webpage on a local network I built a webpage on an ESP32 chip, charged to create an access point allowing my computer to connect in order to access this page.
For the moment I can only access it using the IP of my ESP by typing it in a browser but it can be very bothersome.
I'd like to know if it was possible to change the url of the page using words instead of the ESP's IP.
Maybe I'm missing some technical terms but I didn't find any solution on the internet.
PS: I'm using micropython with sockets to serve html files from the board:
def handleClient(client_socket):
    headers, data = loadRequest(client_socket.recv(1024).decode('utf-8'))
    # print('[*] Received:\n%s\n%s\n' % (headers, data))
    if headers['method'] == 'GET' and '/connect' == headers['route']:#'/connect' in headers['route']:
        ssid, password, status, code = connect(headers)
        client_socket.sendall(RESPONSE_TEMPLATE % (code, status, {'ssid': ssid, 'password': password}, code))
        return ssid, password
    elif headers['method'] == 'GET' and headers['route'] == '/':
        renderWebPage(client_socket)
    client_socket.close()
    return None, None

A: there are two parts needed to solve your Q:

*

*publish a name (using mdns)

*resolve that name from a client

MicroPython has built-in support for mdns since v1.12.
The essential code is to assign a hostname using the below:
wlan.config(dhcp_hostname="prettyname")

Note that your client also needs to have mdns support in order to be able to resolve that address. That may/will depend on your client.
a complete sample would be:
import network
wlan = network.WLAN(network.STA_IF)
if not wlan.isconnected():
    wlan.active(True)
    mac = wlan.config('mac')
    host = "prettyname"
    wlan.config(dhcp_hostname = host)
    wlan.connect('myssid', 'mypassword')
    while not wlan.isconnected():
        pass

host = wlan.config('dhcp_hostname')
print('Wifi connected as {}/{}, net={}, gw={}, dns={}'.format(
    host, *wlan.ifconfig()))

Source: MicroPython Forum

A: Certainly. The easiest option is enabling mDNS. This allows hosts in the same local network to resolve the device's name (e.g. espressif.local) into its IP. Only works in local network and requires an mDNS client on the computer (Mac, Linux and Windows all tend to have it built in these days).
No idea how to do it in Micropython, though. Give Google a try.


text:
Q: JQuery ui dialog css problem under Firefox I got a job : There is a website, that is contains some ExtJ functions. I have to change these to JQuery functions.
I'm started to change dialogs. Under IE8 / IE7 it works fine, but under FF 3.5.10 it's not perfect.
The code I'm using is :

Kérjük adja meg az e-mail címét:

  <form>
      <fieldset>
        E-mail:
        <input type="text" name="dialog_lostpassword_email" id="dialog_lostpassword_email" value="" class="text ui-widget-content ui-corner-all" />
      </fieldset>

        Ha Ön még nem rendelkezik hozzáféréssel, itt regisztrálhat!
        Elfelejtette jelszavát? Ide kattintva igényelhet újat!

    </form>

The Javascript:
function showLostPasswordWindow() {
    $('#dialog-lostpassword').dialog('open');
};

$(function () {
    $("#dialog").dialog("destroy");

    var dialog_lostpassword_email = $("#dialog_lostpassword_email"),
        allFields = $([]).add(dialog_lostpassword_email),
        tips = $(".validateTips");

    function updateTips(t) {
        tips
            .text(t)
            .addClass('ui-state-highlight');
        setTimeout(function() {
            tips.removeClass('ui-state-highlight', 1500);
        }, 500);
    }

    function checkLength(o,n,min,max) {

        if ( o.val().length > max || o.val().length < min ) {
            o.addClass('ui-state-error');
            updateTips("Az e-mail cím hossza " + min + " és " + max + " között kell legyen" + ".");
            return false;
        } else {
            return true;
        }

    }

    function checkRegexp(o,regexp,n) {

        if ( !( regexp.test( o.val() ) ) ) {
            o.addClass('ui-state-error');
            updateTips(n);
            return false;
        } else {
            return true;
        }

    }

    $("#dialog-lostpassword").dialog({
        autoOpen: false,
        height: 250,
        width: 380,
        modal: true,
        buttons: {
            'Küldés': function() {
                var bValid = true;
                allFields.removeClass('ui-state-error');

                bValid = bValid && checkLength(dialog_lostpassword_email,"",6,80);
                bValid = bValid && checkRegexp(dialog_lostpassword_email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"Hibás az e-mail cím formátuma.");

                if (bValid) {
                    // ha 'Küldés' gombra kattintotunk és valid minden
                    $(this).dialog('close');
                }
            },
            'Mégsem': function() {
                $(this).dialog('close');
            }
        },
        close: function() {
            allFields.val('').removeClass('ui-state-error');
        }
    });
});

The problem is :
In FF when I call showLostPasswordWindow() function the dialog shows up, but it is empty, doesn't contains the input field and the texts. Input field and texts are in the background, they are part of the main site (they are at the top of the page).

A: Hmm...you could try using Firebug console to check for js console errors, and also to look at the markup and see what's going on.


text:
Q: $x(t)=e^{j\cdot 2\pi \cdot10t}-je^{j\cdot 2\pi \cdot 40t}= $?? I'm just wondering how I would go about getting the real and imaginary parts of
$$
x(t) = e^{j\cdot 2\pi \cdot10t}-je^{j\cdot 2\pi \cdot 40t}.
$$
How does the real part come out to be $\cos(2\pi 10t)+\sin(2\pi \cdot 40t)$ and the imaginary to be $\sin(2\pi 10t)-\cos(2\pi \cdot 40t)$

A: You should use Euler's rule
$$
\mathrm{e}^{jx} = \cos x + j \sin x
$$
you can then expand each term with the $j^2 = -1$
$$
\mathrm{e}^{jax} - j\mathrm{e}^{jbx} = \cos(ax) + j \sin(ax) -j(\cos (bx) + j \sin(bx)) = \cos(ax) - j^2\sin(bx) + j(\sin(ax) - \cos(bx))
$$
or
$$
\mathrm{e}^{jax} - j\mathrm{e}^{jbx} =\cos(ax) + \sin(bx) + j(\sin(ax) - \cos(bx))
$$


text:
Q: Are the argument passing semantics for methods on structs purely determined by the method and not by the caller? Consider the following simple program, where we define a method on a pointer to the struct Vertex and then invoke it with a pointer.
package main

import (
    "fmt"
)

type Vertex struct {
    X, Y float64
}

func (v *Vertex) Mutate()  {
    v.X = 8
}

func main() {
    v := &Vertex{3, 4}
    v.Mutate()
    fmt.Println(v.X)
}

The output of this program is 8, which we expect because we are passing a pointer to a method which takes a pointer.
However, the following invocation also has an output of 8.
func main() {
    v := Vertex{3, 4}
    v.Mutate()
    fmt.Println(v.X)
}

Symmetrically, if we redefine the method Mutate to take a Vertex instead of a pointer, then the mutation fails regardless of whether a pointer or a struct is passed.
This behavior seems to imply that whether the argument v or a pointer to v to passed depends entirely on the definition of the method, rather than on what is actually being passed.
Is this a correct interpretation, and will this always be the case? If not, what is the correct explanation for this behavior?

A:
This behavior seems to imply that whether the argument v or a pointer to v to passed depends entirely on the definition of the method, rather than on what is actually being passed.
Is this a correct interpretation, and will this always be the case? If not, what is the correct explanation for this behavior?

No, this is not correct but it is almost correct.
What gets passed to your method is a pointer, even if it looks like v.Mutate() with v a non-pointer. The reason is: Your v is "addressable" and thus its method set includes methods on the pointer type. See http://golang.org/ref/spec#Calls for details. This is a kind of syntactic sugar. Because v is addressable you may take its address &v and on this pointer you may invoke your method like (&v).Mutate. This syntax is clumsy and Go automatically does it for you for addressable expressions.
(If you are interested in such stuff, why not read the whole language specification? It can be done in 3 hours.)


text:
Q: cublasSgemmBatched usage with jcuda I've been trying to use cublasSgemmBatched() function in jcuda for matrix multiplication and I'm not sure how to properly handle pointer passing and vectors of batched matrices. I will be really thankful if someone knows how to modify my code to properly handle this problem. In this example, C array stays unchanged after cublasGetVector.
public static void SsmmBatchJCublas(int m, int n, int k, float A[], float B[]){

    // Create a CUBLAS handle
    cublasHandle handle = new cublasHandle();
    cublasCreate(handle);

    // Allocate memory on the device
    Pointer d_A = new Pointer();
    Pointer d_B = new Pointer();
    Pointer d_C = new Pointer();

    cudaMalloc(d_A, m*k * Sizeof.FLOAT);
    cudaMalloc(d_B, n*k * Sizeof.FLOAT);
    cudaMalloc(d_C, m*n * Sizeof.FLOAT);

    float[] C = new float[m*n];
    // Copy the memory from the host to the device
    cublasSetVector(m*k, Sizeof.FLOAT, Pointer.to(A), 1, d_A, 1);
    cublasSetVector(n*k, Sizeof.FLOAT, Pointer.to(B), 1, d_B, 1);
    cublasSetVector(m*n, Sizeof.FLOAT, Pointer.to(C), 1, d_C, 1);

    Pointer[] Aarray = new Pointer[]{d_A};
    Pointer AarrayPtr = Pointer.to(Aarray);
    Pointer[] Barray = new Pointer[]{d_B};
    Pointer BarrayPtr = Pointer.to(Barray);
    Pointer[] Carray = new Pointer[]{d_C};
    Pointer CarrayPtr = Pointer.to(Carray);

    // Execute sgemm
    Pointer pAlpha = Pointer.to(new float[]{1});
    Pointer pBeta = Pointer.to(new float[]{0});

    cublasSgemmBatched(handle, CUBLAS_OP_N, CUBLAS_OP_N, m, n, k, pAlpha, AarrayPtr, Aarray.length, BarrayPtr, Barray.length, pBeta, CarrayPtr, Carray.length, Aarray.length);
    // Copy the result from the device to the host
    cublasGetVector(m*n, Sizeof.FLOAT, d_C, 1, Pointer.to(C), 1);

    // Clean up
    cudaFree(d_A);
    cudaFree(d_B);
    cudaFree(d_C);
    cublasDestroy(handle);
}

A: I asked on official jcuda forum and quickly received the answer here.


text:
Q: convert Anonymous objets to JSON object Sorry if this has been asked already, suppose I have an anonymous list of objects like this:
   Collection = new List<object>() {
    new {
        FirstSetting    =  new
        {
            FirstKEy = "Property vs Inspections",
            color = "#FF6384",
            fontStyle = "Arial",
            sidePadding = 10,
        }
    },
    new {
        AnotherSettings =  new
        {
            text = "another text",
            color = "#FF6384",
            fontStyle = "Arial",
            sidePadding = 10,
        }
    }
};

and would like to convert to a JSON string using
JsonConvert.SerializeObject(Collection, JsonSerializerSettings);
I get this result.
[{
    "FirstSetting": {
        "FirstKey": "Property vs Inspections",
        "color": "#FF6384",
        "fontStyle": "Arial",
        "sidePadding": 10
    }
}, {
    "anotherSettings": {
        "text": "another text",
        "color": "#FF6384",
        "fontStyle": "Arial",
        "sidePadding": 10
    }
}]

but I do not wish to have an array. I'd like to have each settings to be an object something like this.
{
    "FirstSetting": {
        "FirstKey": "Property vs Inspections",
        "color": "#FF6384",
        "fontStyle": "Arial",
        "sidePadding": 10
    },
    "anotherSettings": {
        "text": "another text",
        "color": "#FF6384",
        "fontStyle": "Arial",
        "sidePadding": 10
    }
}

could someone shed some light please?

A: Not that's it's any better but if anyone finds it useful you can use a dictionary for this also. It's still clean code and it removes the first object 'Result' from the list. I sort of find it cleaner but that's preference.
var collection = new Dictionary<object, object>()
{
    ["FirstSetting"] = new
    {
        FirstKEy = "Property vs Inspections",
        color = "#FF6384",
        fontStyle = "Arial",
        sidePadding = 10,
    },
    ["AnotherSettings"] = new
    {
        text = "another text",
        color = "#FF6384",
        fontStyle = "Arial",
        sidePadding = 10,
    }
};

var jsonString = JsonConvert.SerializeObject(collection);

It outputs to:
{
    "FirstSetting":
    {
        "FirstKEy":"Property vs Inspections",
        "color":"#FF6384",
        "fontStyle":"Arial",
        "sidePadding":10
    },
    "AnotherSettings":
    {
        "text":"another text",
        "color":"#FF6384",
        "fontStyle":"Arial",
        "sidePadding":10
    }
}

A: For that you need to construct another anonymous object in that way to get the desired json.
If you serialize the collection then it will obviously be converted to array in json :
var obj = new
    {
        Result = new
        {
            FirstSetting = new
            {
                FirstKEy = "Property vs Inspections", color = "#FF6384", fontStyle = "Arial", sidePadding = 10
            },
            AnotherSettings = new
            {
                text = "another text", color = "#FF6384", fontStyle = "Arial", sidePadding = 10
            }
        }
    };

The json generated would be :
{
   "Result":{
      "FirstSetting":{
         "FirstKey":"Property vs Inspections",
         "color":"#FF6384",
         "fontStyle":"Arial",
         "sidePadding":10
      },
      "anotherSettings":{
         "text":"another text",
         "color":"#FF6384",
         "fontStyle":"Arial",
         "sidePadding":10
      }
   }
}

A: To follow up on the answer Ehsan Sajjad. Putting it in an object makes it a bit more readable I think.
Object mySettings = new {
    FirstSetting = new {
            FirstKEy = "Property vs Inspections",
            color = "#FF6384",
            fontStyle = "Arial",
            sidePadding = 10,
    },
    AnotherSettings = new {
        text = "another text",
        color = "#FF6384",
        fontStyle = "Arial",
        sidePadding = 10,
    }
};

The above might give you the desired result.


text:
Q: Add New column not containing value in previous column I've seen several solutions to this, but for some reason I just cant get this working.
I have data that looks like this.
data = {'Col1': ['Apples', 'Bananna, Pear', 'Suns, Moons, Stars', 'Orange, Blue, Green']}
df = pd.DataFrame(data)

                  Col1                 Col2
0               Apples               Apples
1        Bananna, Pear        Bananna, Pear
2   Suns, Moons, Stars   Suns, Moons, Stars
3  Orange, Blue, Green  Orange, Blue, Green

And I would like it to look like this.
EDIT:  Explain logic of col2
The goal is that if col1 does not have a comma in it (,) then I'd like to add that value to col2.  Eventually, I'll fill in the None values down with what is in col2
goal_data = {'Col1': ['Apples', 'Bananna, Pear', 'Suns, Moons, Stars', 'Orange, Blue, Green'],
             'Col2': ['Apples', None, None, None]}

goal_df = pd.DataFrame(goal_data)
                 Col1    Col2
0               Apples  Apples
1        Bananna, Pear    None
2   Suns, Moons, Stars    None
3  Orange, Blue, Green    None

I've tried a few variations of this for loop
for i in df['Col1']:
    if ',' in i:
        None
    else:
        df['Col2'] = df['Col1']

But I keep running into issues where the entire 'col1' is either copied, or everything in col2 is set to None or Apples.
In my actual data, I have thousands of rows that repeats this pattern.  When I run different versions of this, it will usually set col2 to whatever the last col1 value was that did not have a comma in it.

A: Let's try:
f = lambda x: None if ',' in x else x

df['Col2'] = df['Col1'].apply(f, axis=1)


text:
Q: How do I replace part of string with various combinations in lookup in Python? I have the following code replacing every element with it's short form in the lookup:
case = ["MY_FIRST_RODEO"]
lookup = {'MY': 'M', 'FIRST': 'FRST', 'RODEO' : 'RD', 'FIRST_RODEO': 'FRD', 'MY_FIRST': 'MF', 'MY_FIRST_RODEO': 'MFR'}
case_mod = []
for string in case:
    words = string.split("_")
    new_string = [lookup[word] for word in words]
    case_mod.append("_".join(new_string))
print(case_mod)

This returns:
['M_FRST_RD']

However, I want it to additionally return all possibilities since in the lookup, I have short words for all MY_FIRST, FIRST_RODEO, and MY_FIRST_RODEO. So, I want the following returned:
['M_FRST_RD', 'MF_RD', 'M_FRD', 'MFR']

I was able to write code to break the original list into all possibilities as follows:
case = ["MY_FIRST_RODEO"]
result = []
for string in case:
    words = string.split("_")
    n = len(words)
    for i in range(n):
        result.append("_".join(words[:i + 1]))
        for j in range(i + 1, n):
            result.append("_".join(words[i:j + 1]))
            result.extend(words)
result = list(dict.fromkeys(result))
print(result)

to return:
['MY', 'MY_FIRST', 'FIRST', 'RODEO', 'MY_FIRST_RODEO', 'FIRST_RODEO']

But somehow can't make the connection between the two solutions. Any help will be greatly appreciated.

A: One thing you could try is the following:
from itertools import combinations

string = "MY_FIRST_RODEO"
lookup = {'MY': 'M', 'FIRST': 'FRST', 'RODEO' : 'RD', 'FIRST_RODEO': 'FRD', 'MY_FIRST': 'MF', 'MY_FIRST_RODEO': 'MFR'}

underscores = [i for i, c in enumerate(string) if c == "_"]
length = len(string)
results = []
for r in range(len(underscores), -1, -1):
    for parts in combinations(underscores, r):
        limits = ((a + 1, b) for a, b in zip((-1,) + parts, parts + (length,)))
        results.append("_".join(lookup[string[a:b]] for a, b in limits))

First record the indices of string with an underscore and then use them  with combinations (from the standard library module itertools) to choose all the different partitions of string along the underscores. (I've left out the outer loop over case since that is not needed to show the proposed mechanic.)
Result here:
['M_FRST_RD', 'M_FRD', 'MF_RD', 'MFR']


text:
Q: GROUP BY Multiple columns each on I have this table:
id   | word1   | word2
1    |  100    | 200
2    |  101    | 200

I want to show the word_number values only one time, for example, for the current table - here`s my expected result:
100, 101, 200

I have tried this:
$stmt = $mysqli->prepare('SELECT word1, word2 FROM table GROUP BY word1, word2 ORDER BY id DESC LIMIT ?, ?');
$stmt->bind_param('ii', $start,$perpage);
$stmt->execute();

in this way its group only the word1, so the result its:
100, 200, 101, 200

When I change the GROUP BY to word2 its correct, but its to opposite.
More explain for the question:
id   | word1   | word2
1    |  100    | 200
2    |  101    | 200

for this table, id row its primary key, its mean grow every row.
so for word1 = 100, word2 = 200 - the id value its 1 - I want to ORDER BY this id key.

A: If you don't really need the result to be sorted by the ID?
Then you could use a normal UNION with a select for both word fields.
A normal UNION already discards duplicates, so it won't need a GROUP BY then.
$stmt = $mysqli->prepare('SELECT word1 as word FROM table UNION SELECT word2 FROM table ORDER BY word DESC LIMIT ?, ?');

And if it does need to be sorted by the ID, then using a UNION ALL wouldn't remove the dups. So you can group & sort from a sub-query.
Then the Query could be something like this:

SELECT word
FROM
(
  SELECT id, word1 as word
  FROM table
  UNION ALL
  SELECT id, word2
  FROM table
) q
GROUP BY word
ORDER BY MAX(id) DESC
LIMIT ?, ?

Or by using the CROSS JOIN to numbers trick.

select case n when 1 then word1 when 2 then word2 end as word
from table
cross join (select 1 n union all select 2) N
group by word
order by min(id) desc
limit ?, ?


text:
Q: Apply function row wise on pandas data frame on columns with numerical values I have the following data frame:
import pandas as pd
df = pd.DataFrame({'AAA' : ['w','x','y','z'], 'BBB' : [10,20,30,40],'CCC' : [100,50,-30,-50]})

Which looks like this:
In [32]: df
Out[32]:
  AAA  BBB  CCC
0   w   10  100
1   x   20   50
2   y   30  -30
3   z   40  -50

What I want to do is to perform function operation on every row for every column except those with non-numerical value (in this case AAA). In the real case the non-numerical case is always on first column, and the rest (could be greater than 2 columns) are always numerical.
The final desired output is:
  AAA  BBB  CCC  Score
0   w   10  100  110
1   x   20   50   70
2   y   30  -30    0
3   z   40  -50  -10

I tried this but failed:
import numpy as np
df["Score"] = df.apply(np.sum, axis=1)

What's the right way to do it?
Update2:
This is the code that give SettingWithCopyWarning.
Please fresh start the ipython for testing.
import pandas as pd
import numpy as np
def cvscore(fclist):
    sd = np.std(fclist)
    mean = np.mean(fclist)
    cv = sd/mean
    return cv

def calc_cvscore_on_df(df):
    df["CV"] = df.iloc[:,1:].apply(cvscore, axis=1)
    return df

df3 = pd.DataFrame(np.random.randn(1000, 3), columns=['a', 'b', 'c'])
calc_cvscore_on_df(df3[["a","b"]])

A: To select everything but the first column, you could use df.iloc[:, 1:]:
In [371]: df['Score'] = df.iloc[:, 1:].sum(axis=1)

In [372]: df
Out[372]:
  AAA  BBB  CCC  Score
0   w   10  100    110
1   x   20   50     70
2   y   30  -30      0
3   z   40  -50    -10

To apply an arbitrary function, func, to each row:
df.iloc[:, 1:].apply(func, axis=1)

For example,
import numpy as np
import pandas as pd

def cvscore(fclist):
    sd = np.std(fclist)
    mean = np.mean(fclist)
    cv = sd/mean
    return cv

df = pd.DataFrame({'AAA' : ['w','x','y','z'], 'BBB' : [10,20,30,40],
                   'CCC' : [100,50,-30,-50]})

df['Score'] = df.iloc[:, 1:].apply(cvscore, axis=1)
print(df)

yields
  AAA  BBB  CCC     Score
0   w   10  100  1.211386
1   x   20   50  0.868377
2   y   30  -30       NaN
3   z   40  -50 -5.809058


text:
Q: Unable to start monetdb using mserver5 I have an existing monetdb installation and a dbfarm. I want to change the number of threads being used by monetdb as specified in this (https://www.monetdb.org/Documentation/Guide/Multicores) docs page. It looks like we need to start monetdb using mserver5 instead of monetdbd to be able to set this parameter. So, I tried the following command:
mserver5 --dbpath=dbfarm/voc/ --set mapi_port=50000
 BBPdiskscan: unexpected file log.6, leaving /home/mskd/dbfarm/voc/bat/sql_logs/sql.
 BBPdiskscan: unexpected file BBP.dir, leaving /home/mskd/dbfarm/voc/bat/bat/BACKUP.
 # MonetDB 5 server v11.27.13 "Jul2017-SP4"
 # Serving database 'voc', using 8 threads
 # Compiled for x86_64-pc-linux-gnu/64bit with 128bit integers
 # Found 31.301 GiB available main-memory.
 # Copyright (c) 1993 - July 2008 CWI.
 # Copyright (c) August 2008 - 2018 MonetDB B.V., all rights reserved
 # Visit https://www.monetdb.org/ for further information
 # Listening for connection requests on mapi:monetdb://127.0.0.1:50000/
 # MonetDB/SQL module loaded

The client is unable to connect to the above.
I think this is occurring because the URI is wrong the above output of mserver. Usually, while starting it using monetdbd, it automatically connects to the URI: mapi:monetdb://127.0.0.1:50000/voc
Can someone point me to how to change this URI while starting monetdb using mserver5?

A: I found how to do this. Have a look at the dbfarm/merovingian.log while starting it using monetdbd. The command is printed into the log file, change the threads parameter as needed.


text:
Q: How to bind content inside another content in Xamarin.UWP? I'm creating controls in one page that have other controls of their own.
I'm trying to bind the content of a frame inside another bound content, but it crashes if I try to access it the second time.
Also tried to change bind mode to TwoWay with the same result.
Xamarin Forms: 5.0.0.2012
Xamarin.Essentials: 1.6.1
PropertyChanged.Fody: 3.3.2
Main Xaml ->
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:test="clr-namespace:Test"
             x:Class="Test.MainPage">
    <ContentPage.BindingContext>
        <test:MainViewModel/>
    </ContentPage.BindingContext>
    <StackLayout>
        <Button Text="Some Content View"
                Command="{Binding ChangeToContent}"/>
        <Button Text="Some other Content View"
                Command="{Binding ChangeToOtherContent}"
                />
        <Frame Content="{Binding model.MainContent}"/>
    </StackLayout>

</ContentPage>

MainViewModel-->
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using Xamarin.Forms;

namespace Test
{
    public class MainViewModel : INotifyPropertyChanged
    {
        public MainModel model { get; set; } = new MainModel();

        public Command ChangeToContent => new Command(() => {
            model.MainContent.Content = new Test1Content();
            });

        public Command ChangeToOtherContent => new Command(() => {
            model.MainContent.Content = new Test2Content();
        });

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            var changed = PropertyChanged;
            if (changed == null)
                return;

            changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }
}

Main Model -->
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using Xamarin.Forms;

namespace Test
{
    public class MainModel : INotifyPropertyChanged
    {
        public Frame SomeContent { get; set; } = new Frame()
        {
            BackgroundColor = Color.Red,
            WidthRequest = 40,
            HeightRequest = 40
        };

        public Frame SomeOtherContent { get; set; } = new Frame()
         {
             BackgroundColor = Color.Blue,
             WidthRequest = 40,
             HeightRequest = 40
         };

        public ContentView MainContent { get; set; } = new ContentView();

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            var changed = PropertyChanged;
            if (changed == null)
                return;

            changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }
}

First Content View -->
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Test.Test1Content">
  <ContentView.Content>
      <StackLayout>
          <Label Text="This is Test 1 Content" />
            <Frame Content="{Binding model.SomeContent}"/>
        </StackLayout>
  </ContentView.Content>
</ContentView>

Second Content
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Test.Test2Content">
  <ContentView.Content>
      <StackLayout>
          <Label Text="This is Test 2 Content" />
            <Frame Content="{Binding model.SomeOtherContent}"/>
        </StackLayout>
  </ContentView.Content>
</ContentView>

Result: https://imgur.com/a/caN9gxX

*

*1st Image is the startup

*2nd Image is after pressing top button

*3rd Image is after pressing the button under

*4th Image is of the error's stack trace after pressing top button again

A: I may have found a solution. The hint was in https://github.com/xamarin/Xamarin.Forms/issues/2713.
If I modify the Command ChangeToOtherContent and ChangeToContent in my Viewmodel like this:

        public Command ChangeToContent => new Command(() => {
            model.MainContent.Content = null;
            model.MainContent.Content = new Test1Content() { BindingContext = this };
            });

        public Command ChangeToOtherContent => new Command(() => {
            model.MainContent.Content = null;
            model.MainContent.Content = new Test2Content() { BindingContext = this };
        });

the app doesn't crash.
The null content is important if I trigger the command successively. It can probably be replaced by a bool, testing if the user has triggered the command more than once, but that would imply a lot more tests.
I don't understand why the bindingcontext needs to be added, as it is correct the first time it gets rendered. Maybe someone can add to this.


text:
Q: ffmpeg -vcopy to folder without filename I'm trying to find a command line to copy part of videos and export them to a different folder.
The problem i need to solve is each file may have different extensions, .mxf, .dv, .avi etc some came from a internal url server that gives download links like /server/download?id=1000 and that will download an mp4, or a mxf so i have no idea the extension.. the name is not important..
i want to know if it's possible or there's an existing command line where the -y file.extension is not needed.
For example
ffmpeg.exe -i "/server/download?id=1000" -vcodec copy -acodec copy -y "folder/"
An i get a filename.avi or filename.mxf inside that "folder/"

A: .mxf is a container format, so just pulling it in like ffmpeg -i http://xx -vcodec copy -acodec copy OUTPUT.mp4 might work regardless of the input (if it starts as an .mxf then ffmpeg will basically re-container it into an mp4 container).  (it will "re-container" the same elemental video/audio streams, which will remain unmodified, I assume that was your initial intent). If you really want to keep the containers also the same, you might be able to run ffmpeg -i http:///xx first, which might tell you the container type, then turn around and run it like ffmpeg -i http://xx  -vcodec copy -acodec copy output.ext


text:
Q: How do I edit a value in an OMElement I'm trying to replace a value in the Value tag in an OMElement.
My code is only adding to it (the 564.12 value below it).
<b:UI022002D>
  <b:Description>Box 2a (Taxable Amount)</b:Description>
  <b:UIRef>UI022002D</b:UIRef>
  <b:Value>564.1200</b:Value>
  564.12
</b:UI022002D>

Code:
ArrayList
<OMElement>
  aElem=getChildrenByPath(oForm, xpathNonUniueTag);
  for(int i=0;i <aElem.size();i++) {
    OMElement elem=aElem.get(i);
    if (xpathNonUniueTag=="*/AmountFields/FormAmountField") {
      if (sValue.length()> 2){
        elem.setText(getChildText(elem, "Value").substring(0, sValue.length() - 2));
      }
    }
  }

A: Found my answer:
private void mapNonUniqueNodes(OMElement oForm, String sFormID, String xpathNonUniueTag, String xpathChildNodeWithUniqueTag,
                               String sDescTag)
{

        ArrayList<OMElement> aElem=getChildrenByPath(oForm, xpathNonUniueTag);
    for(int i=0;i<aElem.size();i++)
    {
        OMElement elem=aElem.get(i);
        String newTagName=getChildText(elem, xpathChildNodeWithUniqueTag);

        newTagName=newTagName.replace("-", "");
        String sDescTagValue=getChildText(elem, sDescTag);

        if (xpathNonUniueTag == "*/AmountFields/FormAmountField") {

            ArrayList<OMElement> aElem2=getChildrenByPath(elem, "*/Value");
            log.info("aElem2  " + aElem2);
            for(int e=0;e<aElem2.size();e++)
            {
                OMElement elem2=aElem2.get(e);

                String sValue = elem2.getText();
                if (sValue.length() > 2){
                    sValue = sValue.substring(0, sValue.length() - 2);

                elem2.setText(sValue);
                log.info("elem2 " + elem2);
                log.info("elem2 text " + elem2.getText());
                }
            }

        }
        }


text:
Q: JPA Specification equivalent of ResultTransformer.DISTINCT_ROOT_ENTITY? I was wondering if there's an equivalent of ResultTransformer.DISTINCT_ROOT_ENTITY to use in JPA Specifications? Right now, I'm trying to implement search functionality and I must use JPA Specifications for that (I'm not allowed to use CriteriaQuery or other alternatives).
I have to execute a JOIN in the search query because there's a one to many relationship between entities.
So, right now, I'm doing this:
String type = "admin";
SpecificationBuilder sb = SpecificationBuilder.getInstance();
Specification<WebContentImpl> spec = new Specification<WebContentImpl>() {
    @Override
    public Predicate toPredicate(Root<WebContentImpl> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
        return cb.equal(root.join("users", JoinType.LEFT).get("type"), type);
    }
};
sb.addSpecification(spec);

As you can see, I can include a JOIN. Several users are mapped to a single web content item. However, when there are for example 3 users mapped to 1 web content item, the web content item should only be shown 1 time, but it's shown 3 times. I had this problem in the past, and the flag ResultTransformer.DISTINCT_ROOT_ENTITY helped me out then, but I can't use that functionality now.
Sure, I can implement my own solution to leave out the doubles, but it will be terrible for the performance. And I already tried changing the JoinType, but the result was always the same.
Anyone out there with some tips to help me? :-)
Thanks in advance!
Kind regards,
K

A: Try using distinct(boolean) in CriteriaQuery.

A: You can de-duplicate via group by based on primary key column of root table:
cq.groupBy(root.get("id"));

Assuming that WebContentImpl.is is primary key column of that table.


text:
Q: Minecraft: PE on Kindle cannot connect to another Kindle running Minecraft: PE We have two Kindles that both have Minecraft: Pocket Edition on them.
When we try to join games and play together only 1 of the Kindles shows a list of Wi-Fi games active. Why doesn't the other Kindle show the same list and read the other Kindle's active games? Whenever we want to join it's only one sided every time. Kindle 1 can join Kindle 2 but Kindle 2 cannot join Kindle 1.
Is there a setting I can change so both can join either game?

A: On one kindle start the world you both want to play on. Then with the second kindle goto multiplayer and click the wifi game. You will then join the game that is on the first kindle.

A: You need to be in the same room and wifi has to be on both and have to have the same computer or it won't work


text:
Q: Interpreting p-values of goodness-of-fit tests using resampling I would like to find a suitable distribution to fit to a dataset. Beyond visual analysis of histograms with overlaid density curves and Q-Q plots I would like to perform statistical tests, namely Kolmogorov-Smirnov and Anderson-Darling. As I don't know the fully specified distribution a priori, I estimate the distribution parameters from the data. However this invalidates the tests and so I simulate the test statistics a large number of times.
My issue is in interpreting the output. Here is an example using R code from the answer on How to determine which distribution fits my data best? to test the suitability of a Weibull distribution for my data:
library(logspline)
library(FAdist)
library(fitdistrplus)
library(ADGofTest)

n.sims <- 5e4 #number of simulations for KS and AD tests
x <- as.numeric(zooList$flow12001) #data vector length 973

fit.wei <- fitdist(x, "weibull")
#replicate KS
ksstats <- replicate(n.sims, {
  r <- rweibull(n = length(x), shape = fit.wei$estimate["shape"]
              , scale = fit.wei$estimate["scale"])
  as.numeric(ks.test(r, "pweibull", shape = fit.wei$estimate["shape"]
                     , scale = fit.wei$estimate["scale"])$statistic)
})

ksfit <- logspline(ksstats)
kspval <- 1 - plogspline(ks.test(x, "pweibull", shape= fit.wei$estimate["shape"],
                       scale = fit.wei$estimate["scale"])$statistic, ksfit)
> kspval
[1] 0.2647569

#replicate A-D
adstats <- replicate(n.sims, {
  r <- rweibull(n = length(x), shape = fit.wei$estimate["shape"]
              , scale = fit.wei$estimate["scale"])
  as.numeric(ad.test(r, pweibull, shape= fit.wei$estimate["shape"]
                     , scale = fit.wei$estimate["scale"])$statistic)
})

adfit <- logspline(adstats)
adpval <- 1 - plogspline(ad.test(x, pweibull, shape = fit.wei$estimate["shape"],
                       scale = fit.wei$estimate["scale"])$statistic, adfit)
> adpval
[1] 0.1292376

My interpretation of these results is that for repeated tests, the KS test results in a rejection of H0 ~26% of the time whilst the AD test a rejection of H0 ~13% of the time. Often hypothesis tests are compared to tables of critical values for the test statistic or associated p-values (generally p-val = 0.05), but in my example can I choose the p-value arbitrarily due to the resampling procedure?
I am aware that there exist tables for the critical values of the KS test (e.g. http://www.cas.usf.edu/~cconnor/colima/Kolmogorov_Smirnov.htm) and asymptotic AD test (http://www.cithep.caltech.edu/~fcp/statistics/hypothesisTest/PoissonConsistency/AndersonDarling1954.pdf) but to be honest I am not sure how to use these in a resampling-based methodology.

A: You are essentially looking at a distribution of p-values. As discussed in [1] and [2], p-value is a uniformly-distributed random variable when the null hypothesis is true. Note that in this case your null hypothesis is that your sampled data orginate from the reference distribution curve.
A good way to validate this fact is to perform a large number of K-S tests where you compare between resampled populations of your data instead of a reference distribution curve. You will see that indeed, when comparing sets of data that come from the same model, the p-value distribution is uniform.
Thus, you could perhaps use a uniformity test on the p-value distribution to determine its uniformness. If your uniformity test gives a p-value < 0.05 or some other critical value, then you can reject your null hypothesis.
[1] Murdoch, D, Tsai, Y, and Adcock, J (2008). P-Values are Random Variables. The American Statistician, 62, 242-245.
[2] Why are p-values uniformly distributed under the null hypothesis?


text:
Q: iPhone dev - how to store and retrieve data on sqlite server using RESTful services I am fairly new to iOS development, but have made an iPhone app that allows users to key simple contact info (name, email, phone, title) into a view that then stores it into a sqlite data base on my MAC. I am using the FMDB library to help with this. Now, I would like to use a RESTful web service to store the data on a server somewhere instead of on my MAC, but am not sure how to start. Any suggestions? Any libraries that would help?

A: If you would like to keep your database on a server then it may be a better idea to have a MySQL or PostgreSQL database set up with a language like PHP or Python to serve as your back-end "server side" web framework. This will keep all of your queries and connections separate from the application itself. With this model your Objective-C written native app becomes a simple front end. This also allows you to write the app for other platforms like Android and/or a website without changing the server side code much.
Here's a nice tutorial on how to get started for an iPhone app: link.


text:
Q: Get `tsc` import dependencies on Node project I'm creating a small discord bot using Node and Typescript.
The current code is pretty simple:
import * as Discord from "discord.js";
const config = require("./config.json");

const client = new Discord.Client();

client.on("ready", () => {
  if (client.user) {
    console.log(`Logged in as ${client.user.tag}!`);
  } else {
    console.log(`Ready without client.user`);
  }
});

client.on("message", (msg: any) => {
  if (msg.content === "ping") {
    msg.reply("Pong!");
  }
});

client.login(config.BOT_TOKEN);

And out of that, I'm trying to have it build a single bot.js file to be uploaded to the host.
So far, it has been failing, as the result is only:
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
define(["require", "exports", "discord.js"], function (require, exports, Discord) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    Discord = __importStar(Discord);
    var config = require("./config.json");
    var client = new Discord.Client();
    client.on("ready", function () {
        if (client.user) {
            console.log("Logged in as " + client.user.tag + "!");
        }
        else {
            console.log("Ready without client.user");
        }
    });
    client.on("message", function (msg) {
        if (msg.content === "ping") {
            msg.reply("Pong!");
        }
    });
    client.login(config.BOT_TOKEN);
});
//# sourceMappingURL=index.js.map

I've been tweaking the settings for a while trying to make it build as expected but so far no results.
My tsconfig.json follows:
{
    "compilerOptions": {
      /* Basic Options */
      "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */,
      "module": "amd" /* Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
      // "lib": [],                             /* Specify library files to be included in the compilation:  */
      "allowJs": true /* Allow javascript files to be compiled. */,
      // "checkJs": true,                       /* Report errors in .js files. */
      // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
      // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
      "sourceMap": true /* Generates corresponding '.map' file. */,
      // "outFile": "./dist/index.js" /* Concatenate and emit output to single file. */,
      "outDir": "./dist" /* Redirect output structure to the directory. */,
      // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
      // "resolveJsonModule": true /* Do not emit comments to output. */,
      "esModuleInterop": true /* Do not emit comments to output. */,
      "removeComments": true /* Do not emit comments to output. */,
      // "noEmit": true,                        /* Do not emit outputs. */
      // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
      // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
      // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

      /* Strict Type-Checking Options */
      "strict": true /* Enable all strict type-checking options. */,
      "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
      "strictNullChecks": true /* Enable strict null checks. */,
      "noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */,
      // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

      /* Additional Checks */
      // "noUnusedLocals": true,                /* Report errors on unused locals. */
      // "noUnusedParameters": true,            /* Report errors on unused parameters. */
      // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
      // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

      /* Module Resolution Options */
      "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
      // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
      // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
      // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
      // "typeRoots": [],                       /* List of folders to include type definitions from. */
      // "types": [],                           /* Type declaration files to be included in compilation. */
      // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
      // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */

      /* Source Map Options */
      // "sourceRoot": "./",                    /* Specify the location where debugger should locate TypeScript files instead of source locations. */
      // "mapRoot": "./",                       /* Specify the location where debugger should locate map files instead of generated locations. */
      // "inlineSourceMap": true /* Emit a single file with source maps instead of having a separate file. */,
      // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

      /* Experimental Options */
      "experimentalDecorators": true /* Enables experimental support for ES7 decorators. */
      // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
    },
    "include": ["src/**/*.ts"],
    "exclude": ["node_modules"]
  }

A: In your compiler options you have "module": "amd". This is wrong.
Discord uses a node api which uses common js so change it to: "module": "commonjs".
Reference
https://discordjs.guide/creating-your-bot/#logging-in-to-discord


text:
Q: What is scala.enable file? I have a java maven project and now I have to include codebase in scala for that project. I added the scala dependencies to pom.xml. As soon as I create the directory src/main/scala, my project build starts to fail with the following error.
Failed to execute goal org.apache.maven.plugins:maven-enforcer-plugin:1.4.1:enforce (enforce-scala-enable-exist) on project XYZ.
Some required files are missing - projectpath/scala.enable.
I have done such integrations in the past but never faced an issue like this. I could not find any information on scala.enable file. As soon as I add scala.enable file, I am successfully able to build the project. I also get it that it is to enable scala in the project but as far as my understanding goes it should happen on it's own and I don't need to push such files to production. I want to understand if I can avoid adding scala.enable file to the project.

A: It was enforced at parent pom level in my case. So there are two ways you can bypass this. remove the parent pom.xml if you can. or you can override this setting in your project pom.xml using below snippet.
    <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-enforcer-plugin</artifactId>
    <version>3.0.0-M2</version>
    <executions>
    <execution>
    <id>enforce-scala-enable-exist</id>
    <goals>
    <goal>enforce</goal>
    </goals>
    <configuration combine.self="override">
    <rules>
    <requireFilesExist>
    <files>
    <file>${project.build.directory}/scala.enable</file>
    </files>
    </requireFilesExist>
    </rules>
    <fail>false</fail>
    </configuration>
    </execution>
    </executions>
    </plugin>


text:
Q: Adding Constraint Programmatically Does Not Work I'm setting constraints to image view programmatically like so:
        imgScrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        imgScrollView.showsHorizontalScrollIndicator = false
        imgScrollView.showsVerticalScrollIndicator = false
        imgScrollView.bouncesZoom = false
        imgScrollView.bounces = false

        view.addSubview(imgScrollView)

        imgScrollView.translatesAutoresizingMaskIntoConstraints = false
        imgScrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        imgScrollView.bottomAnchor.constraint(equalTo: toolBar.topAnchor, constant: -100).isActive = true
        imgScrollView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 0).isActive = true
        imgScrollView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: 0).isActive = true

        // add image view to scrollview
        imgView = UIImageView(frame: CGRect(x: 0, y: 0,width: 100, height: 100))

        imgScrollView.addSubview(imgView)
        imgView.translatesAutoresizingMaskIntoConstraints = false

        imgView.topAnchor.constraint(equalTo: imgScrollView.contentLayoutGuide.topAnchor, constant: 0).isActive = true
        imgView.bottomAnchor.constraint(equalTo: imgScrollView.contentLayoutGuide.bottomAnchor, constant: 0).isActive = true
        imgView.leftAnchor.constraint(equalTo: imgScrollView.contentLayoutGuide.leftAnchor, constant: 0).isActive = true
        imgView.rightAnchor.constraint(equalTo: imgScrollView.contentLayoutGuide.rightAnchor, constant: 0).isActive = true

        imgView.widthAnchor.constraint(equalTo: imgScrollView.widthAnchor, multiplier: 1).isActive = true

Now later on with button tap I'm adding additional constraint
imgView.heightAnchor.constraint(equalTo: imgScrollView.heightAnchor, multiplier: 1).isActive = true

However the constraint is not being added. Why is it happening?

A: Your implementation logic working for me.

*

*Left image show implementation without height constraint.

*Right image show button pressed with height constraint.

In function viewDidLoad
override func viewDidLoad() {
  super.viewDidLoad()
  view.backgroundColor = .white
  scrollView.isScrollEnabled = true
  scrollView.bounces = false
  scrollView.alwaysBounceVertical = true
  imageView.image = UIImage(color: .lightGray)

  navigationItem.rightBarButtonItem = barButtonItem
  view.addSubview(scrollView)
  scrollView.addSubview(imageView)

  scrollView.translatesAutoresizingMaskIntoConstraints = false
  imageView.translatesAutoresizingMaskIntoConstraints = false
  NSLayoutConstraint.activate([
    scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
    scrollView.leftAnchor.constraint(equalTo: view.leftAnchor),
    scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
    scrollView.rightAnchor.constraint(equalTo: view.rightAnchor)
  ])
  NSLayoutConstraint.activate([
    imageView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor),
    imageView.leftAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leftAnchor),
    imageView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor),
    imageView.rightAnchor.constraint(equalTo: scrollView.contentLayoutGuide.rightAnchor),
    imageView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
  ])
}

In function buttonPressed
@objc func buttonPressed() {
  navigationItem.rightBarButtonItem = nil
  UIView.animate(withDuration: 1) {
    NSLayoutConstraint.activate([
      self.imageView.heightAnchor.constraint(equalTo: self.scrollView.heightAnchor)
    ])
    self.view.setNeedsLayout()
    self.view.layoutIfNeeded()
  }
}

UIImage util Create UIImage with solid color in Swift
fileprivate extension UIImage {
  convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
    let rect = CGRect(origin: .zero, size: size)
    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
    color.setFill()
    UIRectFill(rect)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    guard let cgImage = image?.cgImage else { return nil }
    self.init(cgImage: cgImage)
  }
}


text:
Q: Port Mapping memory components not working I'm using Quartus II and i need to create a 256 x 4B (1KB) memory out of 8 components of 128x1B, but i'm a begginer in vhdl.
Here's the 128x1B component(this is not where the problem lies), created using MegaWizard Quartus II plugin:
LIBRARY ieee;
USE ieee.std_logic_1164.all;

LIBRARY altera_mf;
USE altera_mf.all;

ENTITY RAM_128B_MegaWizard IS
PORT
(
    address     : IN STD_LOGIC_VECTOR (6 DOWNTO 0);
    clock       : IN STD_LOGIC  := '1';
    data        : IN STD_LOGIC_VECTOR (7 DOWNTO 0);
    wren        : IN STD_LOGIC ;
    q       : OUT STD_LOGIC_VECTOR (7 DOWNTO 0)
);
END RAM_128B_MegaWizard;

ARCHITECTURE SYN OF ram_128b_megawizard IS

SIGNAL sub_wire0    : STD_LOGIC_VECTOR (7 DOWNTO 0);

COMPONENT altsyncram
GENERIC (
    clock_enable_input_a        : STRING;
    clock_enable_output_a       : STRING;
    intended_device_family      : STRING;
    lpm_hint        : STRING;
    lpm_type        : STRING;
    numwords_a      : NATURAL;
    operation_mode      : STRING;
    outdata_aclr_a      : STRING;
    outdata_reg_a       : STRING;
    power_up_uninitialized      : STRING;
    widthad_a       : NATURAL;
    width_a     : NATURAL;
    width_byteena_a     : NATURAL
);
PORT (
        wren_a  : IN STD_LOGIC ;
        clock0  : IN STD_LOGIC ;
        address_a   : IN STD_LOGIC_VECTOR (6 DOWNTO 0);
        q_a : OUT STD_LOGIC_VECTOR (7 DOWNTO 0);
        data_a  : IN STD_LOGIC_VECTOR (7 DOWNTO 0)
);
END COMPONENT;

BEGIN
q    <= sub_wire0(7 DOWNTO 0);

altsyncram_component : altsyncram
GENERIC MAP (
    clock_enable_input_a => "BYPASS",
    clock_enable_output_a => "BYPASS",
    intended_device_family => "Cyclone II",
    lpm_hint => "ENABLE_RUNTIME_MOD=NO",
    lpm_type => "altsyncram",
    numwords_a => 128,
    operation_mode => "SINGLE_PORT",
    outdata_aclr_a => "NONE",
    outdata_reg_a => "UNREGISTERED",
    power_up_uninitialized => "FALSE",
    widthad_a => 7,
    width_a => 8,
    width_byteena_a => 1
)
PORT MAP (
    wren_a => wren,
    clock0 => clock,
    address_a => address,
    data_a => data,
    q_a => sub_wire0
);

END SYN;

Now here's the problem. I'm trying to use port map to instantiate the memory components and i'm getting the following errors
Error (10500): VHDL syntax error at RAM_256x4B.vhd(50) near text "1.1";  expecting  "end", or "(", or an identifier, or a concurrent statement
Error (10500): VHDL syntax error at RAM_256x4B.vhd(51) near text ";";  expecting "<="
Error (10500): VHDL syntax error at RAM_256x4B.vhd(53) near text ";";  expecting "<="
Error (10500): VHDL syntax error at RAM_256x4B.vhd(55) near text ";";  expecting "<="
Error (10500): VHDL syntax error at RAM_256x4B.vhd(57) near text ";";  expecting "<="
Error (10500): VHDL syntax error at RAM_256x4B.vhd(60) near text ";";  expecting "<="
Error (10500): VHDL syntax error at RAM_256x4B.vhd(62) near text ";";  expecting "<="
Error (10500): VHDL syntax error at RAM_256x4B.vhd(64) near text ";";  expecting "<="
Error (10500): VHDL syntax error at RAM_256x4B.vhd(66) near text ";";  expecting "<="

Here's the code. My address have to be of size 10 bits and i'm using a decoder and a mux through packages.
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

library work;
use work.RAM_128B_MegaWizard_package.all;
use work.dec1to2_package.all;
use work.mux2to1_package.all;

entity RAM_256x4B is
generic(
        depth : integer range 1 to 10 := 10;
        width: integer range 1 to 32 := 32;
        init_file : string := "init_file2.mif");
        -- .mif filename

port(Clock : in std_logic;
     WrEn: in std_logic;
    -- write control signal
     Address : in std_logic_vector(depth-1 downto 0);
    -- read and write addresses
     data : in std_logic_vector(width-1 downto 0);
    -- data to be written
     DataOut : out std_logic_vector(width-1 downto 0));
    -- memory read output
end RAM_256x4B;

architecture behavior of RAM_256x4B is

signal dOut0: std_logic_vector(width-1 downto 0);
signal dOut1: std_logic_vector(width-1 downto 0);
signal En: std_logic_vector(0 to 1);

begin

    decoder: dec1to2 port map (Address(depth-3), WrEn, En);

    1.1: RAM_128B_MegaWizard port map
        (Clock, En(0), Address(depth-4 downto 0), data(width-1 downto 24), dOut0(width-1 downto 24));
    1.2: RAM_128B_MegaWizard port map
        (Clock, En(0), Address(depth-4 downto 0), data(23 downto 16), dOut0(23 downto 16));
    1.3: RAM_128B_MegaWizard port map
        (Clock, En(0), Address(depth-4 downto 0), data(15 downto 8), dOut0(15 downto 8));
    1.4: RAM_128B_MegaWizard port map
        (Clock, En(0), Address(depth-4 downto 0), data(7 downto 0), dOut0(7 downto 0));

    2.1: RAM_128B_MegaWizard port map
        (Clock, En(1), Address(depth-4 downto 0), data(width-1 downto 24), dOut1(width-1 downto 24));
    2.2: RAM_128B_MegaWizard port map
        (Clock, En(1), Address(depth-4 downto 0), data(23 downto 16), dOut1(23 downto 16));
    2.3: RAM_128B_MegaWizard port map
        (Clock, En(1), Address(depth-4 downto 0), data(15 downto 8), dOut1(15 downto 8));
    2.4: RAM_128B_MegaWizard port map
        (Clock, En(1), Address(depth-4 downto 0), data(7 downto 0), dOut1(7 downto 0));

    mux: mux2to1 port map (dOut0, dOut1, Address(depth-3),DataOut);

end behavior;

I know it's incomplete, but whatever i do compilation gives me the same errors. Even if the part after begin and end architecture is just
1.1: RAM_128B_MegaWizard port map
        (Clock, En(0), Address(depth-4 downto 0), data(width-1 downto 24), dOut0(width-1 downto 24));

the same will happen.
I understand port map can't be used inside a process, but a component with process(the 128x1B) also can't be port mapped? How can i combine these components to make what i want?

A: It looks to me like you're having a problem doing your port mapping by reference.  Here's the component you're instantiating:
address     : IN STD_LOGIC_VECTOR (6 DOWNTO 0);
clock       : IN STD_LOGIC  := '1';
data        : IN STD_LOGIC_VECTOR (7 DOWNTO 0);
wren        : IN STD_LOGIC ;
q       : OUT STD_LOGIC_VECTOR (7 DOWNTO 0)

So if you're doing by reference, you should have this instantiation:
 inst_1_1 : RAM_128B_MegaWizard port map
    (Address(depth-4 downto 0), Clock, data(width-1 downto 24), En(0), dOut0(width-1 downto 24));

Notice the placement of the signals.  This is why I prefer to do explicit port mapping, you'll make less mistakes.
Also I'm not sure what restrictions there are against your instantiation name, but 1.1 doesn't seem like a good name to me.  Try something that begins with a letter and only has underscores, not periods.

A: A label is required to be an identifier.  These cause the Error (10500) VHDL... errors.
Either a basic identifier:
 basic_identifier ::=
     letter  { [ underline ] letter_or_digit }

 letter_or_digit ::=  letter | digit

 letter ::=  upper_case_letter | lower_case_letter

or an extended identifier:
 extended_identifier ::=
    \ graphic_character { graphic_character } \

In your case the labels (1.1, 1.2, etc.) need to start with a letter, sort of like Russel demonstrates in his answer incidentally and in addition to the incorrect positional association in the port interfaces where they are instantiated.
Fix both issues.


text:
Q: Custom segue animating with delay after code being run. (Objective C) I have several dispatch_async methods linked so they authenticate a user in my system.
The next async method only happens when the previous one finishes, as they each have completion handlers.
When the last one is finished I perform a custom segue with 2 uiview animation blocks.
However, when I log when each of these actually run, there is a considerable gap between the log and the animation actually happening, eventually the views animate and the completion block is called.
I don't really know how useful it would be adding my code here, but i have tested and it must be the async methods because if I comment them out and just return YES the animations happen without delay at the same time as the log.
Does anyone know why this might happen?
EDIT *(with code)
Typical 'exist check' used for email, user, user id.
- (void)existsInSystemWithCompletionHandler:(void (^)(BOOL))block
{
    self.existsInSystem = NO;

    if (self.isValid) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //
            //  Get data
            //
            if (dataIsValid) {
                block(YES);
            } else {
                block(NO);
            }
        });
    } else {
        block(self.existsInSystem);
    }
}

Check user exists
[potentialUser existsInSystemWithCompletionHandler:^(BOOL success) {
    if (success) {
        //  Perform segue
        //
        [self performSegueWithIdentifier:@"Logging In" sender:self];
    }
}];

Segue
- (void)perform
{
    NSLog(@"Perform");

    LogInViewController *sourceViewController = (LogInViewController *)self.sourceViewController;
    LoggingInViewController *destinationViewController = (LoggingInViewController *)self.destinationViewController;

    destinationViewController.user = sourceViewController.potentialUser;

    //  Animate
    //
    [UIView animateWithDuration:0.2f
                     animations:^{
                         NSLog(@"Animation 1");
                         //
                         // Animate blah blah blah
                         //
                     }];

    [UIView animateWithDuration:0.4f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         NSLog(@"Animation 2");
                         //
                         // Animate blah blah blah
                         //
                     }
                     completion:^(BOOL finished) {
                         NSLog(@"Completion");
                         //
                         // Finished
                         //

                         [sourceViewController presentViewController:destinationViewController animated:NO completion:nil];
                     }];
}

LoggingIn VC
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self.user loginWithCompletionHandler:^(BOOL success) {
        if (success) {
            [self performSegueWithIdentifier:@"Logged In" sender:self];
        }
    }];
}

A: Fixed! It seems to work now that in my code I have added the lines:
dispatch_async(dispatch_get_main_queue(), ^{
    completionBlock(success);
});

A: From your description it seems likely that your segue is waiting for a process to finish.
Maybe your nested async methods that follow each other through their completion methods have produced somewhat convoluted code. This might be the reason why you could be overlooking the blocking method.
One way to tidy up your code is use a sequential queue. The blocks pushed to the queue will start only when the previous one has finished.


text:
Q: Match charactes and whitespaces, but not numbers I am trying to create a regex that will match characters, whitespaces, but not numbers.
So hello 123 will not match, but hell o will.
I tried this:
[^\d\w]

but, I cannot find a way to add whitespaces here. I have to use \w, because my strings can contain Unicode characters.

A: Brief
It's unclear what exactly characters refers to, but, assuming you mean alpha characters (based on your input), this regex should work for you.

Code
See regex in use here
^(?:(?!\d)[\w ])+$

Note: This regex uses the mu flags for multiline and Unicode (multiline only necessary if input is separated by newline characters)

Results
Input
ÀÇÆ some words
ÀÇÆ some words 123

Output
This only shows matches
ÀÇÆ some words

Explanation

*

*^ Assert position at the start of the line

*(?:(?!\d)[\w ])+ Match the following one or more times (tempered greedy token)

*

*(?!\d) Negative lookahead ensuring what follows doesn't match a digit. You can change this to (?![\d_]) if you want to ensure _ is also not used.

*[\w ] Match any word character or space (matches Unicode word characters with u flag)`

*$ Assert position at the end of the line

A: You can use a lookahead:
(?=^\D+$)[\w\s]+

In Python:

import re

strings = ['hello 123', 'hell o']

rx = re.compile(r'(?=^\D+$)[\w\s]+')

new_strings = [string for string in strings if rx.match(string)]
print(new_strings)
# ['hell o']


text:
Q: Failed to execute 'texImage2D' on 'WebGL2RenderingContext'. Access to image at 'imageurl.com' from origin 'exampale.com' has been blocked by CORS i have seen this answer:
Uncaught (in promise) DOMException: Failed to execute 'texImage2D' on 'WebGL2RenderingContext': Tainted canvases may not be loaded
it does help on local made server but i am trying to make an extension/addon so i run the script on different server and if i try to set the crossOrigin attribute to 'anonymous' it says:

Access to image at
'https://dl5zpyw5k3jeb.cloudfront.net/photos/pets/48663430/1/?bust=1596323497&width=560'
from origin 'https://www.petfinder.com' has been blocked by CORS
policy: No 'Access-Control-Allow-Origin' header is present on the
requested resource.

my manifest:
{
    "manifest_version" : 2,
    "name" : "tf",
    "description": "tf",
    "version" : "0.2",
    "content_scripts" : [
        {
            "matches" : [ "<all_urls>"],
            "js" : ["tfjs.js", "coco-ssd.js", "content.js"]
        }
    ]
}

my code:
const img = document.getElementByTagName('img');
img.setAttribute('crossOrigin', 'anonymous');
cocoSsd.load().then(model => {
    let canvas = document.createElement("CANVAS");
    let ctx = canvas.getContext("2d");
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0);
    model.detect(img).then(predictions => {
          ctx.strokeRect(predictions[0].bbox[0], predictions[0].bbox[1], predictions[0].bbox[2], predictions[0].bbox[3]);
      }
      let dataURL = canvas.toDataURL();
      img.src = dataURL;
      });
    }
  });

Ty in advance

A: wOxxOm said the answer:

The thing is, content scripts can't make cross-origin requests in new
Chrome so you'll have to use an extension page. For example you can
add an iframe to the web page, pointing to an html file inside your
extension directory exposed via web_accessible_resources. That iframe
will have a chrome-extension:// URL and will be able to make
cross-origin requests for URLs listed in permissions


text:
Q: Setting file directory in appSettings of an app.config file Currently I'm hard coding this file location like so
   var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../Resources/PushSharp.Apns.Sandbox.p12"));

What I'd like to do is the somehow change that line to var appleCert = somevariablehere;
And I'd like it so that in my AppSettings section of the app.config file contacts the location or is able to find it. Is this possible? If so would anyone care to help me on how to implement this in appSettings?

A: I'm not sure if I understand correctly what you want.  But personnaly if I have a file path I would put it in a key value in my web.config:
  <appSettings>
        <add key="UploadPath" value="C:\temp" />
  </appSettings>

I normally Have a ConfigurationManager class that have each app setting value into this class like that:
public class ConfigurationManager
{
    public string UploadPath
    {
        get
        {
            return System.Configuration.ConfigurationManager.AppSettings["UploadPath"];
        }
    }
}

It's also very useful when you have unit test so you can mock your class.
I don't use static class because I'm using dependency injection.. but if you are not and you don't have unit test, you can set your class as static


text:
Q: How can I remove the spaces from these numbers? I am using SQL Server 2014 and I have a table (t1) in my database which contain a column called "MealPlan".
This column contains a list of strings (extract below):
                        MealPlan
Sansrepas315€/pers.=630€pour2pers.Devis/RésaSelectionner

Sansrepas394€/pers.=787€pour2pers.Devis/RésaSelectionner

Sansrepas547€/pers.=1 093€pour2pers.Devis/RésaSelectionner

Sansrepas547€/pers.=1 093€pour2pers.Devis/RésaSelectionner

Sansrepas700€/pers.=1 400€pour2pers.Devis/RésaSelectionner

Sansrepas328€/pers.=656€pour2pers.Devis/RésaSelectionner

I need to extract the numbers between the characters = and €
I have the following codes in place which does exactly what I need:
SUBSTRING(MealPlan,LEN(LEFT(MealPlan,CHARINDEX('=', MealPlan)+1)),LEN(MealPlan) - LEN(LEFT(MealPlan,CHARINDEX('=', MealPlan))) - LEN(RIGHT(MealPlan,CHARINDEX('€', (REVERSE(MealPlan)))))) AS [Price]

After running the above my column "Price" appear as follows:
Price
630
787
1 093
1 093
1 400
656

However, I want to get rid of that space in the numbers where a thousand digit is present.
My expected output:
   Price
    630
    787
    1093
    1093
    1400
    656

I have tried the following but it is not working:
REPLACE(SUBSTRING(MealPlan,LEN(LEFT(MealPlan,CHARINDEX('=', MealPlan)+1)),LEN(MealPlan) - LEN(LEFT(MealPlan,CHARINDEX('=', MealPlan))) - LEN(RIGHT(MealPlan,CHARINDEX('€', (REVERSE(MealPlan)))))), ' ','') AS [Price2]

Any help would be much appreciated.

A: I just ran your query in my sample database and it is working fine..
select
REPLACE(SUBSTRING(Description,
LEN(LEFT(Description,CHARINDEX('=', Description)+1)),
LEN(Description) - LEN(LEFT(Description,CHARINDEX('=', Description))) - LEN(RIGHT(Description,CHARINDEX('€', (REVERSE(Description)))))
), ' ','') AS [Description]
from Worker

A: Table #a1
| MealPlan |
| -------- |
| Sansrepas315€/pers.=630€pour2pers.Devis/RésaSelectionner   |
| Sansrepas394€/pers.=787€pour2pers.Devis/RésaSelectionner   |
| Sansrepas547€/pers.=1 093€pour2pers.Devis/RésaSelectionner |

Query
SELECT
        REPLACE(
            SUBSTRING(MealPlan,CHARINDEX('=', MealPlan)+1, CHARINDEX('=',REVERSE(MealPlan)) - CHARINDEX('€',REVERSE(MealPlan)) -1 )
            ,' ', ''
        )
        as value
FROM #a1

results

value

630

787

1093

A: The solution about "cut and paste" provided by Jiří Baum above did the trick for me.

A: It is very easy to tokenize a string of characters by using XML and XQuery.
No need to parse string and call multiple functions: SUBSTRING(), CHARINDEX(), PATINDEX(), LEN(), REVERSE(), etc.
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE  (ID INT IDENTITY(1,1) PRIMARY KEY, MealPlan NVARCHAR(1000));
INSERT INTO @tbl (MealPlan) VALUES
(N'Sansrepas315€/pers.=630€pour2pers.Devis/RésaSelectionner'),
(N'Sansrepas394€/pers.=787€pour2pers.Devis/RésaSelectionner'),
(N'Sansrepas547€/pers.=1 093€pour2pers.Devis/RésaSelectionner'),
(N'Sansrepas547€/pers.=1 093€pour2pers.Devis/RésaSelectionner'),
(N'Sansrepas700€/pers.=1 400€pour2pers.Devis/RésaSelectionner'),
(N'Sansrepas328€/pers.=656€pour2pers.Devis/RésaSelectionner');
-- DDL and sample data population, end

DECLARE @separator CHAR(1) = '='
    , @euro CHAR(1) = '€';

SELECT t.*
    , REPLACE(c.value('(/root/r[3]/text())[1]', 'VARCHAR(20)'),SPACE(1),'') AS Price
FROM @tbl AS t
CROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' +
        REPLACE(REPLACE(MealPlan,@euro,@separator), @separator, ']]></r><r><![CDATA[') +
        ']]></r></root>' AS XML)) AS t1(c);

Output
+----+------------------------------------------------------------+--------+
| ID |                          MealPlan                          | Result |
+----+------------------------------------------------------------+--------+
|  1 | Sansrepas315€/pers.=630€pour2pers.Devis/RésaSelectionner   |    630 |
|  2 | Sansrepas394€/pers.=787€pour2pers.Devis/RésaSelectionner   |    787 |
|  3 | Sansrepas547€/pers.=1 093€pour2pers.Devis/RésaSelectionner |   1093 |
|  4 | Sansrepas547€/pers.=1 093€pour2pers.Devis/RésaSelectionner |   1093 |
|  5 | Sansrepas700€/pers.=1 400€pour2pers.Devis/RésaSelectionner |   1400 |
|  6 | Sansrepas328€/pers.=656€pour2pers.Devis/RésaSelectionner   |    656 |
+----+------------------------------------------------------------+--------+

A: Try this:
Declare @MealPlan as varchar(250) = 'Sansrepas547€/pers.=1 093€pour2pers.Devis/RésaSelectionner'

Select Replace(
          SUBSTRING(@MealPlan,
                    CharIndex('=', @MealPlan)+1,
                    CharIndex(')',Replace(@MealPlan, '€p', ')'))- CharIndex('=', @MealPlan)-1 ),
          ' ', '')

Output:

Let me know if this doesn't work or you have a problem understanding the query.


text:
Q: How to make flexible array that based on the input #include<stdio.h>
#include<ctype.h>
int main() {
    int i=0;
    char in[100],mychar;
    fgets(in,sizeof(in),stdin);
    while (in[i]) {
        mychar=in[i];
        putchar (toupper(mychar));
        i++;
    }
    return 0;
}

This is a simple program used to change a string of characters to uppercase letters. My question is that I declare the array in[100], how can I make the array number follow my input? I mean if I type 1201 characters , then the program will make the have the array that follows my input which is     in[1201].

A: You can see what C++ Vector does: you can malloc a length of L at fist, every time you getch(), you should decide if you expand L to 2*L (or to L + 100 for saving spaces)

A: Perhaps something like this?
#include<stdio.h>
#include<ctype.h>

int main()
  {
  int mychar;

  mychar=fgetc(stdin);
  while(EOF != (mychar=fgetc(stdin)))
     putchar(toupper(mychar));

  return 0;
  }


text:
Q: Как сделать free() внутри функции, функция не void Есть вот такой код https://github.com/gnuvse/c_git/blob/master/big_num.c
Конкретно интерисуют функции diff_number и reverse_number.
Я в них выделяю память, как эту память потом освободить?
Мне кажется, что это память висит.
Код функций:
char *diff_number(int count_digits, char *buf1, char *buf2) {
char *res = malloc(sizeof(char) * count_digits);

    for (int i = 0; i < count_digits; i++) {
        if (buf1[i] - buf2[i] < 0) {
            buf1[i + 1] -= 1;
            res[i] = (buf1[i] + 10) - buf2[i];
        }
        else
            res[i] = buf1[i] - buf2[i];
    }

    return res;
}

char *reverse_number(int count_digits, char *buf) {
char *buf_reverse = malloc(sizeof(char) * count_digits);

    for (int i = 0, j = count_digits - 1; i < count_digits; i++, j--)
        buf_reverse[i] = buf[j];

    return buf_reverse;
}

valgrind показывает 6 раз память выделена, а в коде всего 5. Еще и 2 ошибки.
==20631== HEAP SUMMARY:
==20631==     in use at exit: 1,011 bytes in 3 blocks
==20631==   total heap usage: 6 allocs, 3 frees, 1,042 bytes allocated
==20631==
==20631== LEAK SUMMARY:
==20631==    definitely lost: 1,011 bytes in 3 blocks
==20631==    indirectly lost: 0 bytes in 0 blocks
==20631==      possibly lost: 0 bytes in 0 blocks
==20631==    still reachable: 0 bytes in 0 blocks
==20631==         suppressed: 0 bytes in 0 blocks
==20631== Rerun with --leak-check=full to see details of leaked memory
==20631==
==20631== For counts of detected and suppressed errors, rerun with: -v
==20631== ERROR SUMMARY: 2 errors from 1 contexts (suppressed: 1 from 1)

A: Странный вопрос. Взять да освободить:
char * some = diff_number( ... );
/* ... */
free( some );


text:
Q: Error:Execution failed for task ':app:processDebugResources'. Error:Execution failed for task ':app:processDebugResources'.

com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Users/sherily/android sdk/android-sdk-macosx/build-tools/android-5.0/aapt'' finished with non-zero exit value 1

build file

A: Maybe this will help, give it a try:
Build -> Clean Project

then:
Build -> Rebuild Project