text:
Q: Why does my python print run faster than Go's fmt.Print and os.Stdout.Write I'm trying to research some details about efficiency with Go because I'm new to it. One of the tests I wanted to perform was to see if Go's fmt.Print was faster or slower than os.Stdout.WriteLine
Here are the results.
fmt.Print speed
[kamori@kamori-pc playground]$ cat print.go
package main

import "fmt"
import "os"

func main(){
   os.Stderr.WriteString("Printing Hello World! 1000000000 times")
   for i := 0; i < 1000000000; i++{
       fmt.Print("Hello World!\n")
   }
}
[kamori@kamori-pc playground]$ go build print.go
[kamori@kamori-pc playground]$ time ./print >/dev/null
Printing Hello World! 1000000000 times
real    13m9.127s
user    8m52.461s
sys 4m15.433s

os.Stdout.WriteString
[kamori@kamori-pc playground]$ cat stdoutwrite.go
package main

import "os"

func main(){
   os.Stderr.WriteString("StdoutWriting Hello World! 1000000000 times")
    for i := 0; i < 1000000000; i++{
       os.Stdout.WriteString("Hello World!\n")
   }
}
[kamori@kamori-pc playground]$ go build stdoutwrite.go
[kamori@kamori-pc playground]$ time ./stdoutwrite >/dev/null
StdoutWriting Hello World! 1000000000 times
real    11m36.198s
user    7m31.211s
sys    4m0.080s

I understand this isn't the best way to test this process. But it was the one I chose and it was interesting. I'm still curious to know the differences but the results kinda make sense to me. However, just for fun, I did the same thing with Python 3 and it went way faster
Python 3
[kamori@kamori-pc playground]$ cat print.py

for i in range(1000000000):
    print("Hello World!")
[kamori@kamori-pc playground]$ time python3 print.py >/dev/null

real    6m46.542s
user    6m44.450s
sys    0m0.836s

Here is version details
[kamori@kamori-pc playground]$ go version
go version go1.13.4 linux/amd64
[kamori@kamori-pc playground]$ python --version
Python 3.7.4
[kamori@kamori-pc playground]$ uname -a
Linux kamori-pc 4.19.59-rt23-MANJARO #1 SMP PREEMPT RT Sat Jul 20 07:14:03 UTC 2019 x86_64 GNU/Linux

My question is, why did python out perform Go? My expectation was Go would be faster as its a compiled language. Sure there isn't a ton of logic that needs to be figured out on the fly so Python might be able to take some shortcuts. But, these workloads seem really small, IMO both languages should be returning pretty fast besides the startup overhead.
--- Edit ---
I saw comments about using bufio to buffer my writes. And holy moly.
[kamori@kamori-pc playground]$ cat bufferio.go
package main

//import "fmt"
import "os"
import "bufio"
func main(){
   os.Stderr.WriteString("Printing Hello World! 1000000000 times")
   mywrite := bufio.NewWriter(os.Stdout)
   for i := 0; i < 1000000000; i++{
       mywrite.WriteString("Hello World!\n")
   }
}
[kamori@kamori-pc playground]$ go build bufferio.go
[kamori@kamori-pc playground]$ time ./bufferio >/dev/null
Printing Hello World! 1000000000 times
real    0m9.882s
user    0m9.003s
sys 0m0.865s

--- Edit2 ---
For dave's answer I went ahead and set flush=True and here are the results. This is what I expected to see in my original comparison. Looks like buffering saves the day!
[kamori@kamori-pc playground]$ cat print_with_flush_true.py

for i in range(1000000000):
    print("Hello World!", flush=True)
[kamori@kamori-pc playground]$ time python3 print_with_flush_true.py >/dev/null

real    27m38.319s
user    23m15.274s
sys 4m16.869s

A: Python3 buffers the output of print.
https://docs.python.org/3/library/functions.html#print

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

You would need to do:
print("Hello World!", flush=True)

for the tests to be equivalent


text:
Q: Is it possible to trigger a spark job via oozie when a folder's size reaches a certain threshold? For instance, if a folder reaches 100 MB then a spark job should be triggered.
I read about the dirSize hdfs el function in oozie, but I'm not sure how to use it. Does it trigger the job when the folder reaches 100 MB, or does it have to be checked periodically in, let's say, every 2 minutes?

A: 1 option for you is to run a oozie coordinator periodically (say for every 2min) to check on the file size, if it attains the specified limit you can trigger the spark job.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to choose multiple topics in firebase console? I'm currently creating an app in android studio with fcm implemented. For sending push notifictations I use the firebase console (cloud messaging).
I want to choose mutliple topics when I send out a push notification. I don't want to make the whole process twice, so I want to choose multiple topics.
But I can only choose one topic per message, how can I choose more than one?
Thanks.

A: The Firebase console currently only allows sending messages to a single topic. It does not allow sending messages to multiple topics, nor sending to conditions.
If you need such functionality, you will have to send the messages by calling the FCM API for example with a condition like 'TopicA' in topics || 'TopicB' in topics.
You might also want to file a feature request for adding the feature to the console.


text:
Q: document.getElementById is undefined. Please look I sit at the computer all day and can not find the reason for the error.
My problem is that I can not get the values from the field.
I need a modal window to display data from the line.
Then he wants to send it to the base, but it's a different story
Please, look at my code and say what's wrong.
    <?php
session_start();
require_once "db.php";
?>

          <title>Lista użytkowników</title>

          <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

Lista użytkowników

    <form action="" method="post">

       ID
       Login

       Imię
       Nazwisko
       Email
       Telefon
       Stanowisko
       NR_pracownika
       Upranienia
       Opcje

<?php
if ($mysqli->connect_errno!=0){
  echo "Error".$mysqli->connect_errno;
}else{
$sql ="SELECT * FROM uzytkownicy ORDER BY id ";
if ($result = @$mysqli->query($sql)){
      $_SESSION['zalogowany'] = true;

      while($row = mysqli_fetch_array($result))
     {
      $_SESSION['log_'. $row['id']] = $row['login'];

?>

      <td method='POST' name ="id_<?=$row['id']?>" id="id_<?=$row['id']?>" value="<?=$row['id']?>"  class=" orm-control"/> <?=$row['id']?>
      <td method='POST' name="log_<?=$row['id']?>" id="log_<?=$row['id']?>" value="<?=$row['login']?>" class=" orm-control"/> <?=$row['login']?>
      <td method='POST' name="imi_<?=$row['id']?>" id="imi_<?=$row['id']?>" value="<?=$row['imie']?>" class=" orm-control"/> <?=$row['imie']?>
      <td method='POST' name="naz_<?=$row['id']?>" id="naz_<?=$row['id']?>" value="<?=$row['nazwisko']?>" class=" orm-control"/> <?=$row['nazwisko']?>
      <td method='POST' name="ema_<?=$row['id']?>" id="ema_<?=$row['id']?>" value="<?=$row['email']?>" class=" orm-control"/> <?=$row['email']?>
      <td method='POST' name="tel_<?=$row['id']?>" id="tel_<?=$row['id']?>" value="<?=$row['telefon']?>" class=" orm-control"/> <?=$row['telefon']?>
      <td method='POST' name="sta_<?=$row['id']?>"  id="sta_<?=$row['id']?>" value="<?=$row['stanowisko']?>" class=" orm-control"/> <?=$row['stanowisko']?>
      <td method='POST' name="nr_<?=$row['id']?>" id="nr_<?=$row['id']?>" value="<?=$row['nr_pracownika']?>" class=" orm-control"/> <?=$row['nr_pracownika']?>
      <td method='POST' name="ran_<?=$row['id']?>" id="ran_<?=$row['id']?>" value="<?=$row['ranga']?>" class=" orm-control"/> <?=$row['ranga']?>

        <button type="button" id="<?=$row['id']?>" onClick="reply_click()"  class="glyphicon glyphicon-pencil" data-toggle="modal" data-target="#myModalEdit"  ></button>

      </form>

    <?php  ;
     }

      //header('Location: ../workshop.php');
    }
    else{
     // header('Location: ../index.php');

    }

}

?>

          <form role="form">

Zmiana danych dla

 dfhdyjd

               id
              <input type="text" class="form-control" id="usrname" value='<?php $aaaa ?>'>

               Username
              <input type="text" class="form-control" id="usrname" value='name'>

               Password
              <input type="text" class="form-control" id="psw" placeholder="Enter password">

              <button type="submit" class="btn btn-success btn-block"> Zmien</button>
          </form>

Please, look at my code and say what's wrong.

A: I found the answer myself
I wanted to download data from the table so I use the query ....
document.getElementById("log_1").value;

is wrong,
 and the wording should be so ...
document.getElementById("myTable_U").rows[rrr].cells.item(1).innerHTML


text:
Q: Jinja2 Email Template Using Jijna2, I'm trying to make a responsive HTML email template which is almost simple

<!DOCTYPE html>

Hello,

Below are the deals running on {{ url }} at {{ date }}:

        {% for image in images %}

        {% endfor %}

Regards,

Team

That's what is shown currently:

and during full screen:

How to make it responsive in this case and keep the display of images one by one. not side by side during full screen or mobile screen!

A: I won't consider this responsive but to keep images one on top of each other, you can try to just have them as list items and hide the list bullets with list-style: none, like:

<!DOCTYPE html>

Hello,

Below are the deals running on {{ url }} at {{ date }}:

Regards,

Team

Or as I told you in comments, make the anchor link to have full width like:

A: Good morning Ahmed, what you can do is insert the css code you need to behave responsively, as in the example:

<!DOCTYPE html>

Hello,

Below are the deals running on {{ url }} at {{ date }}:

        {% for image in images %}

        {% endfor %}

Regards,

Team

Should do the trick.


text:
Q: I have warnings when I pull from git to Android Studio I uploaded a very simple and legit code and it is correct, but when I pull from another computer the XML files are colored red
Both computers with the same version of the software
All words that start with
android,
app:layout,
tools:... is red
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="250dp"
        android:layout_height="69dp"
        android:textSize="34sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.809" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: Removing namespaces and adding again worked for me.
If it didn't work try

*

*Files->Sync Project with Gradle Files

*File->Invalidate Caches/ Restart->Invalidate and Restart

If none of them works check if you've the correct SDK versions installed


text:
Q: Best practice to reload div on click and post data I am not the greatest at jQuery and still learning bits and bobs.  I currently have the below function and I would like to expand on it to post data to referrer-ajax2.php.
$(document).ready(function() {
    $('#clickthrough').click(function(){
        $('#declined').load('referrer-ajax2.php #declined2');
    });
});

Can I just add another function such as:
$(document).ready(function() {
$('#clickthrough').click(function(){
    $('#declined').load('referrer-ajax.php2 #declined2', function() {
        $.post('referrer-ajax.php2', { company_selected: $('#refselect').val(), ref_date_from:  $('#ref_date_from').val(), ref_date_to:  $('#ref_date_to').val() },
    });
});
});

Is this the correct way to do things or is there a more sensible way?  Would this not reload the div and THEN post the data (which would be the wrong way round) I assume I can just switch the functions round?
Not really tried anything yet just looking to understand the correct way to do this and develop my knowledge of jQuery.
Appreciate your input guys.

A: yes, you can add it but it should be first post, then load. Buf if you want to show something specific after you post something, just send what you want to show back and don't make another request (load) to get the updated content.


text:
Q: How can I pass value to Perl Subroutine parameters on command line? my test.pl script as below.
#!C:\Perl\bin\perl.exe
use strict;
use warnings;

sub printargs
{
    print "@_\n";
}

&printargs("hello", "world"); # Example prints "hello world"

If I replaced printargs("hello", "world"); with print($a, $b);.
How to pass 'hello' ,'world' to $a , $b when I run perl test.pl hello world at command line, Thanks.

A: Do read about @ARGV in perldoc perlvar.

A: $ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc.
$#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1.

A: The command-line arguments are in the @ARGV array.  Just pass that to your function:
&print( @ARGV );

Probably best to avoid a name like print - might get confused with the built-in function of the same name.

A: You want to access "command line parameters" in Perl.
Basically Perl sees the string you pass after the actual script name as an array named @ARGV.
Here is a brief tutorial: http://devdaily.com/perl/edu/qanda/plqa00001.shtml
Just google "perl command line parameters" for more.

A: Basically, as others said, the @ARGV list is the answer to your question.
Now if you want to go further and define command lines options for your programs, you should also have a loog at getargs.

A: This would also print "hello world" from the command line arguments while passing the data to $a and $b as requested.
#!/usr/bin/perl -w

use warnings;
use strict;

sub printargs($$)
{
    print $_[0] . " " . $_[1] . "\n";
}

my($a,$b) = ($ARGV[0],$ARGV[1]);
printargs($a,$b);


text:
Q: Scatter plot - Connect points even when there is no data in between In my graph i have x-axis data to be shown as months in year like
arrXData = [[NSArray alloc] initWithObjects:@"Jan",@"Feb", @"Mar",@"Apr",@"May", @"Jun", @"Jul",@"Aug", @"Sep", @"Oct", @"Nov", @"Dec",nil];

And Y axis Data as
arrYData = [[NSArray alloc] initWithObjects:@"25",@"30", @"35",@"40",@"50", @"55", @"65",@"70", @"75", @"80", @"85", @"85",  nil];

By using the above static values i am able to plot the scatter plot using core plot.
While doing it dynamically my arrYData will change. I may get some values as nulls.
For example i may not have data for a month "May". In this case my plot getting broke at the month May. Instead i want to connect the points at April and June neglecting the May value.
(Note: I should have all the fields on x-axis even though there is no data for some of the months)
Can some one suggest me how can i do that. Thanks

A: Remove the x-y pairs with NULL values from your data before sending it to the plot. For the given example, return 11 from -numberOfRecordsForPlot: and skip the values for "May" in both data arrays.


text:
Q: How to parse pipe delimited data returned by command FIND? I am having a 5 GB text file which contains pipe | delimited data. Now I have to search for a user given phone number, which is the first data column or the first token of the delimited file containing the phone number, and print the entire row when the phone number matches in the file By using command like:
find "999999999" "F:\....\list.txt"

Now it returns the row containing the phone number and other details in a delimited by | form, e.g.
9999999999|Mark An****|....blah...|....Address...|...

My purpose is to select first token, second token and fourth token from that row and display it. I am not sure whether I can do it directly via find command. So I thought I will use the output of find as an input for further processing. Any suggestions would be welcome.
Background: Later I would like to create a windows UI as an interface for user to search phone numbers, but for now I just want to do it through a batch file. So I need this query working. I first thought of doing it via python but it was taking lot of time and seemed unnecessary as Windows has a find command for quick search and also I would be using windows systems only.


text:
Q: SELECT a category with it sub categories and put them into a DataGridView without category duplicates I'm sorry about the not clear title but I don't know how to explain what I want exactly, so it would be easier with pictures.
Programming language : C#
I have three tables : voltage, catenary_type and type_into_voltage
In the table voltage we have the name of the voltage levels,
in catenary_type the name of the catenary types and
in type_into_voltage we can associate a voltage level to a catenary type.
I want to show in a DataGridView all the catenary types associated to their voltage levels, so I'm actually selecting data with this code that return a DataTable :
internal DataTable SelVoltType()
        {
            DataTable dt = new DataTable();

            using (SqlConnection connection = Program.GetOpenedSqlConnection())
            using (SqlCommand cmd = new SqlCommand("SELECT tiv.id_voltage, volt.name 'Tension', tiv.id_type, cattype.name as 'Types de caténaire' " +
                "FROM [allocation_schematic.types].type_into_voltage tiv " +
                "INNER JOIN [allocation_schematic.types].catenary_type cattype ON cattype.id = tiv.id_type " +
                "INNER JOIN [allocation_schematic.types].voltage volt ON volt.id = tiv.id_voltage; ", connection))
            using (SqlDataAdapter DataAdapter = new SqlDataAdapter(cmd))
                DataAdapter.Fill(dt);

            return dt;
        }

and I put it straight to the DataGridView.DataSource.
It gives me this
But I want it like this without the duplicated voltage levels
Could anyone help me please ? Thanks

A: The easiest way is to remove voltage after the table is created.  Try following :
           string oldVoltage = "";

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string tension = (string)dt.Rows[i]["Tension"];
                if (tension == oldVoltage)
                {
                    dt.Rows[i]["Tension"] = string.Empty;
                }
                else
                {
                    oldVoltage = tension;
                }
            }


text:
Q: Laravel 5 custom login I have write a custom login functionality in an old fashioned way.
1.If the email or password is incorrect it will shows the correct error message (ie invalid email,invalid password,account blocked)
2.If login is ok set a session user with corresponding row from the user table.
3.redirect to different url's according to usertype
Here is the implementation
public function login(Request $request)
    {

        $matches=['email'=>$request->email];
        $users =User::where($matches)->first();
        if($users == FALSE)
        {
          $request->session()->flash(
            'errors',
            'Invalid Email');
           return redirect('adminlogin');
        }
      else if($users->account_status==0)
      {
            $request->session()->flash(
            'errors',
            'Account is blocked please contact admin');
           return redirect('adminlogin');
      }
        else if (!Hash::check($request->password,$users->user_password))
        {
                $request->session()->flash('errors', 'Invalid Password');
                return redirect('adminlogin');
          }
        else
        {
              $request->session()->put('user',$users);
            if($users->user_type == 1)
            {
                $url = 'index';
            }
            else if($users->user_type == 3)
            {
                $url = 'index/package-home';
            }
            else
            {
                return view('errors.404');
            }

            return redirect($url);
        }

    }

Also in every page i've checked the user authentication with session value,if user session is not set it will redirect to login screen.
public function index(Request $request,$page='admin-home',$id=null)
    {
        if(!$request->session()->has('user'))
        {
            $request->session()->flash('errors', 'Session is expired');
            return redirect('adminlogin');
        }
       //load dashboard

 }

So my question is my method is correct for a custom authentication or do i need to anything else??
Note:
 I don't like to use laravel default auth system,because it dosen't provide a way for custom error message or redirect to differnt url's based on usertype (ie admin,super admin etc)


text:
Q: Apache Superset Error: An unexpected occurred while executing the report: list index out of range I was able to successfully setup superset in Compute Engine, i have the Dockerfile, docker-compose.ym and superset_config.py
Everything looks good especially the async queries, but when generating Alerts and Reports every minute the error occured.
Dockerfile
FROM python:3.7.4-slim-buster

LABEL maintainer="reymart.betana@gmail.com"

ENV FLASK_APP="superset"

RUN apt-get update \
  && apt-get install -y unzip wget build-essential python-psycopg2 libpq-dev postgresql libldap2-dev libsasl2-dev libffi-dev libssl-dev git \
  && apt-get clean

RUN wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \
    apt install -y --no-install-recommends ./google-chrome-stable_current_amd64.deb && \
    wget https://chromedriver.storage.googleapis.com/90.0.4430.24/chromedriver_linux64.zip && \
    unzip chromedriver_linux64.zip && \
    chmod +x chromedriver && \
    mv chromedriver /usr/bin && \
    apt autoremove -yqq --purge && \
    apt clean && \
    rm -f google-chrome-stable_current_amd64.deb chromedriver_linux64.zip

RUN pip install --upgrade pip

RUN pip install apache-superset

RUN superset db upgrade

RUN export FLASK_APP=superset

RUN superset fab create-admin --username=admin --firstname=admin --lastname=admin --email=test@gmail.com --password=admin

RUN superset load_examples

RUN superset init

RUN pip install gevent -U

RUN pip install flower

RUN pip install psycopg2

RUN pip install pybigquery

RUN pip install authlib

RUN pip install Pillow

WORKDIR /usr/src/app

COPY superset_config.py superset_config.py

RUN export PYTHONPATH=/usr/src/app/superset_config.py

docker-compose.yml
version: "3.8"

services:

 worker:
  image: superset
  restart: always
  depends_on:
    - superset
  command: celery worker --app=superset.tasks.celery_app:app --pool=gevent --concurrency=500

 flower:
  image: superset
  restart: always
  ports:
   - "5555:5555"
  depends_on:
    - superset
    - worker
    - beat
  command: celery flower --address=0.0.0.0 --app=superset.tasks.celery_app:app

 beat:
  image: superset
  restart: always
  depends_on:
    - superset
  command: celery beat --app=superset.tasks.celery_app:app --pidfile /tmp/celerybeat.pid --schedule /tmp/celerybeat-schedule

 superset:
  image: superset
  restart: always
  ports:
   - "8080:8080"
  command: gunicorn -b 0.0.0.0:8080 -w 10 -k gevent --timeout 120 --limit-request-line 0 --limit-request-field_size 0 "superset.app:create_app()"

Logs
worker_1    | Taking a PNG screenshot or url http://superset.com/superset/dashboard/8/
worker_1    | [2021-05-20 07:15:07,236: INFO/MainProcess] Taking a PNG screenshot or url http://superset.com/superse
t/dashboard/8/
worker_1    | Caching thumbnail: 97160ab7ea43b549ea4ec3827375ca49
worker_1    | [2021-05-20 07:15:07,652: INFO/MainProcess] Caching thumbnail: 97160ab7ea43b549ea4ec3827375ca49
worker_1    | Done caching thumbnail
worker_1    | [2021-05-20 07:15:07,656: INFO/MainProcess] Done caching thumbnail
worker_1    | An unexpected occurred while executing the report: list index out of range
worker_1    | [2021-05-20 07:15:07,665: ERROR/MainProcess] An unexpected occurred while executing the report: list index out of range

Thumbnail cache works fine but when submitting the reports through email "list index out of range" happened.

A: Migrating OP's solution from a comment to an answer

The problem was the SMTP config from superset_config.py was empty had put some values on it.


text:
Q: problem related to date format hi
  I have 2 input dates in different format,so please tell me how to iterate through them
  and convert them into new format using if-else.
  Here is my input:
  String first="Mar 12";
  String second="Feb 23 2010";
  I am trying to convert these different format into new format.
  I have used follwing code:
Date date=new Date();
//I used this format for Mar 12
DateFormat dateFormat1=new SimpleDateFormat("MMM dd");
// Mar 12 gets converted in follwing new format
DateFormat dateFormat2=new SimpleDateFormat("yyyy-MM-dd");
//I used this format for Feb 23 2010
DateFormat dateFormat3=new SimpleDateFormat("MMM dd yyyy");
// Feb 23 2010 gets converted in follwing new format
DateFormat dateFormat4=new SimpleDateFormat("yy-MM-dd");

date=dateFormat1.parse("first");
first=dateFormat2.format(date);
date=dateFormat3.parse("second");
second=dateFormat4.format(date);

now I am facing problem,I am not getting how to parse & convert them in new format using  if-else block.

A: Use string length / no of space in the string  to differentiate the formats.[as you have only two format.]

A: SimpleDateFormat.parse returns null in case of an error. So, you could do something like this:
date = dateFormat1.parse(first, new ParsePosition(0));
if (date == null) {
  date = dateFormat2.parse(first, new ParsePosition(0));
}


text:
Q: Append user text with 'enter' key into ul (chat box) jQuery I am designing a chatbox with jQuery.
I want to attach a li that contains the user text to ul using 'Enter' key
 (without PHP or any server), but it's not working.
My code looks like this:
var txt = "me:"+$(".usertext").val();
var myli = $("
").html(txt);
$('chav_box_in').keypress(function(e)
{
    if ( $(".usertext").val() != "" )
    {
        if (e.keyCode == 13)
        {
            $("#send").click(function(){
                $("#chatlog").append(myli);
                $(".usertext").val("");
            })
        }
    }
});

My chat.

A: You are creating a click event listener on your #send element each time you do a enter keypress, not actually firing that event.
If you are meaning to do a enter keypress and do a Send button click to add the messages you can make a single function and pass it as an argument to jQuery event listener methods
function appendChat(e) {
    var id = e.target.id;
    //variables for testing, you could have all of the
    //comparisons in the 'if' statement, just using these to
    //make the 'if' statement more clear
    var notEmpty = $(".usertext").val() != "",
        isEnterKeypress = e.type == "keypress" && e.keyCode == 13,
        isSendClick = e.type == "click" && id == "send";

    if( notEmpty && (isEnterKeypress || isSendClick) ) {
       var txt = "me:"+$(".usertext").val();
       $("#chatlog").append($("
").html(txt));
       $(".usertext").val("");
    }
}

$("#send").click(appendChat);
$(".chav_box_in").keypress(appendChat);

Demo

function appendChat(e) {
  var id = e.target.id;
  var notEmpty = $(".usertext").val() != "",
      isEnterKeypress = e.type == "keypress" && e.keyCode == 13,
      isSendClick = e.type == "click" && id == "send";

  if( notEmpty && (isEnterKeypress || isSendClick) ) {
    var txt = "me:"+$(".usertext").val();
    $("#chatlog").append($("
").html(txt));
    $(".usertext").val("");
  }
}

$("#send").click(appendChat);
$(".chav_box_in").keypress(appendChat);

<input class="usertext chav_box_in"><button id="send">Send</button>

A: You can't have event inside an event.
Remove that click event from keypress keeping code in there.
 $('.chav_box_in').keypress(function(e)
{

    if (e.keyCode == 13)
    {
        if ($(this).val ()!=""){

                $("#chatlog").append(myli);
                $(".usertext").val("");
        }
        }

});


text:
Q: Stacked bar in R - reversed size and/or percent label I have taken this code from an open source, it is a part of an R Markdown Notebook, and it is supposed to render a stacked bar, and it does, but I think that it reverses the size and/or the labels that represent the percentage (picture attached).
I am new to R, any help is appreciated. Thanks
# Severity

data_severity <- data.frame(
  TIME = as.numeric(),
  SEVERITY = character(),

 PCT = numeric(),
  stringsAsFactors=FALSE)

for(i in 1:max(data$TIME, na.rm = TRUE)) {
  data_severity[nrow(data_severity) + 1,] <- c(i, 1, nrow(data[data$TIME == i & (data$SEVERITY >= 1 & data$SEVERITY <= 3),]) / nrow(data[data$TIME == i,]))
  data_severity[nrow(data_severity) + 1,] <- c(i, 2, nrow(data[data$TIME == i & data$SEVERITY == 4,]) / nrow(data[data$TIME == i,]))
  data_severity[nrow(data_severity) + 1,] <- c(i, 3, nrow(data[data$TIME == i & (data$SEVERITY >= 5 & data$SEVERITY <= 7),]) / nrow(data[data$TIME == i,]))
}

data_severity <- data_severity[order(-data_severity$TIME,data_severity$SEVERITY),]

data_severity$PCT <- as.numeric(data_severity$PCT)

 labels <- round(data_severity$PCT*100, digits=0)

 labels[
 labels<5] <- ""

 labels[
 labels != ""] <- paste(
 labels[
 labels != ""], "%", sep="")

ggbarplot(
  data_severity,
  x = "TIME",
  y = "PCT",
  fill = "SEVERITY",
  position = position_stack(reverse = FALSE),
  color = "white",
  legend = "right",
  xlab = "",
  ylab = "",
  ylim = c(0,1),
  title = "Perceived severity",
  subtitle = "Grouped results, originally rated on scales ranging from 1 (not severe)\nto 7 (very severe).\n",
  font.x = c(10, "plain", "#111111"),
  font.y = c(10, "plain", "#111111"),
  font.label = c(10, "plain", "#111111"),
  font.legend = c(10, "plain", "#111111"),
  font.tickslab = c(10, "plain", "#111111"),
  font.title = c(12, "bold", "#111111"),
  font.subtitle = c(10, "plain", "#111111"),
  label = rev(
 labels),
  lab.pos = "in",
  lab.col = "#444444",
  lab.size = 3.3
) + scale_x_discrete(
  name = "",

 labels = waves
) + scale_fill_manual(
  name = "",

 labels = c("not/less severe", "partly severe ", "more/very severe"),
  values = c("#9ab5c1","#ebedc8","#c1867b")
) + scale_y_continuous(
  expand = c(0, 0),
  breaks=c(0, 0.25, 0.5, 0.75, 1),

 labels = scales::percent
)

A: Found what made the percentages upside down - the list (or vector) of labels was being reversed within the ggbarplot function, just removed the rev and it works fine.
it said:
label =  rev(labels) ...
Thanks to the community for editing my question, I felt welcomed.


text:
Q: How to simulate a tap with code in swift? I want to open a windows on my app, but actually this windows open only when I tap on an element. I want to simulate the tap to open this windows by default or simply to open the window automatically.
I've try:
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))

view.addGestureRecognizer(payOptionTapGue)

view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.paymentOptionTapped(sender:))))

self.paymentOptionTapped()

payOptionTapGue.addGestureRecognizer(payOptionTapGue)

Here is my function that open the windows when I tap:
func getPayTapGue() -> UITapGestureRecognizer{
        let payOptionTapGue = UITapGestureRecognizer()
        payOptionTapGue.addTarget(self, action: #selector(self.paymentOptionTapped(sender:)))
        return payOptionTapGue
    }

A: I think it's better to lunch this function without trigger the tap gesture, so that's why I'll create new question for this.


text:
Q: Is 'jdbcType' necessary in a MyBatis resultMap? When we use Mybatis , in <select> ...</select> statment  I know we need set jdbcType  beacuse  the IN variable maybe null,   but when I see the document of Mybatis,  I found  jdbcType in  <result>...</result> under ResultMap. the document of the
jdbcTpe in  <result>...</result> was:

...  The JDBC type is only required for nullable columns upon insert, update or delete. This is a JDBC requirement, not a MyBatis one. So even if you were coding JDBC directly, you'd need to specify this type – but only for nullable values.

the bold word say only required for nullable columns upon insert, update or delete.
BUT,the element of result is used in select neither insert, update or delete.
so ,is it necessary use jdbcType in <result>...</result> ?

A: Most of the time, no. Why? Read on.
If you want to use a null as a JDBC parameter value you need to specify the jdbcType. That's a restriction of the JDBC specification you can't avoid. Therefore, if there's even a remote possibility a JDBC parameter could have a null value, then yes, specify it.
This does not apply to parameters preprocessed by MyBatis inside MyBatis tags, like the ones you use in the "test" attribute of the < if > tag. Those ones are not JDBC parameters.
Now, for the columns you read. These are the ones you are interested on. The thing is most of the time you don't need them. MyBatis will pick the right JDBC type for you. Well... this has been the case for me 99.999% of the time.
What about the other 0.001%? For some exotic column types -- that you rarely use -- MyBatis may pick the wrong JDBC type for you. The designers of MyBatis thought about this case, and give you the chance of overriding it. I think I remember an XML type database column that MyBatis was unsuccessfully trying to read as a VARCHAR, but I don't remember which database.
Bottom line, don't use it when reading columns, unless MyBatis reads exotic data type columns (XML, UUID, POINT, etc.) the wrong way.


text:
Q: logic words alternative I am using logic words to design circuits like ALU, on windows in class and my pc itś running only ubuntu, my question is how I can open this extension (.cct) on linux, please not tell me about virtual machine.
thanks.


text:
Q: Access localhost from docker container I have an assignment to set up 3 docker container on localhost:8081, localhost:8082 and localhost:8083 which i've done succesfully.Then there is a last container that is a java app on localhost:8080 and it needs to send requests using HttpClient and HttpRequest to the other containers i've done this creating a bridge with "docker network create web_server --driver brigde" and im running the containers with --network web_server and this way they can communicate using the container names and it works. But my teacher told me to send the request to http://localhost:8081, 8082 etc. Is there a way to make containers access localhost? Im using docker for linux

A: On Linux containers, your can access the host using IP address 172.17.0.1. So from inside your Java app you should be able to reach the other containers on 172.17.0.1:8081, 172.17.0.1:8082 and 172.17.0.1:8083. That's equivalent to using localhost:8081, localhost:8082 and localhost:8083 on your host machine.

A: add --network="host" on your docker run command, then 127.0.0.1 in your docker container will point to your docker host. (only work for docker on linux or windows container)
For docker for mac or docker for windows just connect services using the host
host.docker.internal instead of 127.0.0.1


text:
Q: What is known about computing all binary error correcting codes of given parameters? Define a binary $(n, M, 2e + 1)$ code to be a code $C$ having $M$ code words in $\mathbb{F}_2^n$ whose minimum distance is $2e + 1$.
Are there any sources about using algorithms to find all given codes of certain parameters? I suspect that there are some ways to reduce the search space or some other clever techniques for finding all codes that are more subtle than a brute force search of all possible $M$ subsets of $\mathbb{F}^n_2$ and then computing the Hamming distance for every such subset. Certainly I would still expect that such a problem cannot be solved in polynomial time. I could not however, find any good sources on this material and was wondering if anyone knew of any. Partial answers or computational results and methods related to special classes of binary codes are welcome as well.

A: People are generally only interested in "good" codes. Which means maximum minimum distance $d$ for given $n,M$ or minimum length for given $M,d$ etc. Let $A(n,d)$ be the maximum $M$ for which an $(n,M,d)$ code exists.
Even for such codes the computational complexity of the problem is overwhelming. There are too many bad codes (if $d$ is small relative to $(n,M)$ as determined by bounds such as Hamming, Plotkin, Gilbert-Varshamov the search space is way too big).
There is the idea of code equivalence under the automorphism group of the code, which is used to reduce search complexity. At a very basic level if you find a code with certain parameters, and apply a permutation to the coordinates, this gives another code with the same paramaters. If the code has algebraic structure, you can do more.
The site http://www.codetables.de/ maintained by Markus Grassl has some tables of good codes, for example, and links to other tables. If you restrict to, for example, self-dual codes or codes with only two nonzero weights, etc. you can do more.
The tables by Litsyn, Rains and Sloane at http://www.eng.tau.ac.il/~litsyn/tableand/index.html of lower bounds on $A(n,d)$ may not have been updated in a long time. But a snippet from that site gives an idea about how hard the problem is.

Memo to algorithms specialists:
  This file contains a large number of clique-finding problems. Construct the graph whose vertices represent binary strings of length $n.$ Join two vertices by an edge if and only if the Hamming distance bewteen the strings is at least $d.$ Then what we are interested in is the quantity $A(n,d),$ the size of the largest clique in this graph.
  This file contains a large number of lower bounds on this clique size. If you can improve any of these entries or establish the optimality of any entries that we don't already know are optimal (these are indicated by a period after the number) please let us know (send us the clique too!).

Edit: I haven't used it for this purpose but the Magma package http://magma.maths.usyd.edu.au/calc/can do computations related to automorphism groups of codes. See here for details. There is a publicly accessible calculator at the first link I gave, but the memory and computation time allowed is limited. I am less familiar with Pari/GP but they may have a similar functionality.


text:
Q: UICollectionView not displayed to view I have been stuck on this problem for nearly a week now. I have even reverted my code and wrote the same code as some tutorials but I cannot seem to get my UICollectionView to be displayed to the view for the life of me.  I have a lot of other code going on in my view controllers so I am going to display the code that pertains to the UICollectionView. This is what I have so far:
view controller:
class UARTModuleViewController: UIViewController, CBPeripheralManagerDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupMenuBar()
    }

    let menuBar: MenuBar = {
        let mb = MenuBar()
        return mb
    }()

    private func setupMenuBar() {
        view.addSubview(menuBar)
        let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":menuBar])
        let verticalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0(100)]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":menuBar])
        view.addConstraints(horizontalConstraint)
        view.addConstraints(verticalConstraint)
    }
}

MenuBar.swift:
class MenuBar : UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = UIColor.red
        cv.dataSource = self
        cv.delegate = self
        return cv
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.addSubview(collectionView)
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MenuCell")

        //took out constraints here just to make the warning mentioned below easier to follow.
    }

I do have my protocols implemented but I didn't add them just to save the amount of code I'm posting. I do get this warning after the UARTModuleViewController loads :

[LayoutConstraints] Unable to simultaneously satisfy constraints.

I've tried reasoning through it and can't seem to come to a solution. I do have a cell class as well but thought it was not necessary to include since I can't get the UICollectionView to be displayed. The only other thing that I may add is that I have a UIImageView in the middle of the view that I added in story board and put constraints on like so:
Does anyone have any suggestions as to what I may be doing wrong? Thanks in advance for any help or advice that can be given.

A: According to comments:

*

*First of all, every time you use constraint in code, you must set translatesAutoresizingMaskIntoConstraints = false to the view you want to add constraint.

*You're not telling the collection view to fill entire MenuBar space.

*Constraints applied to MenuBar in setupMenuBar are not enaugh to determine the size and position of the view.

These are changes you should apply to tell the MenuBar to fill width, be 60 pt height and to position on bottom of the screen:
private func setupMenuBar() {
    view.addSubview(menuBar)
    menuBar.translatesAutoresizingMaskIntoConstraints = false // this will make your constraint working
    menuBar.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true // every constraint must be enabled.
    menuBar.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
    menuBar.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
    menuBar.heightAnchor.constraint(equalToConstant: 60).isActive = true
}

To tell the collection view to fill entire MenuBar view do this in MenuBar init(frame:) method:
override init(frame: CGRect) {
    super.init(frame: frame)

    self.addSubview(collectionView)
    collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MenuCell")

    collectionView.translatesAutoresizingMaskIntoConstraints = false
    collectionView.topAnchor.constraint(equalTo: topAnchor).isActive = true
    collectionView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    collectionView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
    collectionView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true

    //took out constraints here just to make the warning mentioned below easier to follow.
}

As you can see in my code, I usually use "anchor" methods to apply constraint because are easier than visual format.


text:
Q: C# Unity EditorTool Frame-Rate Issues I'm writing a tool which gives the user quick access to all their prefabs, and easy ways to place them in the scene. I've used it for hours without many problems. A performance bug crept in overnight - and now the GUI FPS is slowed to a crawl, no matter what I comment out. I can replace the entire OnToolGUI() function with a single GUI.Button() call and that button will have a reaction delay upwards of 1s. UI interactions like clicks still happen immediately. After moving the script to a few other projects, the same bug cropped up after a few seconds or minutes of use. Here's the whole thing - at this point I'd appreciate just knowing what happens when somebody else uses it, but any suggestions on this weird frame-rate issue would be great.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.EditorTools;
using UnityEngine.SceneManagement;
using UnityEditor.SceneManagement;
using UnityEditor.Experimental.SceneManagement;

[EditorTool("Placer Tool")]
class Placer : EditorTool
{
    bool verbose = true;
    GUIContent m_IconContent;
    public override GUIContent toolbarIcon { get { return m_IconContent; } }

    Texture2D magnetIcon;
    Texture2D gridIcon;
    Texture2D toolIcon;
    float grid = 1f;
    bool snapToGrid = false;
    bool forceStickySurfaces = false;
    bool editorVisible = true;
    List<string> filters = new List<string>();
    List<string> currentFilters = new List<string>();
    Texture2D whiteTexture;
    Texture2D backgroundTexture;

    void OnEnable()
    {
        whiteTexture = Swatch( new Color( 1,1,1,1f ) );
        backgroundTexture = Swatch( new Color( 0.24f, 0.24f, 0.24f, 1f ) );
        magnetIcon = MagnetIcon;
        gridIcon = GridIcon;
        toolIcon = ToolIcon;

        m_IconContent = new GUIContent()
        {
            image = toolIcon,
            text = "Placer Tool",
            tooltip = "Placer Tool"
        };

        GetStyles();
        GetPreviewMaterial();
        GetPlaceables();
        UpdateFilterResults();
    }

    public override void OnToolGUI( EditorWindow window )
    {
        // verbose = false;

        if ( !(window is SceneView sceneView) ) return;
        else
        {
            CheckForNewResources();
            GetMouseInfo();
            Handles.BeginGUI();
            DrawGUI( window );
            Handles.EndGUI();

            if( MouseIsInSceneView() )
            {
                if( Event.current.button == 0 && GUI.Button( new Rect( mouseInfo.screenPos.x - 16, mouseInfo.screenPos.y - 16, 32,32 ), "", GUIStyle.none ) )
                { // Detecting clicks is done by drawing a button under the mouse - using the default method caused unnecessary object selections
                    if( Event.current.control && mouseInfo.collider != null )
                    { // Destroy object
                        Undo.RegisterFullObjectHierarchyUndo( mouseInfo.collider.gameObject, "Unplace "+mouseInfo.collider.gameObject.name );
                        DestroyImmediate( mouseInfo.collider.gameObject );
                    }
                    else if( selectedIndex > -1 )
                    { // Create object
                        previewMaterial.color = Color.green;
                        GameObject newObj = PrefabUtility.InstantiatePrefab( placeables[selectedIndex].originPrefab, mouseInfo.scene ) as GameObject;
                        if( mouseInfo.isInPrefab ) StageUtility.PlaceGameObjectInCurrentStage( newObj );
                        Undo.RegisterCreatedObjectUndo( newObj, "Place "+placeables[selectedIndex].originPrefab.name );
                        newObj.transform.position = mouseInfo.worldPos;
                        newObj.transform.rotation = rotation;
                    }
                }

                if( Event.current.isScrollWheel && Event.current.type == EventType.ScrollWheel )
                { // Adjusting the primary rotation according to scrollwheel movement
                    primaryRotation += Event.current.delta.y > 0 ? 15 : -15;
                    Event.current.Use();
                }

                // Getting the base rotation from the mouse normal if necessary/possible
                if( forceStickySurfaces && mouseInfo != null ) rotation = Quaternion.FromToRotation( Vector3.up, mouseInfo.worldNormal );
                else rotation = Quaternion.identity;

                if( Event.current.control && mouseInfo.collider != null )
                { // Delete mode - matching the preview mesh position/rotation to the object to be deleted
                    GameObject rootPrefabAtMouse = PrefabUtility.GetOutermostPrefabInstanceRoot( mouseInfo.collider.gameObject );

                    if( rootPrefabAtMouse != null )
                    {
                        previewMaterial.color = new Color(1,0,0,0.3f);
                        rotation = rootPrefabAtMouse.transform.rotation;
                        position = rootPrefabAtMouse.transform.position;
                    }
                }
                else
                { // Standard preview mode - rotation is adjusted using the primary rotation about the Y axis
                    previewMaterial.color = new Color(0,1,0,0.3f);
                    rotation *= Quaternion.Euler( 0, primaryRotation, 0 );
                }

                if( Event.current.type == EventType.Layout && lastRenderedFrame != Time.renderedFrameCount )
                { // Drawing object preview
                    DrawObjectPreview( Camera.current );
                    lastRenderedFrame = Time.renderedFrameCount;
                }
            }
        }
    }

    Material previewMaterial;

    void GetPreviewMaterial()
    {
        if( verbose ) Debug.Log( "Creating preview material" );
        previewMaterial = new Material( Shader.Find( "Universal Render Pipeline/Lit" ) );
    }

    GUIStyle boldStyle;
    GUIStyle focussedStyle;
    GUIStyle normalStyle;
    Texture2D transparentBg;
    Texture2D hoverBg;

    void GetStyles()
    {
        if( verbose ) Debug.Log( "Fetching style" );
        if( normalStyle == null || boldStyle == null || focussedStyle == null )
        {
            transparentBg = Swatch( new Color(0,0,0,0) );
            hoverBg = Swatch( new Color(1,1,1,0.25f) );

            normalStyle = new GUIStyle( GUIStyle.none );
            normalStyle.fontStyle = FontStyle.Normal;
            normalStyle.alignment = TextAnchor.MiddleCenter;

            normalStyle.normal.textColor = Color.Lerp( Color.gray, Color.white, 0.5f );
            normalStyle.normal.background = transparentBg;
            normalStyle.hover.background = hoverBg;
            normalStyle.hover.textColor = Color.white;

            boldStyle = new GUIStyle( normalStyle );
            boldStyle.fontStyle = FontStyle.Bold;

            focussedStyle = new GUIStyle( boldStyle );

            focussedStyle.normal.textColor = Color.white;
            focussedStyle.normal.background = hoverBg;
            focussedStyle.hover.background = hoverBg;
        }
    }

    int lastRenderedFrame;
    MousePositionInfo mouseInfo;

    public void GetMouseInfo()
    {
        mouseInfo = EditorMouseInfo;

        if( mouseInfo != null && snapToGrid )
        {
            mouseInfo.worldPos = Vector3Int.RoundToInt( mouseInfo.worldPos/grid );
            mouseInfo.worldPos *= grid;
        }

        if( mouseInfo != null ) position = mouseInfo.worldPos;
    }

    List<Placeable> placeables = new List<Placeable>();
    int selectedIndex = -1;

    public void GetPlaceables()
    {
        if( verbose ) Debug.Log( "Fetching prefabs" );

        List<GameObject> allGos = new List<GameObject>();
        placeables.Clear();
        filters.Clear();
        filters.Add( clearFilterSymbol );

        string head = Application.dataPath;
        List<string> subPaths = new List<string>( System.IO.Directory.GetDirectories( head ) );
        bool allDiscovered = false;

        // Find all subidrectories within the asset folder
        while( allDiscovered == false )
        {
            List<string> newSubPaths = new List<string>();
            allDiscovered = true;
            foreach( string subPath in subPaths )
            {
                string[] subDirectories = System.IO.Directory.GetDirectories( subPath );

                if( subDirectories.GetLength(0) > 0 )
                foreach( string subDirectory in subDirectories )
                if( subPaths.Contains( subDirectory ) == false )
                {
                    newSubPaths.Add( subDirectory );
                    allDiscovered = false;
                }
            }
            subPaths.AddRange( newSubPaths );
        }

        // Iterate list in reverse so each gameobject records its full path to the filter list
        for( int s = subPaths.Count-1; s >= 0; s-- )
        {
            string resourcePath = subPaths[s].Replace( head+"\\", "" );
            resourcePath = "Assets\\"+resourcePath;
            List<string> pathFilters = new List<string>( resourcePath.Split( "\\".ToCharArray()) );
            pathFilters.Remove( "Assets" );

            string[] guids = AssetDatabase.FindAssets("t:prefab",new string[]{ resourcePath });
            bool addFiltersForPath = false;

            foreach( string guid in guids )
            {
                GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>( AssetDatabase.GUIDToAssetPath( guid ) );

                if( go != null && allGos.Contains( go ) == false )
                {
                    placeables.Add( new Placeable( pathFilters, go ) );
                    allGos.Add( go );
                    addFiltersForPath = true;
                }
            }

            if( addFiltersForPath )
            foreach( string filter in pathFilters )
            if( filters.Contains( filter ) == false )
            {
                filters.Add( filter );
            }
        }
    }

    int lastResourceCount = 0;

    void CheckForNewResources()
    {
        int newResourceCount = Resources.LoadAll<GameObject>("").GetLength(0);

        if( lastResourceCount != newResourceCount )
        {
            if( verbose ) Debug.Log( "New prefab list requested by file change" );

            GetPlaceables();
            UpdateFilterResults();
            lastResourceCount = newResourceCount;
        }
    }

    Quaternion rotation = Quaternion.identity;
    Vector3 position = Vector3.zero;
    float primaryRotation = 0;
    Mesh previewMesh;

    void GetPreviewMesh()
    {
        if( verbose ) Debug.Log( "New preview mesh being generated" );

        if( previewMesh == null ) previewMesh = new Mesh();
        MeshFilter[] meshFilters = placeables[selectedIndex].originPrefab.GetComponentsInChildren<MeshFilter>();

        if( meshFilters.GetLength(0) > 1 )
        {
            CombineInstance[] combines = new CombineInstance[meshFilters.GetLength(0)];

            for( int m = 0; m < meshFilters.GetLength(0); m++ )
            { // SuperSimplify removes submesh data from the existing mesh, the result of which is given as a combine
                combines[m].mesh = SuperSimplify( meshFilters[m].sharedMesh );
                combines[m].transform = Matrix4x4.TRS( meshFilters[m].transform.localPosition, meshFilters[m].transform.localRotation, Vector3.one );
            }

            previewMesh.CombineMeshes( combines, true, true, false );
            previewMesh = SuperSimplify( previewMesh );
        }
        else if( meshFilters.GetLength(0) == 1 ) previewMesh = SuperSimplify( meshFilters[0].sharedMesh );
        else previewMesh.Clear( false );
    }

    void DrawObjectPreview( Camera cam )
    { // Uses Graphics.DrawMesh which generates garbage. This is mostly handled by the in-built GC; this method is still sub-optimal
        if( selectedIndex > -1 && previewMaterial != null )
        Graphics.DrawMesh( previewMesh, position, rotation, previewMaterial, LayerMask.NameToLayer( "Default" ) );
    }

    // All GUI below this point
    Rect widgetRect = new Rect( 0,0,0,0 );
    float lineHeight = 20;
    float panelWidth = 128;
    int accentThickness = 4;
    enum FilterMode { Any, All };
    FilterMode filterMode = FilterMode.Any;
    string gridString = "0.25";
    Color backgroundColor = new Color( 0.2f,0.2f,0.2f,0.6f );
    string clearFilterSymbol = "⊗";

    void DrawGUI( EditorWindow window )
    {
        lineHeight = 20;
        widgetRect = new Rect( 0,0,lineHeight,lineHeight );

        if( DoWidget( Widget.Button, false, "", "Toggle Placer UI", null, toolIcon ) ) editorVisible = !editorVisible;

        if( editorVisible )
        {
            DrawToolControls( window );
            DrawFilterSelect( window );
            DrawPlaceableSelect( window );
        }
    }

    void DrawToolControls( EditorWindow window )
    {
        widgetRect.x = widgetRect.x + widgetRect.width;
        widgetRect.y = 0;
        widgetRect.width = panelWidth * 0.2f;

        if( DoWidget( Widget.Toggle, forceStickySurfaces, "", "Toggle stick to surface to normal", null, magnetIcon ) ) forceStickySurfaces = !forceStickySurfaces;

        widgetRect.x += widgetRect.width;
        if( DoWidget( Widget.Toggle, snapToGrid, "", "Toggle grid snap", null, gridIcon ) ) snapToGrid = !snapToGrid;
        widgetRect.x += widgetRect.width;

        widgetRect.width = panelWidth - ( widgetRect.x + lineHeight );
        GUI.DrawTexture( new Rect( widgetRect.position+Vector2.left,widgetRect.size+(Vector2.right*2) ), backgroundTexture );
        gridString = GUI.TextField( widgetRect, gridString );

        if( gridString != "" )
        {
            try{ grid = Mathf.Clamp( float.Parse( gridString ), 0.0000001f, Mathf.Infinity ); }
            catch{}
        }
        widgetRect.x = panelWidth - lineHeight;
        widgetRect.width = lineHeight;

        if( DoWidget( Widget.Repeat, false, "||", "", null ) )
        {
            panelWidth = Event.current.mousePosition.x + lineHeight/2;
        }

        panelWidth = Mathf.Clamp( panelWidth, 120, 1024 );
    }

    void DrawFilterSelect( EditorWindow window )
    {
        widgetRect.y = 0;
        widgetRect.x += widgetRect.width;

        widgetRect.width = boldStyle.CalcSize( new GUIContent( "Any" ) ).x + 8;
        if( DoWidget( Widget.Button, false, filterMode.ToString(), "Require all filters / Require any filters" ) ) filterMode = (FilterMode)1-(int)filterMode;
        widgetRect.x += widgetRect.width;

        for( int f = 0; f < filters.Count; f++ )
        {
            string filter = filters[f];
            bool isCurrent = currentFilters.Contains( filter );

            widgetRect.width = boldStyle.CalcSize( new GUIContent( filter ) ).x + 8;

            if( DoWidget( Widget.Filter, isCurrent, filter, "", f==0?null:new Color[]{ FilterColor(f) } ) )
            {
                if( filter == clearFilterSymbol ) currentFilters.Clear();
                else if( isCurrent ) currentFilters.Remove( filter );
                else currentFilters.Add( filter );

                UpdateFilterResults();
            }

            widgetRect.x += widgetRect.width;

            if( widgetRect.x + widgetRect.width > ( window.position.width - panelWidth ) )
            {
                widgetRect.x = panelWidth;
                widgetRect.y += lineHeight;
            }
        }

        widgetRect.height = lineHeight;
    }

    public Vector2 placeableScrollPos = Vector2.zero;
    float placeableLineHeight = 0.75f;

    void DrawPlaceableSelect( EditorWindow window )
    {
        if( this.filterResults.Contains( null ) ) UpdateFilterResults();

        widgetRect.position = new Vector2(0, lineHeight);
        widgetRect.width = panelWidth;
        widgetRect.height = lineHeight*placeableLineHeight;

        Rect scrollWindow = new Rect( widgetRect.position, new Vector2( panelWidth, window.position.height-(widgetRect.y+widgetRect.height) ) );

        Rect scrollContent = new Rect( widgetRect );
        scrollContent.width -= 16;
        scrollContent.height = lineHeight*placeableLineHeight * filterResults.Count;

        placeableScrollPos = GUI.BeginScrollView( scrollWindow, placeableScrollPos, scrollContent );

        for( int p = 0; p < filterResults.Count; p++ )
        {
            int originalIndex = filterResultIndexes[p];
            List<Color> filterColors = new List<Color>();

            foreach( string filter in filterResults[p].filters )
            {
                filterColors.Add( FilterColor( filters.IndexOf( filter ) ) );
            }

            GUIStyle selectedStyle = selectedIndex == originalIndex ? boldStyle : normalStyle;

            if( DoWidget( Widget.Prefab, selectedIndex == originalIndex, filterResults[p].originPrefab.name, "", filterColors.ToArray() ) )
            {
                selectedIndex = originalIndex;
                GetPreviewMesh();
            }

            widgetRect.y += widgetRect.height;
        }

        GUI.EndScrollView();
    }

    List<Placeable> filterResults = new List<Placeable>();
    List<int> filterResultIndexes = new List<int>();

    void UpdateFilterResults()
    {
        if( verbose ) Debug.Log( "Updating filter results" );
        filterResults.Clear();
        filterResultIndexes.Clear();

        for( int p = 0; p < placeables.Count; p++ )
        {
            bool isInFilter = filterMode == FilterMode.Any ? ContainsAny( currentFilters, placeables[p].filters ) : ContainsAll( placeables[p].filters, currentFilters );

            if( currentFilters.Count == 0 || isInFilter )
            {
                filterResults.Add( placeables[p] );
                filterResultIndexes.Add( p );
            }
        }
    }

    // Items below this point are utilities to the above functions

    bool MouseIsInSceneView()
    {
        if( SceneView.currentDrawingSceneView != null && SceneView.currentDrawingSceneView.camera != null && mouseInfo != null )
        {
            Vector2 mouseUV = SceneView.currentDrawingSceneView.camera.ScreenToViewportPoint( mouseInfo.screenPos );

            return ( mouseUV.x > 0 && mouseUV.y > 0 && mouseUV.x < 1 && mouseUV.y < 1 );
        }
        else return false;
    }

    Vector3 EditorMousePos { get
    {
        Vector3 mousePosition = Event.current.mousePosition;
        mousePosition.y = SceneView.currentDrawingSceneView.camera.pixelHeight - mousePosition.y;
        mousePosition = SceneView.currentDrawingSceneView.camera.ScreenToWorldPoint(mousePosition);
        mousePosition.y = -mousePosition.y;
        return mousePosition;
    }}

    MousePositionInfo EditorMouseInfo { get
    {
        PrefabStage stage = PrefabStageUtility.GetCurrentPrefabStage();
        bool inPrefab = stage != null;
        Scene scene = inPrefab ? stage.scene : EditorSceneManager.GetActiveScene();
        PhysicsScene physics = PhysicsSceneExtensions.GetPhysicsScene(scene);
        Vector3 mousePosition = Event.current.mousePosition;
        Ray ray = HandleUtility.GUIPointToWorldRay(mousePosition);
        RaycastHit hitInfo;
        LayerMask mask = LayerMask.GetMask( "Default" );
        bool hit = physics.Raycast( ray.origin, ray.direction, out hitInfo, 1024, mask, QueryTriggerInteraction.Ignore );

        if( hit )  return new MousePositionInfo( mousePosition, hitInfo.point, hitInfo.normal, hitInfo.collider, scene, inPrefab );
        else return new MousePositionInfo( mousePosition, RayToPlane( ray ), Vector3.up, null, scene, inPrefab );
    }}

    Texture2D Swatch( Color color )
    {
        Texture2D swatch = new Texture2D(1,1);
        swatch.SetPixel( 0,0,color );
        swatch.Apply();
        return swatch;
    }

    Mesh SuperSimplify( Mesh mesh )
    {
        Mesh newMesh = new Mesh();

        newMesh.vertices = mesh.vertices;
        newMesh.normals = mesh.normals;
        newMesh.triangles = mesh.triangles;
        newMesh.uv = mesh.uv;

        return newMesh;
    }

    Color FilterColor( int filterIndex )
    {
        float hue = (float)filterIndex/filters.Count;
        hue += filterIndex%2==0?0.5f:0;
        hue %= 1;
        return Color.HSVToRGB( hue,0.7f,0.8f );
    }

    Vector3 RayToPlane( Ray ray )
    {
        Plane hPlane = new Plane(Vector3.up, Vector3.zero);
        float distance = 0;
        if( hPlane.Raycast(ray, out distance) ) return ray.GetPoint( distance );
        else if( hPlane.Raycast(new Ray( ray.origin, -ray.direction ), out distance) ) return ray.GetPoint( distance );
        else return ray.origin;
    }

    Texture2D ToolIcon{ get
    {
        Vector2 editorIconSize = EditorGUIUtility.GetIconSize();
        int max = editorIconSize == Vector2.zero ? 16 : Mathf.Max( Mathf.RoundToInt( editorIconSize.x ), Mathf.RoundToInt( editorIconSize.y ) );
        Texture2D newIcon = new Texture2D(max,max);

        for( int x = 0; x < max; x++ ){
        for( int y = 0; y < max; y++ ){
            bool set = false;

            Vector2 direction = new Vector2(x,y) - new Vector2( (max/2f)-0.5f,(max/2f)-0.5f);
            float range = direction.magnitude;
            float angle = Vector2.SignedAngle( Vector2.up, direction );
            angle = angle < 0 ? 360-angle : angle;

            if( range <= max/2 )
            {
                // Rosette
                if( range > ( max/2 ) - ( max/16 ) ) set = true;
                // Hammer head
                if( x > (max-y) && y < ( x+(max/2) ) && y > ( x-(max/2) ) && x < (max-y+(max/2) )-2 ) set = true;
                // Hammer handle
                if( Mathf.Abs(x-y) < max/8 && x < (max-y+(max/2) ) ) set = true;
            }

            newIcon.SetPixel( x,y,set?Color.Lerp( Color.white,Color.gray,0.5f ) : new Color(0,0,0,0) );
        }}
        newIcon.Apply();

        return newIcon;
    }}

    Texture2D MagnetIcon{ get
    {
        Vector2 editorIconSize = EditorGUIUtility.GetIconSize();
        int max = editorIconSize == Vector2.zero ? 16 : Mathf.Max( Mathf.RoundToInt( editorIconSize.x ), Mathf.RoundToInt( editorIconSize.y ) );
        Texture2D newIcon = new Texture2D(max,max);

        for( int x = 0; x < max; x++ ){
        for( int y = 0; y < max; y++ ){
            bool set = false;

            Vector2 direction = new Vector2(x,y) - new Vector2( (max/2f)-0.5f,(max/2f)-0.5f);
            float range = direction.magnitude;
            float angle = Vector2.Angle( Vector2.one, direction );

            float outRadius = ( max/2f );
            float inRadius = (max/4f);

            if( range < outRadius && !( x < max/3f && y < max/3f ) )
            {
                // Rosette
                if( range > inRadius )
                {
                    if( angle < 120 ) set = true;
                    else if( angle < 160 && (x+y)%2==1 ) set = true;
                }
            }

            newIcon.SetPixel( x,y,set?Color.Lerp( Color.white,Color.gray,0.5f ) : new Color(0,0,0,0) );
        }}
        newIcon.Apply();

        return newIcon;
    }}

    Texture2D GridIcon{ get
    {
        Vector2 editorIconSize = EditorGUIUtility.GetIconSize();
        int max = editorIconSize == Vector2.zero ? 16 : Mathf.Max( Mathf.RoundToInt( editorIconSize.x ), Mathf.RoundToInt( editorIconSize.y ) );
        Texture2D newIcon = new Texture2D(max,max);

        for( int x = 0; x < max; x++ ){
        for( int y = 0; y < max; y++ ){
            bool set = false;

            Vector2 direction = new Vector2(x,y) - new Vector2( (max/2f)-0.5f,(max/2f)-0.5f);
            float range = direction.magnitude;
            float angle = Vector2.Angle( Vector2.one, direction );

            if( (x+(max/3)) % ( max/2 ) < 2 || (y+(max/3)) % ( max/2 ) < 2 ) set = true;

            newIcon.SetPixel( x,y,set?Color.Lerp( Color.white,Color.gray,0.5f ) : new Color(0,0,0,0) );
        }}
        newIcon.Apply();

        return newIcon;
    }}

    bool ContainsAny( List<string> values, List<string> query )
    {
        foreach( string strA in query )
        if( values.Contains( strA ) ) return true;

        return false;
    }

    bool ContainsAll( List<string> values, List<string> query )
    {
        foreach( string strA in query )
        if( values.Contains( strA ) == false ) return false;

        return true;
    }

    class MousePositionInfo
    {
        public Vector3 screenPos;
        public Vector3 worldPos;
        public Vector3 worldNormal;
        public Collider collider;
        public Scene scene;
        public bool isInPrefab;

        public MousePositionInfo( Vector3 screenPos, Vector3 worldPos, Vector3 worldNormal, Collider collider, Scene scene, bool inPrefab )
        {
            this.screenPos = screenPos;
            this.worldPos = worldPos;
            this.worldNormal = worldNormal;
            this.collider = collider;
            this.scene = scene;
            this.isInPrefab = inPrefab;

        }
    }

    class Placeable
    {
        public List<string> filters;
        public GameObject originPrefab;

        public Placeable( List<string> filters, GameObject originPrefab )
        {
            this.filters = filters;
            this.originPrefab = originPrefab;
        }
    }

    // Items below this point are GUI utilities

    enum Widget { Filter,Prefab,Button,Toggle,Repeat }

    bool DoWidget( Widget type, bool isActive, string widgetText, string widgetTooltip = "", Color[] widgetColors = null, Texture2D widgetIcon = null )
    { // Uses the current widgetRect to draw a widget
        bool iconOnly = ( ( type == Widget.Button || type == Widget.Toggle || type == Widget.Repeat ) && widgetIcon != null );

        GUIStyle widgetStyle = type == Widget.Filter ? boldStyle : normalStyle;
        if( isActive ) widgetStyle = focussedStyle;

        GUIContent widgetContent = new GUIContent()
        {
            image = widgetIcon,
            text = iconOnly ? "" : widgetText,
            tooltip = widgetTooltip
        };

        GUI.DrawTexture( widgetRect, backgroundTexture );
        int colorCount = widgetColors != null ? widgetColors.GetLength(0) : 0;

        if( ( type == Widget.Filter || type == Widget.Prefab ) && widgetColors != null && colorCount > 0 )
        {
            Rect accentRect = new Rect( widgetRect );

            for( int c = 0; c < colorCount; c++ )
            {
                if( type == Widget.Filter )
                {
                    if( isActive == false )
                    {
                        accentRect.y = ( widgetRect.y + widgetRect.height ) - accentThickness;
                        accentRect.height = accentThickness;
                    }
                }
                else
                {
                    accentRect.x = ( widgetRect.x + widgetRect.width ) - ( (c+1) * accentThickness );
                    accentRect.width = accentThickness;
                }

                GUI.color = widgetColors[c];
                GUI.DrawTexture( accentRect, whiteTexture );
            }
        }
        GUI.color = Color.white;

        if( type == Widget.Repeat ) return GUI.RepeatButton( widgetRect, widgetContent, widgetStyle );
        else return GUI.Button( widgetRect, widgetContent, widgetStyle );
    }
}


text:
Q: How to express type of "slice of (string or 'other such slice')" How can I express in Go a type which is "a list of (strings or other such lists)"? Basically the good ol' "tree represented as infinitely nested lists of lists and something as values (strings in this example)"
I'm looking for the simplest possible representation of an S-expression (which itself would be the simplest of an AST), which in Python would look like this:
sexp1 = ["+", "x", "y", ["*", "10", "myVal"]]
sexp2 = ["foo" "bar" "baz"]
sexp3 = [ [ [["gooo"], "moo"] ], "too", ["yoo", "2"] ]

What type would all these expressions have in Go? Obviously [][]string doesn't work, as this doesn't work:
func makeSexp(parserName string, values ...[][]string) [][]string {
    return append([]string{parserName}, values...)
}

(Compile errors: 1. cannot use values (type [][][]string) as type []string in append, 2. cannot use append([]string literal, values...) (type []string) as type [][]string in return argument.)
...while the fully untyped version works (but I don't want to completely give up type safety!):
func makeSexp(parserName string, values ...interface{}) interface{} {
    return append([]interface{}{parserName}, values...)
}

A: Unfortunately, Go doesn't support algebraic data types, so your best bet to make it type-safe is to create an unexported interface, and make two implementations of it:
type sExp interface {
    sExp()
}

type s string

func (s) sExp() {}

type l []sExp

func (l) sExp() {}

// ...
var sexp1 sExp = l{s("+"), s("1"), s("2"), l{s("*"), s("10"), s("myVal")}}

This is basically how Protobuf compilers deal with e.g. oneof cases. This will still need a lot of type switches or type assertions to work with, but at least you can be sure that nothing outside of your module will be able to tinker with it.
Playground: https://play.golang.org/p/KOvFqJEvxZ.


text:
Q: Creating map of New Zealand with coordinates in Folium I want to create a map of New Zealand in Folium Python. I want to show the map of New Zealand. Later on I will add the markers on the map. I started coding as follow:
nz_map = folium.Map(location=(lat,long), zoom_start=12)
display(nz_map)

I don't know exactly the coordinates of NZ. I googled the NZ coordinates and entered 40.9006 (S), 174.8860 (E). When I ran the code it shows a blank image as shown below:

I'm not sure where I made the mistake. Could anyone help me in fixing the issue?

A: As stated by gene, it seems like you had longitude as a negative coordinate, this correctly shows NZ.
lat = -40.9006
long =  174.8860
nz_map = folium.Map(location=[lat,long], zoom_start=6)


text:
Q: Is it safe to clean temporary files produced by Hudson? I tried to clean this directory in my vitural machine:
C:\Documents and Settings\Administrator\Local Settings\Temp

However, this VM is a Hudson Slave, and I found it full with directories of this kind: hudson-remoting57575653437742745725
and which contains such a tree: hudson-remoting57575653437742745725\com\sun\jna\win32-x86
and the final directory contains this dll: jnidispatch.dll
Is it safe to delete these kind of directories?
If it is safe to delete clean Temp directory, when can I include the cleaning action in a script that would be compiled by a Hudson job? At the end of the script or at the begining?

A: jnidispatch is a Java Native Library, so I would say 'NO' on that.
The others(s), I would recommend that you not delete them if you have no real need to delete them.  If you want to delete them for no particular reason, then I would say leave them be.  If there is an immediate threat, then delete them, but make sure you do proper backing up.


text:
Q: Stretch Bitmap without anti-aliasing I found this example and used it How do you resize a Bitmap under .NET CF 2.0
However my image looks horrible because of anti aliasing. It no longer looks pixelated as it should. How do i disable anti aliasing?

A: Set the interpolation mode to nearest neighbor:
g.InterPolationMode = InterpolationMode.NearestNeighbor


text:
Q: Indexing issue on fread() vs. read.csv()? myInput <- data.frame('X' = c(1, 2, 3, 4, 5),
                      'n' = c(87, 119, 94, 95, 134),
                      'r' = c(76, 8, 74, 11, 0))

write.csv(myInput, file = "test.csv", row.names = FALSE)

input_file <- "test.csv"

#Load input
myInput <- read.csv(input_file, stringsAsFactors = FALSE)
a_csv <- myInput[-3]
b_csv <- myInput[,-3]

Gives this:
> print(dim(a_csv))
[1] 5 2
> print(dim(b_csv))
[1] 5 2

Compared to this result with fread():
myInput <- fread(input_file, stringsAsFactors = FALSE)
a_fread <- myInput[-3]
b_fread <- myInput[,-3]

> print(dim(a_fread))
[1] 4 3
> print(dim(b_fread))
[1] 5 2

So reading in data using these 2 methods return objects of the same type but indexing on them is giving different results.  Why?  And how can I make these consistent so that users who choose to use read.csv() don't get different results from users who choose fread()?
P.S. This is the closest I could find: read.csv and fread produce different results for the same data frame
But it has to do with how the data is being read. I couldn't find anything that addresses the indexing issue.

A: read.csv() returns a data.frame. When you do myInput[-3] for this data.frame, the data.frame is treated as a list, and the indexing drops the third element of the list, i.e, the third column.
myInput <- read.csv(input_file, stringsAsFactors = FALSE)
class(myInput)
# [1] "data.frame"

fread() returns a data.table. When you do myInput[-3], this drops the third row of the data.table.
myInput <- fread(input_file, stringsAsFactors = FALSE)
class(myInput)
# [1] "data.table" "data.frame"

This is just the way data.table and data.frame are difference. More technically, it's a difference between [.data.table and [.data.frame.
Example:
DT <- data.table(a = 1:4, b = letters[1:4], c = LETTERS[1:4])
DT
#    a b c
# 1: 1 a A
# 2: 2 b B
# 3: 3 c C
# 4: 4 d D
DT[-3]
#    a b c
# 1: 1 a A
# 2: 2 b B
# 3: 4 d D
df <- data.frame(a = 1:4, b = letters[1:4], c = LETTERS[1:4])
df
#   a b c
# 1 1 a A
# 2 2 b B
# 3 3 c C
# 4 4 d D
df[-3]
#   a b
# 1 1 a
# 2 2 b
# 3 3 c
# 4 4 d


text:
Q: Registration with CodeIgniter Ion Auth I am trying to register a user with Ion Auth, but the register() function does not seem to report any error messages. How does one register with Ion Auth? I've already read various tutorials like this one and this one (and the documentation), but they do not seem to be working.
function register()
{
    // do not allow registration if logged in
    if ($this->ion_auth->logged_in())
    {
        redirect('/');
    }

    $this->load->helper(array('form', 'url'));
    $this->load->library('form_validation');

    $this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
    $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback_email_check');
    $this->form_validation->set_rules('email2', 'Email Confirmation', 'trim|required|valid_email|matches[email]');
    $this->form_validation->set_rules('password', 'Password', 'trim|required|md5');

    if ($this->form_validation->run() == FALSE)
    {
        $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

        $this->load->view('header');
        $this->load->view('register', $this->data);
        $this->load->view('footer');
    }
    else
    {
        $username = $this->input->post('email');
        $password = $this->input->post('password');
        $email = $username;

        $additional_data = array(
            'first_name' => $this->input->post('name'),
            'last_name' => '',
        );

        if (!$this->ion_auth->email_check($email))
        {
            $group_name = 'users';
            $uId = $this->ion_auth->register($username, $password, $email, $additional_data, $group_name);

            if ($uId == FALSE)
            {
                $this->session->set_flashdata('message', $this->ion_auth->errors());
                redirect("home/register", 'refresh');
            }
            else
            {
                redirect('/'); // registration success
            }
        }
    }
}

function email_check($str)
{
    if ($this->ion_auth->email_check($str))
    {
        $this->form_validation->set_message('email_check', 'This email is already registered.');
        return FALSE;
    }

    return TRUE;
}


text:
Q: python - combining argsort with masking to get nearest values in moving window I have some code for calculating missing values in an image, based on neighbouring values in a 2D circular window. It also uses the values from one or more temporally-adjacent images at the same locations (i.e. the same 2D window shifted in the 3rd dimension).
For each position that is missing, I need to calculate the value based not necessarily on all the values available in the whole window, but only on the spatially-nearest n cells that do have values (in both images / Z-axis positions), where n is some value less than the total number of cells in the 2D window.
At the minute, it's much quicker to calculate for everything in the window, because my means  of sorting to get the nearest n cells with data is the slowest part of the function as it has to be repeated each time even though the distances in terms of window coordinates do not change. I'm not sure this is necessary and feel I must be able to get the sorted distances once, and then mask those in the process of only selecting available cells.
Here's my code for selecting the data to use within a window of the gap cell location:
# radius will in reality be ~100
radius = 2
y,x = np.ogrid[-radius:radius+1, -radius:radius+1]
dist = np.sqrt(x**2 + y**2)
circle_template = dist > radius

# this will in reality be a very large 3 dimensional array
# representing daily images with some gaps, indicated by 0s
dataStack = np.zeros((2,5,5))
dataStack[1] = (np.random.random(25) * 100).reshape(dist.shape)
dataStack[0] = (np.random.random(25) * 100).reshape(dist.shape)

testdata = dataStack[1]
alternatedata = dataStack[0]
random_gap_locations = (np.random.random(25) * 30).reshape(dist.shape) > testdata
testdata[random_gap_locations] = 0
testdata[radius, radius] = 0

# in reality we will go through every gap (zero) location in the data
# for each image and for each gap use slicing to get a window of
# size (radius*2+1, radius*2+1) around it from each image, with the
# gap being at the centre i.e.
# testgaplocation = [radius, radius]
# and the variables testdata, alternatedata below will refer to these
# slices

locations_to_exclude = np.logical_or(circle_template, np.logical_or
                                     (testdata==0, alternatedata==0))
# the places that are inside the circular mask and where both images
# have data
locations_to_include = ~locations_to_exclude
number_available = np.count_nonzero(locations_to_include)

# we only want to do the interpolation calculations from the nearest n
# locations that have data available, n will be ~100 in reality
number_required = 3

available_distances = dist[locations_to_include]
available_data = testdata[locations_to_include]
available_alternates = alternatedata[locations_to_include]

if number_available > number_required:
    # In this case we need to find the closest number_required of elements, based
    # on distances recorded in dist, from available_data and available_alternates
    # Having to repeat this argsort for each gap cell calculation is slow and feels
    # like it should be avoidable
    sortedDistanceIndices = available_distances.argsort(kind = 'mergesort',axis=None)
    requiredIndices = sortedDistanceIndices[0:number_required]
    selected_data = np.take(available_data, requiredIndices)
    selected_alternates = np.take(available_alternates , requiredIndices)
else:
    # we just use available_data and available_alternates as they are...

# now do stuff with the selected data to calculate a value for the gap cell

This works, but over half of the total time of the function is taken in the argsort of the masked spatial distance data. (~900uS of a total 1.4mS - and this function will be running tens of billions of times, so this is an important difference!)
I am sure that I must be able to just do this argsort once outside of the function, when the spatial distance window is originally set up, and then include those sort indices in the masking, to get the first howManyToCalculate indices without having to re-do the sort. The answer might involve putting the various bits that we are extracting from, into a record array - but I can't figure out how, if so. Can anyone see how I can make this part of the process more efficient?

A: So you want to do the sorting outside of the loop:
sorted_dist_idcs = dist.argsort(kind='mergesort', axis=None)

Then using some variables from the original code, this is what I could come up with, though it still feels like a major round-trip..
loc_to_incl_sorted = locations_to_include.take(sorted_dist_idcs)
sorted_dist_idcs_to_incl = sorted_dist_idcs[loc_to_incl_sorted]

required_idcs = sorted_dist_idcs_to_incl[:number_required]
selected_data = testdata.take(required_idcs)
selected_alternates = alternatedata.take(required_idcs)

Note the required_idcs refer to locations in the testdata and not available_data as in the original code. And this snippet I used take for the purpose of conveniently indexing the flattened array.

A: @moarningsun - thanks for the comment and answer.  These got me on the right track, but don't quite work for me when the gap is < radius from the edge of the data: in this case I use a window around the gap cell which is "trimmed" to the data bounds. In this situation the indices reflect the "full" window and thus can't be used to select cells from the bounded window.
Unfortunately I edited that part of my code out when I clarified the original question but it's turned out to be relevant.
I've realised now that if you use argsort again on the output of argsort then you get ranks; i.e. the position that each item would have when the overall array was sorted. We can safely mask these and then take the smallest number_required of them (and do this on a structured array to get the corresponding data at the same time).
This implies another sort within the loop, but in fact we can use partitioning rather than a full sort, because all we need is the smallest num_required items. If num_required is substantially less than the number of data items then this is much faster than doing the argsort.
For example with num_required = 80 and num_available = 15000 the full argsort takes ~900µs whereas argpartition followed by index and slice to get the first 80 takes ~110µs. We still need to do the argsort to get the ranks at the outset (rather than just partitioning based on distance) in order to get the stability of the mergesort, and thus get the "right one" when distance is not unique.
My code as shown below now runs in ~610uS on real data, including the actual calculations that aren't shown here. I'm happy with that now, but there seem to be several other apparently minor factors that can have an influence on the runtime that's hard to understand.
For example putting the circle_template in the structured array along with dist, ranks, and another field not shown here, doubles the runtime of the overall function (even if we don't access circle_template in the loop!). Even worse, using np.partition on the structured array with order=['ranks'] increases the overall function runtime by almost two orders of magnitude vs using np.argpartition as shown below!
# radius will in reality be ~100
radius = 2
y,x = np.ogrid[-radius:radius+1, -radius:radius+1]
dist = np.sqrt(x**2 + y**2)
circle_template = dist > radius
ranks = dist.argsort(axis=None,kind='mergesort').argsort().reshape(dist.shape)
diam = radius * 2 + 1

# putting circle_template in this array too doubles overall function runtime!
fullWindowArray = np.zeros((diam,diam),dtype=[('ranks',ranks.dtype.str),
                                       ('thisdata',dayDataStack.dtype.str),
                                       ('alternatedata',dayDataStack.dtype.str),
                                       ('dist',spatialDist.dtype.str)])
fullWindowArray['ranks'] = ranks
fullWindowArray['dist'] = dist

# this will in reality be a very large 3 dimensional array
# representing daily images with some gaps, indicated by 0s
dataStack = np.zeros((2,5,5))
dataStack[1] = (np.random.random(25) * 100).reshape(dist.shape)
dataStack[0] = (np.random.random(25) * 100).reshape(dist.shape)

testdata = dataStack[1]
alternatedata = dataStack[0]
random_gap_locations = (np.random.random(25) * 30).reshape(dist.shape) > testdata
testdata[random_gap_locations] = 0
testdata[radius, radius] = 0

# in reality we will loop here to go through every gap (zero) location in the data
# for each image
gapz, gapy, gapx = 1, radius, radius
desLeft, desRight = gapx - radius, gapx + radius+1
desTop, desBottom = gapy - radius, gapy + radius+1
extentB, extentR = dataStack.shape[1:]

# handle the case where the gap is < search radius from the edge of
# the data. If this is the case, we can't use the full
# diam * diam window
dataL = max(0, desLeft)
maskL = 0 if desLeft >= 0 else abs(dataL - desLeft)
dataT = max(0, desTop)
maskT = 0 if desTop >= 0 else abs(dataT - desTop)
dataR = min(desRight, extentR)
maskR = diam if desRight <= extentR else diam - (desRight - extentR)
dataB = min(desBottom,extentB)
maskB = diam if desBottom <= extentB else diam - (desBottom - extentB)

# get the slice that we will be working within
# ranks, dist and circle are already populated
boundedWindowArray = fullWindowArray[maskT:maskB,maskL:maskR]
boundedWindowArray['alternatedata'] = alternatedata[dataT:dataB, dataL:dataR]
boundedWindowArray['thisdata'] = testdata[dataT:dataB, dataL:dataR]

locations_to_exclude = np.logical_or(boundedWindowArray['circle_template'],
                                     np.logical_or
                                     (boundedWindowArray['thisdata']==0,
                                      boundedWindowArray['alternatedata']==0))
# the places that are inside the circular mask and where both images
# have data
locations_to_include = ~locations_to_exclude
number_available = np.count_nonzero(locations_to_include)

# we only want to do the interpolation calculations from the nearest n
# locations that have data available, n will be ~100 in reality
number_required = 3

data_to_use = boundedWindowArray[locations_to_include]

if number_available > number_required:
    # argpartition seems to be v fast when number_required is
    # substantially < data_to_use.size
    # But partition on the structured array itself with order=['ranks']
    # is almost 2 orders of magnitude slower!

    reqIndices = np.argpartition(data_to_use['ranks'],number_required)[:number_required]
    data_to_use = np.take(data_to_use,reqIndices)
else:
    # we just use available_data and available_alternates as they are...
    pass
# now do stuff with the selected data to calculate a value for the gap cell


text:
Q: Winforms: Add a close "x" button in a UserControl I need to add a close "x" button in the upper left corner of a UserControl. I'd like that button have similar style as a usual Winforms close button (Blue in XP style, etc).
Is it possible to do such a thing?

A: Here's an example of how to make a simulated button. It does so on the form itself, but works the same on a custom control.
It also shows how to get the "fancy" button style using a VisualStyleRenderer in case the ControlPaint style is too "old".
Updated  After six edits, I think I'm happy with it.
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;

class Form1 : Form
{
    [STAThread]
    static void Main()
    {
        //Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    public Form1()
    {
        SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.Opaque | ControlStyles.AllPaintingInWmPaint, true);
    }

    Rectangle buttonRect = new Rectangle(10, 10, 50, 20);
    ButtonState buttonState = ButtonState.Normal;

    protected override void OnMouseMove(MouseEventArgs e)
    {
        if (buttonRect.Contains(e.Location))
            buttonState = Capture ? ButtonState.Pushed : ButtonState.Checked;
        else
            buttonState = ButtonState.Normal;
        Invalidate(buttonRect);

        base.OnMouseMove(e);
    }

    protected override void OnMouseDown(MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left && buttonRect.Contains(e.Location))
        {
            Capture = true;
            buttonState = ButtonState.Pushed;
            Invalidate(buttonRect);
        }

        base.OnMouseDown(e);
    }

    protected override void OnMouseUp(MouseEventArgs e)
    {
        if (Capture)
        {
            Capture = false;
            Invalidate(buttonRect);
            if (buttonRect.Contains(e.Location))
            {
                // The button was clicked

                MessageBox.Show("You clicked the button.");
            }
        }

        base.OnMouseUp(e);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        e.Graphics.FillRectangle(SystemBrushes.Window, e.ClipRectangle);

        VisualStyleRenderer renderer = null;
        if (Application.RenderWithVisualStyles)
        {
            switch (buttonState)
            {
                case ButtonState.Checked:
                    if (VisualStyleRenderer.IsElementDefined(VisualStyleElement.Window.CloseButton.Hot))
                        renderer = new VisualStyleRenderer(VisualStyleElement.Window.CloseButton.Hot);
                    break;
                case ButtonState.Pushed:
                    if (VisualStyleRenderer.IsElementDefined(VisualStyleElement.Window.CloseButton.Pressed))
                        renderer = new VisualStyleRenderer(VisualStyleElement.Window.CloseButton.Pressed);
                    break;
                default:
                    if (VisualStyleRenderer.IsElementDefined(VisualStyleElement.Window.CloseButton.Normal))
                        renderer = new VisualStyleRenderer(VisualStyleElement.Window.CloseButton.Normal);
                    break;
            }
        }

        if (renderer != null)
            renderer.DrawBackground(e.Graphics, buttonRect);
        else
            ControlPaint.DrawCaptionButton(e.Graphics, buttonRect, CaptionButton.Close, buttonState);

        base.OnPaint(e);
    }
}

Extended Comment
An extended operation is one that begins with the user pressing a mouse button, (optionally) moving the mouse, and then releasing that button. Clicking on a UI button is always an extended operation. The purpose of capturing the mouse is to prevent it from interacting with other windows during that operation.
You can see this demonstrated right now:
First notice how when you move the mouse over elements on this page (like comments), they change background color.
Now open the Windows Run dialog (Win+R).
Click on the Cancel or Browse... button and keep holding the button.
Move the mouse around to the browser window and notice that it no longer registers your mouse movement.
This is how all buttons work by design. While hardly anyone notices it because you generally click and release without moving the mouse (much).
Moving the mouse off of the button and releasing is a mechanism provided to the user to allow them to change their mind and not "click" the button. That's why you test again in the button up event to make sure they are still on the button before you determine that the user has performed a click.
So there are three reasons to capture the mouse:
First you don't want other windows performing things like highlighting because the user is busy interacting with your window, having other windows doing things during the operation is distracting and potentially confusing.
Second you don't want the user's release of the mouse button to be sent to another window on the off chance that they move the mouse all the way onto another window. A spurious mouse release without an accompanying press can confuse poorly written applications.
Third, for certain extended operations like painting or "wrangling", you want to know the coordinates of the mouse even when they are outside the boundaries of your window. You can see an example of wrangling by clicking and holding on the desktop and moving the mouse around. Notice how the rectangle changes even when you move the mouse over other windows.

A: Updated Answer
I just found out there the ControlPaint class in .net, which does the same thing as the DrawFrameControl function. Use that instead!
You could use the ControlPaint class to implement a button control that paints itself to look like the Windows "Close" button (override OnPaint). Depending on the required level of complexity, you might implement the mouse-over-events and mouse-down-events, too, to provide visual feedback for the current state. If you place that control on your UserControl you should be on the right track.
Original, obsolete Answer
You might want to look at the DrawFrameControl API function in windows.
The combination of DFC_CAPTION and DFCS_CAPTIONCLOSE should do what you want.

A: not sure it is possible but that would definately confuse the users if your main Control that will host this UserContorl will have these 3 buttons (min,Max/close) and your UserControl as well. what's the rational behind this?