text:
Q: How to pass raw json data in Retrofit I am implementing following web api in Retrofit.
api example in Postman
To call the api I have implemented three classes.
api.java
public interface Api {
    @POST("/login.jsp")
    void login(@Body LoginRequest loginRequest, Callback<String> callback);
}

LoginRequest.java
public class LoginRequest {
    private String username;
    private String password;

    public LoginRequest() {
    }

    public LoginRequest(String username, String password) {
        this.username = username;
        this.password = password;
    }
}

ServiceClient.java
public class ServiceClient {
    private static Api api;
    private static String BASE_URL = "http://example.com/xxx";

    static {
        setupServiceClient();
    }

    private ServiceClient() {}

    public static Api get() {
        return api;
    }

    private static void setupServiceClient() {
        Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

        api = retrofit.create(Api.class);
    }
}

Then I am trying to call the api as following.
ServiceClient.get().login(new LoginRequest(user, password), new Callback<String>() {
            @Override
            public void onResponse(Response<String> response, Retrofit retrofit) {
                Log.i(TAG, "SUCESS");
            }

            @Override
            public void onFailure(Throwable t) {
                Log.i(TAG, "ERROR");
            }
        });

But unfortunately the app crashes after calling the api. I am suspecting the issue is involved in raw json parameter value.
Any suggestions?
Thanks.


text:
Q: Using JSON & JQUERY From API I have searched solutions for a while now and I really have tried everything. I'm new to json. New to jquery but use it frequently. I have an API that I'm trying to connect to so I need to remove the tokens.. but I'm having a major disconnect with rendering the data.
I used postman to get authorization down and using this information I get json string back. Yet when I put it on my url - nothing loads. I feel I'm missing something basic.
I want to
- click a button
- load json data into a div - or in my example it's a table
my script is

         $("button").click(function(){
        $.ajax({
            async: 'true',
      crossDomain: 'true',
      method: 'GET',
      headers: {
        'authorization': 'Basic OMMITTED',
        'cache-control': 'no-cache'},
            type: 'POST',
            url: 'https://www.OMMITTED.com/api/v2/orders.json?limit=200&page=1',
            data: $('#table').serialize(),
            dataType:"json", //to parse string into JSON object,
            success: function(data){

            if(data){
                var len = data.length;
                var txt = "";
                if(len > 0){
                    for(var i=0;i<len;i++){
                        if(data[i].id && data[i].customer_id){
                            txt += "
"+data[i].id+"	"+data[i].customer_id+"
";
                        }
                    }
                    if(txt != ""){
                        $("#table").append(txt).removeClass("hidden");
                    }

                }
            }
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('error: ' + textStatus + ': ' + errorThrown);
        }
    });
    return false;//suppress natural form submission
});
</script>

MY HTML

            id
            customer_id

    <button>Get JSON Data</button>

I get nothing - no errors - nothing. In another version I used
    $(document).ready(function(){
        $("button").click(function(){
            $("#div1").load("TrackingResults.aspx");
        });
    });

with a variation of the above - and it loaded up the html into the page - but no data showed.
IF I go to POSTMAN, add the headers basic auth and token and hit the url - I get back json data

    [
      {
        "id": 100,
        "customer_id": 0,
        "date_created": "Thu, 07 Jul 2016 18:59:31 +0000",
        "date_modified": "Thu, 07 Jul 2016 18:59:31 +0000",
        "status_id": 0,
        "status": "Incomplete",

etc etc etc

The POSTMAN GENERATE CODE Produced this
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://www.OMITTED.com/api/v2/orders.json",
  "method": "GET",
  "headers": {
    "authorization": "Basic OMITTED",
    "cache-control": "no-cache",
     }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

This API I setup a Single Sign On token - and like I said- pasting that token and the API url into API - viola - I get data. Unfortunately I'm missing what I'm missing.
I'm looking for someone to help point me in the right direction. I've read tutorials for days, I can create text files of sample JSON data and get it to work- but no matter what I do - I can't get any of the json to create and display. Really looking for a point in the right direction as I've spend so many hours on trying to get started with json
Thanks in advance  - be easy on me. I take posting to stackoverflow seriously - you guys are awesome!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set Validation for all controls in a user control? I am looking for the best way to set the validation group for all of the controls contained in a user control.  Most of the controls in the control are created dynamically when the control is loaded.  It has quite a few input fields and validators.
I would like to save time by setting the validation for all the controls and validators with some sort of function that could just loop through everything and set it.
It seems though that there is no consistent interface that includes validation group for all of the different controls that have the property.
Should I use reflection to check for Validation group, I know I can do this, but is there a better way?
We are using C# by the way.
Any help would be appreciated.  Thanks!
EDIT:  I put the answer down below for anyone who wants the code.

A: Just wanted to mark this answered.
Here is the code I used to set the validation group.  I decided to go with using reflection, since I could check types for those I know have ValidationGroup, and cast and set, but there are a lot of types to check, and it could miss new controls that may be added in the future.  Would have been sweet if the ValidationGroup were part of some kind of interface that things had to implement.
/// <summary>
/// this is an extension method to iterate though all controls in a control collection
/// put this in some static library somewhere
/// </summary>
/// <param name="controls"></param>
/// <returns></returns>
public static IEnumerable<Control> All(this ControlCollection controls)
{
    foreach (Control control in controls)
    {
        foreach (Control grandChild in control.Controls.All())
            yield return grandChild;

        yield return control;
    }
}

/// <summary>
/// this function uses reflection to check if the validation group exists, and then set it to the
/// specified string
/// </summary>
/// <param name="ValidationGroup"></param>
private void SetValidationGroup(string ValidationGroup)
{
    //set the validation group for all controls
    if (ValidationGroup.IsNotNullOrEmpty())
    {
        foreach (Control c in Controls.All())
        {
            var Properties = c.GetType().GetProperties();
            var vg = Properties.Where(p => p.Name == "ValidationGroup").SingleOrDefault();
            if (vg != null)
            {
                vg.SetValue(c, ValidationGroup, null);
            }

        }

    }
}

A: I recently had a very similar problem- the soloution I used was to create a couple of extension methods that could loop over all child/descendent controls of a control, find ones of a particular type and then call a subroutine on them (this subroutine could for example, set any properties of a control). The code is below in VB.Net (sorry this is what we use at work, I'm sure a code translator should be able to sort this out for you).
Public Module ControlExtensionMethods

''' <summary>
''' Gets all validation controls used by a control.
''' </summary>
''' <param name="onlyGetVisible">If true, will only fetch validation controls that currently apply (i.e. that are visible). The default value is true.</param>
''' <returns></returns>
''' <remarks></remarks>
<Extension()>
Public Function GetAllValidationControls(ByVal target As Control, Optional ByVal onlyGetVisible As Boolean = True) As ReadOnlyCollection(Of BaseValidator)
    Dim validators As New List(Of BaseValidator)
    GetControlsOfType(Of BaseValidator)(target, Function(x) Not onlyGetVisible OrElse x.Visible = onlyGetVisible, validators)
    Return validators.AsReadOnly()
End Function

''' <summary>
''' Gets if the control is in a valid state (if all child/descendent validation controls return valid)
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
<Extension()>
Public Function IsValid(ByVal target As Control) As Boolean
    Return target.GetAllValidationControls().All(Function(x)
                                                     x.Validate()
                                                     Return x.IsValid
                                                 End Function)
End Function

''' <summary>
''' Iteratively fetches all controls of a specified type/base type from a control and its descendents.
''' </summary>
''' <param name="fromControl"></param>
''' <param name="predicate">If provided, will only return controls that match the provided predicate</param>
''' <remarks></remarks>
<Extension()>
Public Function GetControlsOfType(Of T As Control)(ByVal fromControl As Control, Optional ByVal predicate As Predicate(Of T) = Nothing) As IList(Of T)
    Dim results As New List(Of T)
    GetControlsOfType(fromControl, predicate, results)
    Return results
End Function

Private Sub GetControlsOfType(Of T As Control)(ByVal fromControl As Control, ByVal predicate As Predicate(Of T), ByVal results As IList(Of T))
    'create default predicate that always returns true if none is provided
    Dim cntrl As Control

    If predicate Is Nothing Then predicate = Function(x) True

    If fromControl.HasControls Then
        For Each cntrl In fromControl.Controls
            GetControlsOfType(Of T)(cntrl, predicate, results)
        Next
    End If

    If TypeOf fromControl Is T AndAlso predicate(fromControl) Then
        results.Add(fromControl)
    End If
End Sub
End Module

An example of using this code to disable all validators:
Array.ForEach(myUserControl.GetAllValidationControls().ToArray(), sub(x) x.Enabled = False)

A: I was butting my head against this issue just now, and came up with an alternative solution that doesn't involve duck-typing:
string newGroup = "foo";
IEnumerable<BaseValidator> validators = this.Controls.OfType<BaseValidator>();
IEnumerable<Button> buttons = this.Controls.OfType<Button>();

foreach (var validator in validators)
    validator.ValidationGroup = newGroup;

foreach (var button in buttons)
    button.ValidationGroup = newGroup;

This also might be an alternative:
foreach (var c in this.Controls)
{
    if (c is BaseValidator)
        (c as BaseValidator).ValidationGroup = newGroup;
    else if (c is Button)
        (c as Button).ValidationGroup = newGroup;
}


text:
Q: How to get Columns and Tables used from SQL statement I need to get the columns and tables used in a query but I'm not finding an elegant way of doing it. I've search about it but can't find information that works to me. The query has this format
select TABLE1.Id, TABLE2.Name, TABLE3.Observations, TABLE3.Adress, --and more 70 fields
from TABLE1, TABLE2, TABLE3, TABLE4

Is there any Good Way of doing this two tasks?

A: Your problem is that SqlCommand.Parameters is a series of SqlParameter objects that are to be replaced in the query with actual values. I.e. they are input parameters. They are used for the SqlCommand to replace with SQL Safe and Compatible representations of the included parameters. I.e. with your query, something like the following would suffice:
SqlCommand sql = new SqlCommand("SELECT TABLE1.Id, TABLE2.Name, TABLE3.Observations, TABLE3.Address FROM TABLE1, TABLE2, TABLE3, TABLE4 WHERE TABLE2.Name = @Name")
sql.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 32));
sql.Parameters["@Name"] = "Your Name";

The SQL driver would then replace @Name in the query with a SQL Safe representation of 'Your Name'.
To do what you want, you would be required to parse the actual string and break it down into it's tokens or statements. This is a complex process for some statements.
Depending on what your requirements (for support of syntax) are, you could easily break the statement down by extracting everything between SELECT and FROM in this case, break the strings on commas, and then break further on periods to get table names and fields names.
Some sample code that should do what you want (untested at this moment):
// sql.CommandText can be replaced with the raw SQL Query String
string query = sql.CommandText;
string removeSelect = query.Substring(7); // Remove the SELECT and space
string removeAfterFrom = removeSelect.Substring(0, removeSelect.IndexOf(" FROM ")); // Remove the FROM
string[] columns = removeAfterFrom.Split(','); // Get each Column

List<string> tables = new List<string>();

for (int i = 0; i < columns.Length; i++)
{
    string[] columnName = columns[i].Split('.');
    if (columnName.Length > 1)
        if (!tables.Contains(columnName[0]))
            tables.Add(columnName[0].Trim());
}

Also, another note, this code could readily be modified to extract the table names from the FROM clause instead.
Essentially, your goal here is to create a rudimentary SQL Parser that can return certain values/objects from your SQL Statement. If it's always a SELECT statement, than this method will work on all variants except those that use a wildcard (*) column name, or those that use TOP (n). If you have to support TOP (n) queries, you should add an appropriate filter. It will also only return table names that were included in the column name clause. (I.e. requires fully qualified names: SELECT TABLE1.Name FROM TABLE1 instead of SELECT Name FROM TABLE1.
If you prefer to get all tables specified in the query (regardless if any columns are selected from them) you may use the following instead.
// sql.CommandText can be replaced with the raw SQL Query String
string query = sql.CommandText;
string removeSelect = query.Substring(7); // Remove the SELECT and space
string[] splitOnFrom = removeSelect.Split(new string[] { " FROM " }, StringSplitOptions.RemoveEmptyEntries);
string[] columns = splitOnFrom[0].Split(','); // Get each Column
string[] tables = splitOnFrom[1].Split(','); // Get each Table

The columns array will have all the fully-qualified column names, and the tables array will have all the fully-qualified table names.
Another sidebar on both methods: the FROM term (word) is case-sensitive. I.e. From, from will not work. If you wish to use the first method and make from case-insensitive, the following would work:
string removeAfterFrom = removeSelect.Substring(0, removeSelect.IndexOf(" FROM ", StringComparison.CurrentCultureIgnoreCase));

For the second, you would need to modify it a bit more, but it's not terribly difficult.

As far as I know, there is nothing built-in that has this functionality. (Though I'm sure a quick Google Search could prove me wrong.)

A: There tho ways I can think of right now.
First one is to actually execute the SQL statement in question (possibly wrap it in begin tran/rollback tran) and then extract column names from the SqlDataReader.
Second is to hand-roll a rudimentary parser. This can be pretty simple, especially if all you have to support is the select a.b, c, d.e from ... syntax.


text:
Q: A Strong Law of Large Numbers exercise Let $X_{1},X_{2},\ldots$ be i.i.d. random variables and $f:\mathbb{R}^{3}\rightarrow\mathbb{R}$ a continuous function. For each $n\in\mathbb{N}$ define
$$Y_{n}=f(X_{n},X_{n+1},X_{n+2})$$
If $\mathbb{E}|Y_{1}|<\infty$, show that
$$\frac{Y_{1}+\cdots+Y_{n}}{n}\rightarrow\mathbb{E}Y_{1}\,a.s.$$
As the title suggests, I believe that this exercise will ultimately boil down to the SLN. However, while the random variables $Y_{n}$ are certainly identically distributed, I don't believe them to be independent. How should one think about this problem?

A: Each of  the sequences $(Y_1,Y_4,Y_7,\dots)$, $(Y_2,Y_5,Y_8,\dots)$ and  $(Y_3,Y_6,\dots)$ is iid. Apply SLN three times and add.


text:
Q: Checking for a number if first 4 digits forward equals last 4 digits backwards If the last 4 elements stepping forward are equal to the last 4 elements stepping backwards, print the number. I have input a number where the last 4 elements are clearly palindromic. Why does this not print the number?
def checkNum(i):
    num = str(i)
    if num[len(num)-5:len(num)-1:1] == num[len(num)-5:len(num)-1:-1]:
        print(num)
checkNum(777777)

A: You got the slices wrong. The left part of the string should be sliced like that: num[:4] and the right part should be sliced like that: num[:-5:-1]
Edit for the comment:
You can always print the slices you're attempting to use in the function. To get the problem, use something more visualising than 777777. For example: 123456789. Then, if you print your slices in the function, you will see the strings that you are comparing:
def checkNum(i):
    num = str(i)
    print(num[-4:])
    print(num[-4::-1])
    print(num[-5:-1])
checkNum(123456789)

The output you'll get is:
6789
654321
9876

This shows the way slices work. When you're using negative indexes, you're starting from the end with a positive step, so num[-4:] returns the last 4 characters in the original order. The negative step returns the first characters reversed. Consider some manual testing, it really saves a lot of time.

A: You are going backwards from len(num)-1 to len(num)-5 in the latter part of the equality!
Here's the correct version:
def checkNum(i):
num = str(i)
if num[len(num)-5:len(num)-1:1] == num[len(num)-1:len(num)-5:-1]:
    print(num)
checkNum(777777)

A: >>> num = str(777777)
>>> print num[len(num)-5:len(num)-1:1]
7777
>>> print num[len(num)-5:len(num)-1:-1]
***None***

To access the last four from the last position, you need
>>> print num[len(num)-1:len(num)-5:-1]
7777

def checkNum(i):
    num = str(i)
    if num[len(num)-5:len(num)-1:1] == num[len(num)-1:len(num)-5:-1]:
        print(num)

>>> checkNum(777777)
777777

A: You could take the first 4 characters forward ([:4]), reverse the string ([::-1]) and take the first 4 characters again (which are now the last 4 characters reversed):
def checkNum(i):
    num = str(i)
    if num[:4] == num[::-1][:4]:
        print(num)

>>> checkNum("11118354367451111")
11118354367451111
>>> checkNum("1111835436745111")
>>>
>>> checkNum("otto")
otto
>>>


text:
Q: How to subcribe on WorkItem state changes on TFS? Good day!
I want to know, how to subcribe on WorkItem state changes on TFS 2010\2013?
Should i use WCF?
Please tell we the way.
Thank you.
P.S. i need to get access to tfs workitem changes via c# : when workitem changed- i want to get some notification and do some operations via c#
For example: i have console program,wich get all workitems. But it get by run sheduler.
I want to subscribe my program on some event like onWorkItemChanged: when some user change task- program get this changed and do some work.

A: There are different ways to achive this. You can do it directly within the process of tfs by implementing an ISubscriber and listening to the WorkitemChangedEvent:
http://www.almguide.com/2011/12/tfs-server-side-event-handlers/
Or using the client API you can register a wcf service to get notified for workitem changes. So you can implement the logic on a different tier.
You can find both implementations here:
http://tfswiwatcher.codeplex.com
The 2010 Version uses the client side way and the 2012 and 2013 versions are using the server side way.

A: You can use the tool BisSubsribe to register for an event. It can hook up your own service to events occuring in TFS.

A: TFS has capabilities to set up email notifications. Check this MSDN page for help.


text:
Q: Can duplicate primary keys be apparent for READ COMMITTED isolation? I have a table with a primary key, which is backed by a uniqueness constraint. A query with SERIALIZABLE isolation should therefore never return two rows with the same primary key. But is that also true for a query with READ COMMITTED isolation? What is the most lax isolation level for which apparent duplicate primary keys are impossible?

A:
What is the most lax isolation level for which apparent duplicate
  primary keys are impossible?

REPEATABLE READ or READ COMMITTED SNAPSHOT
In SQL Server it is definitely possible for a scan at READ COMMITTED (locking)  to read a row twice.
At this isolation level the row locks are released as soon as the data is read, not at the end of the statement or transaction.
Thus it is possible for a scan reading an index in key order to encounter the same row again if the key was updated after the initial read moving it until later in the index. In order to observe the duplicate primary key in practice the index being scanned would likely need to be on a different key column than the PK itself.
REPEATABLE READ can miss rows if data that has yet to be read moves forward in the index to a part already scanned but this wouldn't allow the phenomena of apparent duplicate primary keys to occur.

A: On OracleDB, as far as you PK isn't deferrable and deferred, you could not violate it: even in lowest supported 'READ COMMITTED' level (ANSI/ISO Level 1), different sessions operating on same rows occour into a row-lock contention. So, the second session's DML will stay in wait until the first release the lock - by committing or rollbacking - then it's validated on the fly and it would fail if the PK is violated.


text:
Q: How do i fix backgroundworker is busy c# code i keep getting background worker is busy when i run my code. any help?
       struct FtpSetting
    {
        public string Server { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string FileName { get; set; }
        public string FullName { get; set; }
    }

    FtpSetting _inputParameter;

    private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        string fileName = ((FtpSetting)e.Argument).FileName;
        string fullName = ((FtpSetting)e.Argument).FullName;
        string userName = ((FtpSetting)e.Argument).Username;
        string password = ((FtpSetting)e.Argument).Password;
        string server = ((FtpSetting)e.Argument).Server;
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", server, fileName)));
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.Credentials = new NetworkCredential(userName, password);
        Stream ftpStream = request.GetRequestStream();
        FileStream fs = File.OpenRead(fullName);
        byte[] buffer = new byte[1024];
        double total = (double)fs.Length;
        int byteRead = 0;
        double read = 0;
        do
        {
            if (!backgroundWorker.CancellationPending)
            {
                //Upload file & update process bar
                byteRead = fs.Read(buffer, 0, 1024);
                ftpStream.Write(buffer, 0, byteRead);
                read += (double)byteRead;
                double percentage = read / total * 100;
                backgroundWorker.ReportProgress((int)percentage);
            }
        }
        while (byteRead != 0);
        fs.Close();
        ftpStream.Close();
    }

    private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        lblStatus.Text = $"Uploaded {e.ProgressPercentage} %";
        progressBar.Value = e.ProgressPercentage;
        progressBar.Update();
    }

    private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        lblStatus.Text = "Upload complete !";
    }

    private void btnUpload_Click(object sender, EventArgs e)
    {
        string dir = "C:\\Users\\bluevels\\Pictures\\";
        string[] files = Directory.GetFiles(dir);
        foreach (string file in files)
        {

            string FileName = Path.GetFileName(file);

            FileInfo fi = new FileInfo(FileName);
            _inputParameter.Username = txtUserName.Text;
            _inputParameter.Password = txtPassword.Text;
            _inputParameter.Server = txtServer.Text;
            _inputParameter.FileName = fi.Name;
            _inputParameter.FullName = fi.FullName;
            backgroundWorker.RunWorkerAsync(_inputParameter);

        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

i keep getting the error from this line
backgroundWorker.RunWorkerAsync(_inputParameter);

A: By placing RunWorkerAsync() inside the foreach, you are attempting to start multiple copies of the worker using the same instance whilst it is already running.
Consider moving the loop into the worker itself:
class FtpSetting
{
    public string Server { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string[] Files { get; set; }
}

private void btnUpload_Click(object sender, EventArgs e)
{
    if (backgroundWorker.IsBusy)
       return;

      string dir = "C:\\Users\\bluevels\\Pictures\\";
      string[] files = Directory.GetFiles(dir);

     _inputParameter.Username = txtUserName.Text;
     _inputParameter.Password = txtPassword.Text;
     _inputParameter.Server = txtServer.Text;
     _inputParameter.Files = files;
     backgroundWorker.RunWorkerAsync(_inputParameter);
}

Naturally the body of the worker will need to be changed as e is a list of files now.  The rest of the properties can be read directly from instance fields.
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    var setting = (FtpSetting)e.Argument;
    ...
    for (int fileNum = 0; fileNum < setting.Files.Length; fileNum++)
    {
         if (backgroundWorker.CancellationPending)
             break;

         do
             ...
             // use setings.Files[fileNum]
             // also divide percentage done by setting.Files.Length e.g.
             double percentage = (100/setting.Files.Length)+fileNum + (read / total * 100);
             ...
    }

  }

That way if you ever decide to do true concurrent downloading from multiple sites (you'll need multiple workers or perhaps consider TPL DataFlow) there will be minimal code changes.

A: so i figured it our. all i had to do was put the loop in the backgroundworker as seen in the code below.
    struct FtpSetting
    {
        public string Server { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }

    }

    FtpSetting _inputParameter;

    private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        string fileName = "";
        string fullName = "";

        string dir = "C:\\Users\\bluevels\\Desktop\\ww\\";
        string[] files = Directory.GetFiles(dir);
        foreach (string file in files)
        {

            string FileName = "C:\\Users\\bluevels\\Desktop\\ww\\" + Path.GetFileName(file);

            FileInfo fi = new FileInfo(FileName);

            fileName = fi.Name;
            fullName = fi.FullName;

            string userName = ((FtpSetting)e.Argument).Username;
            string password = ((FtpSetting)e.Argument).Password;
            string server = ((FtpSetting)e.Argument).Server;
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", server, fileName)));
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(userName, password);
            Stream ftpStream = request.GetRequestStream();
            FileStream fs = File.OpenRead(fullName);
            byte[] buffer = new byte[1024];
            double total = (double)fs.Length;
            int byteRead = 0;
            double read = 0;
            do
            {
                if (!backgroundWorker.CancellationPending)
                {
                    //Upload file & update process bar
                    byteRead = fs.Read(buffer, 0, 1024);
                    ftpStream.Write(buffer, 0, byteRead);
                    read += (double)byteRead;
                    double percentage = read / total * 100;
                    backgroundWorker.ReportProgress((int)percentage);
                }
            }
            while (byteRead != 0);
            fs.Close();
            ftpStream.Close();
        }
    }

    private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        lblStatus.Text = $"Uploaded {e.ProgressPercentage} %";
        progressBar.Value = e.ProgressPercentage;
        progressBar.Update();
    }

    private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        lblStatus.Text = "Upload complete !";
    }

    private void btnUpload_Click(object sender, EventArgs e)
    {
                _inputParameter.Username = txtUserName.Text;
                _inputParameter.Password = txtPassword.Text;
                _inputParameter.Server = txtServer.Text;
                backgroundWorker.RunWorkerAsync(_inputParameter);

    }

the percentage calculation also works fine with every file.


text:
Q: FutureWarning: elementwise comparison failed; when dropping all rows from pandas dataframe I want to drop those rows in a dataframe that have value '0' in the column 'candidate'. Some of my dataframes only have value '0' in this column. I expected that in this case I will get an empty dataframe, but instead I get the following warning and the unchanged dataframe. How can I get an empty dataframe in this case? Or prevent returning an unchanged dataframe?
Warning message:
C:\Users\User\Anaconda3\lib\site-packages\pandas\core\ops\array_ops.py:253: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  res_values = method(rvalues)
My code:
with open(filename, encoding='utf-8') as file:
    df = pd.read_csv(file, sep=',')
    df.drop(df.index[(df['candidate'] == '0')], inplace=True)
    print(df)

     post id  ...  candidate
0          1  ...          0
1          1  ...          0
2          1  ...          0
3          1  ...          0
4          1  ...          0
..       ...  ...        ...
182       10  ...          0
183       10  ...          0
184       10  ...          0
185       10  ...          0
186       10  ...          0

[187 rows x 4 columns]

A: Thanks everyone for your suggestions!
Indeed, the value type is int, but only if 0 is the only value in the column. Where other values are present, the type is object.
So I solved the problem by using:
df = df.loc[(df["candidate"] != "0") & (df["candidate"] != 0)]

A: Your current implementation tries to find rows from Index matching the condition. You should find the rows to match the condition first and then take its index:
df.drop(df[df['candidate'] == 0].index, inplace=True)

After replacing the line your snippet should return:
Empty DataFrame
Columns: [post id, ..., candidate]
Index: []

You should also check that the type of the column matches with the type of the value you are comparing to.


text:
Q: How to insert an offset to hexdump with xxd? Is there an easy way to add an offset to the hex dump generated by xxd ?
i.e instead of
0000: <data>
0004: <data>
0008: <data>

I should get
Offset+0000: <data>
Offset+0004: <data>
Offset+0008: <data>

A: xxd now appears to come with offset support, using -o [offset]
for example: xxd -o 0x07d20000 file.bin
My version of xxd on Gentoo Linux has it, but I dug deeper to help folks on other distros:
xxd V1.10 27oct98 by Juergen Weigert -- Do not use the xxd version -- I have found this source code without the offset support!! So I tracked down where my binary comes from:
app-editors/vim-core-7.4.769 -- So apparently, as long as you have a modern VIM installed, you can reap the benefits of the added offset support; at least on Gentoo, but I'm steering you in the right direction.
If you find that your distro still ships an older xxd, considering manually compiling a newer VIM that you confirm has offset support.

A: This is what I am doing now..It works perfectly but its kind of lame approach for just adding an offset :)
xxd file.bin | xxd -r -s 0x2e00000 | xxd -s 0x2e00000 > file.hex

A: Reading your comment below:

I want the first byte of binary file to be present at the offset. i.e Just add an offset without seeking.

makes me believe the only way to do this is parsing the output and modifying it in order to add the desired offset.
I didn't found anything in the docs that would allow this to be done easily, sorry. :(

A: If you can live with AWK here's a proof of concept:
$ xxd random.bin | gawk --non-decimal-data ' # <-- treat 0x123 like numbers
> {
>     offset = 0x1000                # <-- your offset, may be hex of dec
>
>     colon = index($0, ":") - 1
>     x = "0x" substr($0, 1, colon)  # <-- add 0x prefix to original offset ...
>     sub(/^[^:]*/, "")              # <-- ... and remove it from line
>
>     new = x + offset               # <-- possible thanks to --non-decimal-data
>     printf("%0"colon"x", new)      # <-- print updated offset ...
>     print                          # <-- ... and the rest of line
> }'
0001000: ac48 df8c 2dbe a80c cd03 06c9 7c9d fe06  .H..-.......|...
0001010: bd9b 02a1 cf00 a5ae ba0c 8942 0c9e 580d  ...........B..X.
0001020: 6f4b 25a6 6c72 1010 8d5e ffe0 17b5 8f39  oK%.lr...^.....9
0001030: 34a3 6aef b5c9 5be0 ef44 aa41 ae98 44b1  4.j...[..D.A..D.
   ^^^^
   updated offsets (+0x1000)

I bet it would be shorter in Perl or Python, but AWK just feels more "script-ish" :-)


text:
Q: What is the syntax for parameter pack expansion with alignas? I'm trying to expand a parameter pack in an alignment specifier.  I can't get the syntax right.  Here's a simple example:
#include <cstdint>
#include <tuple>

template <typename... Ts>
struct C
{
    using Tuple_Type = std::tuple <Ts...>;

    void f()
    {
        uint8_t i1;
        uint8_t i2 alignas (2);
        uint8_t i3 alignas (typename std::tuple_element<0, Tuple_Type>::type);
        uint8_t i4 alignas (Ts...);
    }
};

//template class C <>;  // not compatible with i3 declaration above
template class C <uint64_t>;

This fails to compile with gcc 4.8.3:
foo.cpp: In member function 'void C<Ts>::f()':
foo.cpp:14:31: error: expected ')' before '...' token
         uint8_t i4 alignas (Ts...);
                               ^
foo.cpp:14:31: error: expected ')' before '...' token
foo.cpp:14:31: error: expected initializer before '...' token

The C++ standard ([dcl.align]) says "An alignment-specifier with an ellipsis is a pack expansion", so it seems like it should be possible to do what I want.
I've been unable to find an example of this kind of parameter pack expansion, and my search for a possible bug in gcc didn't find anything.

A: Your syntax is correct; gcc only implements pack expansion within an alignment-specifier since 5.2.0. Here's the bug: 59012 - alignas does not support parameter pack expansions.
You could try using alignas (std::aligned_union_t<1, Ts...>), but unfortunately gcc only implements aligned_union since 5.1.0, so it's only slightly better.
If you want to work with older compilers, you'll have to write your own constexpr max function (since older versions of gcc don't implement constexpr max(std::initializer_list<T>) either) and compute the maximum alignment yourself, as alignas(max({alignof(T)...})).

A: This looks like bug c++/59012 in GCC, which was fixed in GCC 5.2.  Your example compiles fine with Clang 3.5.1.
It's interesting to note that GCC properly complains about the parameter pack if you omit the ellipses entirely:
14 : error: parameter packs not expanded with '...':
uint8_t i4 alignas(Ts);
^

You're not going to be able to (easily) get this to work with GCC 4.8.x; it's just too stupid.  With GCC 4.9 and later, however, you can use the following idea, which I adapted from ecatmur's suggestion to use a constexpr max.
template<int...>
struct maxInts {};

template<int A, int B, int... Cs>
struct maxInts<A, B, Cs...> {
    const static int value = A > B ? maxInts<A, Cs...>::value : maxInts<B, Cs...>::value;
};

template<int A, int B>
struct maxInts<A, B> {
    const static int value = A > B ? A : B;
};

template<int A>
struct maxInts<A> {
    const static int value = A;
};

This just lets you get the maximum of any number of integers at compile time, as in:
const int x = maxInts<1, 2, 3, 4, 5>::value; // x == 5

Now your troublesome alignas looks like this:
uint8_t i4 alignas(maxInts<alignof(Ts)...>::value);

Here's a working example.


text:
Q: Pandoc: applying a style to all images when exporting to docx? I used to ask this question a few years ago, and back then it was not possible to apply a style to all images when exporting to docx using Pandoc.
Today, I wonder whether this still is true? I tried a bit using Pandoc 2.9.x, and images still seem to have applied the generic "Normal" style:

It would be nice to have a style like "Picture" which is applied to each image in the docx. Any way to do this?

A: Images by themselves cannot have any style, you have to wrap an image into a block, that can have custom attributes. I replace figure elements with a pair of an image and a caption, something like this:
funFigure = function(element)
    local attrfigure = pandoc.Attr( "", { }, {{"custom-style", "Picture" }} )
    local attrfiguretext = pandoc.Attr( "", { }, {{"custom-style", "Picture Caption" }} )
    local figuretext = pandoc.Div(pandoc.Para(element.content[1].caption), attrfiguretext)
    element.content[1].caption = pandoc.Null
    local figure = pandoc.Div(element, attrfigure)
    return { figure, figuretext }
end


text:
Q: YAML output from rails console When executing a command like y Grau.all in rails console I am getting these strange !binary strings instead of the attribute's name. Any idea how to fix this?
Thanks.
irb(main):003:0> y Grau.all
  ←[1m←[36mGrau Load (0.0ms)←[0m  ←[1mSELECT "graus".* FROM "gr
  ←[1m←[35mEXPLAIN (0.0ms)←[0m  EXPLAIN QUERY PLAN SELECT "grau

EXPLAIN for: SELECT "graus".* FROM "graus"
0|0|0|SCAN TABLE graus (~1000000 rows)

---
- !ruby/object:Grau
  attributes:
    !binary "aWQ=": 27
    !binary "bm9tZQ==": 1 Grau
    !binary "Y3JlYXRlZF9hdA==": 2012-04-06 21:24:34.553163000 Z
    !binary "dXBkYXRlZF9hdA==": 2012-04-06 21:24:34.553163000 Z
- !ruby/object:Grau
  attributes:
    !binary "aWQ=": 28
    !binary "bm9tZQ==": 2 Grau
    !binary "Y3JlYXRlZF9hdA==": 2012-04-06 21:24:34.599963000 Z
    !binary "dXBkYXRlZF9hdA==": 2012-04-06 21:24:34.599963000 Z

[UPDATES]
irb(main):001:0> Grau.find(1)
  ←[1m←[36mGrau Load (43.8ms)←[0m  ←[1mSELECT "graus".* FROM "graus" WHERE "grau
s"."id" = ? LIMIT 1←[0m  [["id", 1]]
=> #<Grau id: 1, nome: "1º Grau", created_at: "2012-04-11 15:51:32", updated_at:
 "2012-04-11 15:51:32">
irb(main):002:0>

I am using Rails 3.2.3, Ruby 1.9.3 on a Windows 7 64 bit.

A: I was encountering the same issue with displaying my debug(params) on one of my pages.  It was frustrating me to no end.  I probably took the long way around, but I had been using sqlite3, and knowing that I was going to use Postgres in production, I went ahead and configured the Postgres database locally (Kind of a pain in the butt).
The other thing that might have done it was on the database.yml file I added
encoding: unicode.
If you have the time and the patience it's probably best to use same database in test as you will use in production.

A: It appears to be because rails defaults to using the newer psych YAML engine, the older syck yaml engine doesn't output the !binary keys. If you're just wanting it for testing in the console you can switch back to the older yaml engine as a temp workaround:
 > y User.first
  User Load (0.0ms)  SELECT "users".* FROM "users" LIMIT 1
--- !ruby/object:User
attributes:
  !binary "aWQ=": 1
  !binary "bmFtZQ==": Example User
  !binary "ZW1haWw=": user@example.com

 > YAML::ENGINE.yamler= 'syck'
=> "syck"

 > y User.first
  User Load (1.0ms)  SELECT "users".* FROM "users" LIMIT 1
--- !ruby/object:User
attributes:
  id: 1
  name: Example User
  email: user@example.com

You would only need to do this when your ActiveRecord column names/attributes keys are encoded using Encoding::ASCII_8BIT which I think only happens with SQLite.

Update:
Since posting this answer the SQLite3 gem has been fixed to return utf8 for column names. Make sure you're using version 1.3.6 (or higher) of the sqlite3 gem. Then the default/newer psych yaml engine (which also supports human-readable unicode output) will work without problems:
 > y User.first
  User Load (0.0ms)  SELECT "users".* FROM "users" LIMIT 1
  EXPLAIN (0.0ms)  EXPLAIN QUERY PLAN SELECT "users".* FROM "users" LIMIT 1
EXPLAIN for: SELECT  "users".* FROM "users"  LIMIT 1
0|0|0|SCAN TABLE users (~1000000 rows)

--- !ruby/object:User
attributes:
  id: 1
  name: irmão
  email: user@example.com

A: I'm not sure irb, but try rails console inside your Rails application root (which will load all the activerecord objects correctly)
In Rails 2.x
<your rails app> ruby script/console

In Rails 3.x
<your rails app> rails c


text:
Q: SQL insert multiple data in a specific column (python) Hi have the following code:
def create_table():
    c.execute('CREATE TABLE IF NOT EXISTS TEST(Tournament TEXT, MATCH_TIME TEXT, TEAM_1 TEXT, TEAM_2 TEXT)')

create_table()

def data_entry_tournament():
    c.executemany("INSERT INTO TEST(TOURNAMENT) VALUES (?)",
        (Tournament.text.strip()))
    conn.commit()
def data_entry_Time_Event():
    c.executemany("INSERT INTO TEST(MATCH_TIME) VALUES (?)",
        (Time_Event.text.strip()))
    conn.commit()
def data_entry_TEAM_1():
    c.executemany("INSERT INTO TEST(TEAM_1) VALUES (?)",
        (Team_1.text.strip()))
    conn.commit()
def data_entry_TEAM_2():
    c.executemany("INSERT INTO TEST(TEAM_2) VALUES (?)",
        (Team_2.text.strip()))
    conn.commit()

        driver.get(link)

        Tournament = driver.find_element_by_css_selector("h2[class='sport-title']")
        if Tournament.text is not "":
            data_entry_tournament()
        for row in driver.find_elements_by_css_selector("tbody[class='ng-scope']"):
            Time_Event = row.find_elements_by_tag_name("td")[0]
            Team_1 = row.find_elements_by_tag_name("td")[1]
            Team_2 = row.find_elements_by_tag_name("td")[7]
            if Time_Event.text is not "":
                data_entry_Time_Event()
            if Team_1.text is not "":
                data_entry_TEAM_1()
            if Team_1_odds.text is not "":
                data_entry_TEAM_1_ODD()
            if Team_2.text is not "":
                data_entry_TEAM_2()

c.close()
conn.close()

My problem is that the output inside SQL is totally wrong, for every row there is only one character and the text is in vertical (and split it in every column in different row).
What i would like to have is the following table for example:
TOURNAMENT | MATCH_TIME | TEAM_1 | TEAM_2
EURO 2016 | 18:00 | SPAIN | ITALY
EURO 2016 | 12:00 | HUNGARY | PORTUGAL
and so on...
I'm new in python and sql so I'm sorry if the above code is really bad.
How can i solve the problem and display everything correctly?
Is there a better and faster method than what I wrote above, to achieve the same result?
Thanks a lot!!!

A: executemany() executes the SQL statement once for each element in the list.
You did not give it a list but a string, so it executed the SQL statement once for each element in the string, i.e., once for each character.
Just use execute() for a single execution, and don't forget the comma to make a single-element tuple:
c.execute("INSERT INTO TEST(TOURNAMENT) VALUES (?)",
        (Tournament.text.strip(),))


text:
Q: How do I printout my 2 dimensional array? Trying to build a data structure for a sudoku board, and I want to print it to the console for starters. I'm using a 2 dimensional array for represent each cell on a sudoku game and I'm having a really nooby problem printing it out.
public class Main {

public static void main(String[] args) {

    int[][] puzzleBoard = {};

    //Row 1
    puzzleBoard[1][1] = 0;
    puzzleBoard[2][1] = 0;
    puzzleBoard[3][1] = 0;
    puzzleBoard[4][1] = 0;
    puzzleBoard[5][1] = 0;
    puzzleBoard[6][1] = 0;
    puzzleBoard[7][1] = 0;
    puzzleBoard[8][1] = 0;
    puzzleBoard[9][1] = 0;

    //Row 2
    puzzleBoard[1][2] = 0;
    puzzleBoard[2][2] = 0;
    puzzleBoard[3][2] = 0;
    puzzleBoard[4][2] = 0;
    puzzleBoard[5][2] = 0;
    puzzleBoard[6][2] = 0;
    puzzleBoard[7][2] = 0;
    puzzleBoard[8][2] = 0;
    puzzleBoard[9][2] = 0;

    //Row 3
    puzzleBoard[1][3] = 0;
    puzzleBoard[2][3] = 0;
    puzzleBoard[3][3] = 0;
    puzzleBoard[4][3] = 0;
    puzzleBoard[5][3] = 0;
    puzzleBoard[6][3] = 0;
    puzzleBoard[7][3] = 0;
    puzzleBoard[8][3] = 0;
    puzzleBoard[9][3] = 0;

    //Row 4
    puzzleBoard[1][4] = 0;
    puzzleBoard[2][4] = 0;
    puzzleBoard[3][4] = 0;
    puzzleBoard[4][4] = 0;
    puzzleBoard[5][4] = 0;
    puzzleBoard[6][4] = 0;
    puzzleBoard[7][4] = 0;
    puzzleBoard[8][4] = 0;
    puzzleBoard[9][4] = 0;

    //Row 5
    puzzleBoard[1][5] = 0;
    puzzleBoard[2][5] = 0;
    puzzleBoard[3][5] = 0;
    puzzleBoard[4][5] = 0;
    puzzleBoard[5][5] = 0;
    puzzleBoard[6][5] = 0;
    puzzleBoard[7][5] = 0;
    puzzleBoard[8][5] = 0;
    puzzleBoard[9][5] = 0;

    //Row 6
    puzzleBoard[1][6] = 0;
    puzzleBoard[2][6] = 0;
    puzzleBoard[3][6] = 0;
    puzzleBoard[4][6] = 0;
    puzzleBoard[5][6] = 0;
    puzzleBoard[6][6] = 0;
    puzzleBoard[7][6] = 0;
    puzzleBoard[8][6] = 0;
    puzzleBoard[9][6] = 0;

    //Row 7
    puzzleBoard[1][7] = 0;
    puzzleBoard[2][7] = 0;
    puzzleBoard[3][7] = 0;
    puzzleBoard[4][7] = 0;
    puzzleBoard[5][7] = 0;
    puzzleBoard[6][7] = 0;
    puzzleBoard[7][7] = 0;
    puzzleBoard[8][7] = 0;
    puzzleBoard[9][7] = 0;

    //Row 8
    puzzleBoard[1][8] = 0;
    puzzleBoard[2][8] = 0;
    puzzleBoard[3][8] = 0;
    puzzleBoard[4][8] = 0;
    puzzleBoard[5][8] = 0;
    puzzleBoard[6][8] = 0;
    puzzleBoard[7][8] = 0;
    puzzleBoard[8][8] = 0;
    puzzleBoard[9][8] = 0;

    //Row 9
    puzzleBoard[1][9] = 0;
    puzzleBoard[2][9] = 0;
    puzzleBoard[3][9] = 0;
    puzzleBoard[4][9] = 0;
    puzzleBoard[5][9] = 0;
    puzzleBoard[6][9] = 0;
    puzzleBoard[7][9] = 0;
    puzzleBoard[8][9] = 0;
    puzzleBoard[9][9] = 0;

    int rows = 9;
    int columns = 9;

    int i, j;

    for (i = 1; i < rows; i++){
        for(j = 1; j < columns; j++){
            System.out.print(puzzleBoard[i][j] + " ");

        }
        System.out.println( "" );
    }
}

}

A: You didn't specify a size for your array.
int[][] puzzleBoard = {}; should be int[][] puzzleBoard = new int[10][10];
There is no need to initialize your array with a for loop or line by line if you're only filling it with 0.
Then arrays are 0 base indexed. So the first element will be at position [0][0] and the last one at position [9][9].
You could also remove your two variables rows and columns.
Finally, you should modify your for loop to start from 0.
for (i = 0; i < puzzleBoard.length; i++){
        for(j = 0; j < puzzleBoard[i].length; j++){
            System.out.print(puzzleBoard[i][j] + " ");
        }
        System.out.println( "" );
    }

To learn more about arrays in Java, I advise you to read this.

A: You should initialize the array elements with a for loop as well!
Also, remember, Java arrays are zero based, so the topmost cell would be puzzleboard[0][0]!
You should also specify a size for your array - int[][] puzzleBoard = new int[10][10];

A: You should use java.util.Arrays.deepToString() to print 2D arrays:

Returns a string representation of the "deep contents" of the
  specified array. If the array contains other arrays as elements, the
  string representation contains their contents and so on. This method
  is designed for converting multidimensional arrays to strings.
The string representation consists of a list of the array's elements,
  enclosed in square brackets ("[]"). Adjacent elements are separated by
  the characters ", " (a comma followed by a space). Elements are
  converted to strings as by String.valueOf(Object), unless they are
  themselves arrays.


text:
Q: Strange behavior with `find -delete` I'm using Ubuntu 12.04 with 2 x 2TB SATA3 harddisks in software RAID1. The filesystem is ext4 with data=writeback.
When using find . -maxdepth 1 -name '*' -delete to delete a large number of files in a directory, doing df at intervals show that:
Initially a large number of files get deleted, and iotop shows the find operation taking most of the IO.

Later df shows that the number of files remain constant, and iotop shows that IO usage is now dominated by jbd2 and md4_raid1.

Few minutes later, df shows the number of files dropping once more.
Can anyone explain this behavior? Is this normal or is there something wrong with my server? Also, how can 3 processes all have 99.99% IO usage at the same time?

A: It's what I would expect. Find finds files - i.e. it reads from the VFS, when the data is not in cache it needs to be fetched from disk. As it processes each file, it enqueues the changes to be written. At some point the write buffer gets full and the changes must be written to the disk - at this point the process doing the writes will be blocked making further write OR READ requests until there's space to buffer more writes.

A: You can prevent the system from being blocked by reducing the I/O priority of the process:
ionice -c3 nice -15 find ... -delete

If that's not enough then you can use chrt to put the process into the SCHED_IDLE class.


text:
Q: Spring boot data jpa OneToMany relation doesn't add foreign key I have relation
public class Website {
    @OneToMany(mappedBy = "website", fetch = FetchType.EAGER)
    private List<WebsiteCategory> website;
}

public class WebsiteCategory {
    @ManyToOne
    private Website website;
}

And I want to save object website with a list of websiteCategory like this
webSiteRepository.save(website);

and list with WebsiteCategories save without foreign key from website
And my question is how to save a website with a list of websitecategory with foreign key

A: With this mapping a join table is created website_website_category. You need to add @JoinColumn(name = "website_id")  to your @ManyToOne.
Additionally consider if you have here a @ManyToMany relationship. A website can have many categories - hence a List. But also one category may be in many websites.


text:
Q: Django deadline-timer I am building a management application for a company. One of the things the application can do is start new projects. The model for this is:
class Project(models.Model):
    employees = models.ManyToManyField(settings.AUTH_USER_MODEL)
    division = models.ForeignKey(Division)
    client = models.ForeignKey(Company)
    description = models.CharField(max_length=120)
    timestamp = models.DateTimeField(auto_now_add=True)
    deadline = models.DateField(blank=True)
    active = models.BooleanField(default=True)

As you can see in the model, an employee can set a deadline for their project. I need to be able to send the user notifications if they are close to their deadline.
For example, if the deadline is in two days, the user will get a notification like "Your deadline for projectname is over two days". So basically, what I need is a deadline timer.
What is the logic for this? I don't really know where to start with this.


text:
Q: Find, count and sort all audio files. ALAC (M4A) files I'm putting a script together to sort a very large music collection. It's approx 22000 albums, a mixture of FLAC, WAV, AIFF, M4A (AAC & ALAC).
So far, I can sort by file type and get a total size of each type.
ftypes=$(find . -type f | grep -iE ".*\.[a-zA-Z0-9]*$" | sed -e 's/.*\(\.[a-zA-Z0-9]*\)$/\1/' | sort -f | uniq -i)

for ft in $ftypes
do
echo -n "$ft "
find . -name "*${ft}" -print0 | xargs -0 du -hc | grep total | awk '{print $1}'
done

I'd like to edit this to get the number of files by file type as well as the total size.
Now, the M4A files could be either AAC or ALAC, and I'd like to know how many of each.
I can find and print a list of ALAC files with
find . -name \*.m4a | while read file; do avprobe "$file" 2>&1 | grep -q 'Audio: alac' && echo "$file"; done

but I'm lost on how to get the total file count and size, instead of a list of file names, and combine it all into one script.
Basically, I'd like to output:

*

*List of file types

*Number of files by filetype

*Total size by filetype

*M4A total number of AAC & total size

*M4A total number of ALAC & total size

Depending on how well this works, I may consider using this to sort files into directories based on the output.

A: You should decompose your goal into several steps easier to solve. This will have two advantages:

*

*It will be easier to solve,

*The resulting code will be clearer and more reusable.

The scripts below basically follows these steps:

*

*Generate raw statistic files. An easy way is to append the file size and the file name in a temporary file named after the original file extension. So, if you have the file /path/to/foo.mp3 which is 3000000 large, it will append 3000000 /path/to/foo.mp3 at the end of a temporary file named mp3.

*Handle specific cases. Here it will process the temporary file m4a and create the two other files m4a_aac and m4a_alac based on the test you gave in the question.

*Generate output. All the needed information being now available, it just has to:

*

*Count the number of line in each temporary file to determine the number of file of this type,

*Sum up each size to get the total size of files of this type.

Here is the script:
#!/bin/sh

# This script takes the searched directory as first parameter.
# For instance: ./this-script.sh ~/Music

: ${1:?"You must pass the search directory as first parameter."}
searchdir="$1"

# Create a temporary directory
statsdir=""
trap 'rm -rf $statsdir' EXIT
statsdir=$(mktemp -d "/tmp/tmp.XXXXXXXXXX") || exit 1

# Generate one listing file per extension
awkscript='/\.[[:alnum:]]+$/ {print $0 >statsdir"/"$(NF)}'
# For Linux: stat -c "%s %n"
# For Mac: stat -f "%z %N"
find "$searchdir" -type f -exec stat -f "%z %N" {} + | \
    awk -F '.' -v statsdir="$statsdir" "$awkscript"

# Distinguish between m4a/AAC and m4a/ALAC
if [ -f "$statsdir/m4a" ]; then
    input="$statsdir/m4a"
    while IFS= read -r line; do
        filename=${line#* }
        if avprobe "$filename" 2>&1 | grep -q 'Audio: alac'; then
            echo "$line" >> "$statsdir/m4a_alac"
        else
            echo "$line" >> "$statsdir/m4a_aac"
        fi
    done < "$input"
    rm "$statsdir/m4a"
fi

# Generate and display result
{
    printf "Type Count Size\n"
    for extension in $(ls "$statsdir"); do
        count=$(wc -l "$statsdir/$extension" | cut -d ' ' -f 1)
        totalsize=$(awk '{s+=$1} END {print s}' "$statsdir/$extension")
        printf "%s %d %d\n" "$extension" "$count" "$totalsize"
    done
} | column -t


text:
Q: Не отображаются товары woocommerce + wordpress Есть сайт на wordpress с плагином woocommerce, в нём уже большое кол-во товаров и категорий, однако есть проблема: при добавлении нового товара через woocommerce api товар не появляется в категории, т.е. его видно в админке и можно открыть по прямой ссылке, однако рядом с другими товарами в своей категории его нет.
Код добавления товара
`wcapi = API(
    url="url",
    consumer_key="xxx",
    consumer_secret="xxx",
    version="wc/v3",
    timeout=1000,
    verify_ssl=False,
    query_string_auth=True
)

w = wcapi.post('products', data={
        'name': str(i[1]),
        'type': 'simple',
        'regular_price': str(i[2]),
        'description': 'desc',
        'short_description': 'short desc',
        'categories': [
            {'id': str(i[0])}
        ],
        'images': [
            {'src': str(i[3])}
        ],
        'meta_data': [
            {}, {}
        ]
    }).json()
    print(w['id'])`

A: Проблема была в ограничении кол-во отображаемых товаров, исправил добавлением данного кода в functions.php
add_filter( 'loop_shop_per_page', function ( $cols ) {
      return 25;
    }, 25 );


text:
Q: If a ball bounces from a wall, then when (if ever) does it bounce upwards, rather than "loses energy"? If a ball bounces from a wall, then when (if ever) does it bounce upwards, rather than "loses energy"?
I.e. when does the following occur?
This is simulated using "bouncing ball equation" and the direction change is merely about making $x+\Delta x$ to $x- \Delta x$.

In the plot the colors don't matter (it's just default matplotlib to plot in different colors). There's a non-visualized wall at $x=15$. The last dot is over, since with this chosen $t$, the last plot before turn ends up $x > 15$.

A: Assuming a frictionless*, perfectly elastic bounce, then bouncing off a vertical surface won't change the vertical component of the ball's motion.  If it was moving upward when it hit the wall, it still will be moving upward as it bounces away. If it was moving downward when it hit the wall, then it still will be moving downward after the bounce.

* See my comment about "angular momentum" (a.k.a., "spin") of "real" balls on your question.


text:
Q: Android - Change position and size of gallery? I have a gallery in my app, is there a way change the position of it?
I tried android:gravity="center" but that did nothing. Cant get the gallery to move.
Also can the gallery be made bigger? By an exact size too? I don't want it to be fullscreen but i do want it to be bigger than it normally is. Close to fullscreen. Nothing i've done has changed it.
Any ideas?
Thanks in advance.

A: You can use layout_width and layout_height to set the size, the Gallery can be made to be pretty much any size you like. Usually you'll chose wrap_contents or fill_parent, but if you want to you can explicitly set the height to something such as 400dp and the width you would probably want to keep fill_parent. See declaring layout in Android docs for more info.
EDIT: Here is an example in XML:
<?xml version="1.0" encoding="utf-8"?>
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gallery"
    android:layout_width="fill_parent"
    android:layout_height="400dp"
    android:spacing="2px"
    />


text:
Q: mapping class group relations The question I want to ask is vague in a sense. We have examples of mapping class relations, e.g. lantern relation, chain relations, etc. For instance the latern relation on a disk with three boundary components $a$, $b$ and $c$ is: $t_a t_b t_c t_d=t_{ab}t_{bc}t_{ca}$, where $d$ is the curve enclosing all three boundary components and $t_{ij}$ encloses $i$ and $j$ in the most obvious way. While I know how this relation is proved, I have no idea how one comes up with this kind of relations.I want to know if there is general principle to obtain these relations, and whether it is possible to figure out different factorizations of a given element in a mapping class group (of a surface with or without boundary). Is there a more intuitive way to explain for instance the lantern relation?

A: I can answer your last question: there exist natural ways of embedding the fundamental group of the unit tangent bundle of a surface into the mapping class group, and the lantern relation is the image of an "obvious" relation in the unit tangent bundle group (coming from a visually obvious relation in the fundamental group of a surface).  This way of coming up with the lantern relation was discovered independently by myself and by Margalit--McCammond; see our papers
A. Putman
An infinite presentation of the Torelli group
Geom. Funct. Anal. 19 (2009), no. 2, 591-643.
and
Margalit, Dan; McCammond, Jon Geometric presentations for the pure braid group. J. Knot Theory Ramifications 18 (2009), no. 1, 1–20.
In my paper, this can be found in Section 3.1.2.  I also discuss this in my survey paper
A. Putman
The Torelli group and congruence subgroups of the mapping class group
in "Moduli spaces of Riemann surfaces (Park City, UT, 2011)", 167-194,
IAS/Park City Math. Ser., 20 Amer. Math. Soc., Providence, RI.
This occurs towards the beginning (on page 6 in the version on my webpage).  All of my papers can be found here.


text:
Q: Uninstall macOS app I am testing my macOS app, and I need to uninstall it to check some special features. For iOS apps this is very simple, I simple remove the app from the simulator and then I reinstall it. How can I do the same thing for macOS?
I've already tried to delete the app from /Users/myuser/Library/Developer/Xcode/DerivedData/Build/Products/Debug/myapp.app
But that doesn't work. If I run my project again, all previous settings and saves are kept.
How can I completely remove an app made in Xcode for macOS development?
The topic: Delete app from OSX simulator in Xcode didn't help me.

A: This command will delete whatever's in the UserDefaults database for your app:
defaults delete com.mywebsite.myapp

Replace com.mywebsite.myapp with the bundle ID of your application.
If you have items other than just UserDefaults settings, they'll appear in the home/Library/Containers folder in a folder named after your app bundle (assuming your app is sandboxed; otherwise check home/Library/Application Support). You'll find the plist file for your UserDefaults in here as well, although deleting that using the Finder isn't reliable, since the system sometimes caches the plists in memory, so the defaults command is still the best way to clear that.

A: There are many apps that allow you to thoroughly uninstall apps, for example AppCleaner. However I'd try to use the clean build folder option within Xcode first.


text:
Q: Как организовать потоки для паралельного использования ConcurrentLinkedQueue с ExecutorService? У меня поиск который собирает txt файлы в очередь ConcurrentLinkedQueue, и потом в нескольких потоках одновременно проверяет содержимое этих файлов на соответствие заданной строке. В общем многопоточный поиск файла содержащего какую-то строку. Когда один из потоков находит заданную строку, он останавливает все остальные. Сам обход файловой системы у меня выполняется в отдельном потоке.
Для пула потоков использую ExecutorService.
Но когда я начал тестировать код то получилось что правильно срабатывает только один раз из 10 примерно, во всех остальных случаях падает с java.util.concurrent.CancellationException, причем указывает на строку в тесте где вызывается метод get() у Future.
Помогите пожалуйста разобраться что я не так делаю?
Основной класс в котором ExecutorService создается:
public class ParallelSearch implements Parallel {
    // останавливает все потоки (вызывает cancel в цикле по threads).
    private final Stopper stopper;
    // лист запущенных потоков.
    private final List<Future<File>> threads;
    // размер пула потоков.
    private final int amountThreads;
    // очередь в которой храняться файлы.
    private final Queue<File> container;
    private final ExecutorService service;
    // поток поиска txt файлов по диску.
    private Thread searchByFileSystem;

    public ParallelSearch(final int amountThreads) {
        this.service = Executors.newFixedThreadPool(amountThreads);
        this.amountThreads = amountThreads;

        this.container = new ConcurrentLinkedQueue<>();
        this.threads =   new ArrayList<>(amountThreads);
        this.stopper =   new Stopper();
    }

    @Override
    public List<Future<File>> startParallelSearch(
            final String pathToRoot,
            final String targetText) {

        this.searchByFileSystem(pathToRoot);
        this.searchByFilesContent(targetText);
        return this.threads;
    }

    // поток обходит файловую систему в поисках txt файлов и добавляет в очередь.
    private void searchByFileSystem(final String pathToRoot) {
        final Thread searchByFileSystem = new Thread(new Runnable() {
            @Override
            public void run() {
                new CollectingTXTFiles(
                        pathToRoot, container)
                        .collectTXTFromRoot();
            }
        });
        this.service.submit(searchByFileSystem);
        this.searchByFileSystem = searchByFileSystem;
    }

    // добавляем в пул потоки для поиска строки по содержимому txt файлов
    private void searchByFilesContent(final String targetText) {
        for (int i = 0; i < (this.amountThreads - 1); i++) {
            final Future<File> taskRead =
                    this.service.submit(new Callable<File>() {
                        @Override
                        public File call() throws Exception {
                            return new SearchByFileContent(container, stopper)
                                    .scanQueue(targetText);
                        }
                    });
            // добавляем потоки поиска по контенту в лист Future'ов
            this.threads.add(taskRead);
        }
    }

    /**
     * Останавливает все потоки ссылка его экземпляр есть у всех потоков.
     * Если один из потоков найдет искомую строку, вызовет stopAllSearchingThread().
     */
    class Stopper {
        void stopAllSearchingThread() {
            searchByFileSystem.interrupt();
            for (Future future : threads) {
                future.cancel(true);
            }
        }
    }
}

Вот так я вызываю:
@Test
public void whenThen() throws ExecutionException, InterruptedException {
    Parallel parallel = new ParallelSearch(5);
    final List<Future<File>> futures = parallel.startParallelSearch(dir.getAbsolutePath(), "test");

    String result = null;

    for (Future<File> f : futures) {
        String name = f.get().getName();
        if (!name.equals("-1")) {
            result = name;
        }
    }

    Assert.assertThat(result, is("test2.txt"));
}

Класс который по файловой системе ищет txt файлы в паралельном потоке, запускается тем-же объектом ExecutorService.:
public class CollectingTXTFiles implements Collector {
    private final String root;
    private final Queue<File> files;

    public CollectingTXTFiles(final String root,
                              final Queue<File> files) {
        this.root = root;
        this.files = files;
    }

    @Override
    public void collectTXTFromRoot() throws IllegalArgumentException {
        final File root = new File(this.root);

        if (!root.exists() || !root.isDirectory()) {
            throw new IllegalArgumentException(String.format(
                    "Directory: '%s' not found", this.root));
        }

        this.selectTXTFiles(root);
    }

    private void selectTXTFiles(final File file) {
        if (Thread.currentThread().isInterrupted()) {
            return;
        }

        if (file.getName().endsWith(".txt") &&
                !file.isDirectory()) {

            this.files.add(file);
        }

        if (file.isDirectory()) {
            final File[] childes = file.listFiles();
            assert Objects.nonNull(childes);

            for (File f : childes) {
                selectTXTFiles(f);
            }
        }
    }
}

Класс осуществляющий поиск строки, по содержанию каждого файла в отдельности:
public class SearchByFileContent implements SearchByFile {
    private final Queue<File> paths;
    private final ParallelSearch.Stopper stopper;

    public SearchByFileContent(final Queue<File> paths,
                               final ParallelSearch.Stopper stopper) {
        this.stopper = stopper;
        this.paths = paths;
    }

    @Override
    public File scanQueue(final String target) {
        while (this.paths.size() != 0 && !Thread.currentThread().isInterrupted()) {
            System.out.println(paths.size());
            final File next = this.paths.poll();
            final File result = getFileWhichContains(target, next);

            if (result != null && !result.getName().equals("-1")) {
                this.stopper.stopAllSearchingThread();
                return result;
            }
        }
        return new File("-1");
    }

    private File getFileWhichContains(final String target, final File file) {
        final StringBuilder sb = new StringBuilder();
        if (file == null) return new File("-1");
        try (BufferedReader reader = new BufferedReader(
                new FileReader(file))
        ) {

            String line;

            while (Objects.nonNull(line = reader.readLine())) {
                sb.append(line);
            }

            if (new String(sb).contains(target)) {
                return file;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new File("-1");
    }
}

Последние 2 класса, в однопоточном режиме, юнит тесты проходят нормально.
Может быть у меня обход файлов идет впереди их сбора в очередь? Или что-то еще? Помогите пожалуйста это решить.

A:  final Thread searchByFileSystem = new Thread(new Runnable() {
            @Override
            public void run() {
                new CollectingTXTFiles(
                        pathToRoot, container)
                        .collectTXTFromRoot();
            }
        });
        this.service.submit(searchByFileSystem);

А зачем создаете Thread если потом передаете его в ExecutorService? Делайте сразу Runnable. Вы же тред не запускаете через start() а через пул.
А вообще причина простая. Когда вы делаете get() вы ждете завершение работы таска и возврата им результата. Представьте что первый таск из списка работает 1 мин, а второй 10 секунд (и при этом находит текст). В этой ситуации вы получите исключение, т.к. через 10 секунд будет найдет файл, все таски получат событие отмены, а ваш тест ждет ответа от того таска, который работал но его отменили.
Что бы все таки получить результат работы вашего кода, стоит использовать систему колбеков, например на базе Consumer. Для этого надо:
Добавить в базовый класс ссылку на Consumer и передать его в конструкторе, т.е.
public class ParallelSearch implements Parallel {
   private Consumer<File> callback;
   ...
   public ParallelSearch(final int amountThreads, Consumer<File> callback) {
        this.callback = callback;

  public Consumer<File> getCallback() {
        return callback;
  }

  public void setCallback(Consumer<File> callback){
       this.callbacl = callback;
  }

Затем, модифицировать метод scanQueue (только прокиньте в класс с ним ссылку на ParallelSearch) изменив
if (result != null && !result.getName().equals("-1")) {
            this.stopper.stopAllSearchingThread();
            return result;
}

на
 if (result != null && !result.getName().equals("-1")) {
      if (parallelSearch.getConsumer() != null){
          synchronized (parallelSearch.getConsumer()){
                 if (parallelSearch.getConsumer() != null){
                     parallelSearch.getConsumer().accept(result);
                     parallelSearch.setConsumer(null);
                 }
          }
      }
      this.stopper.stopAllSearchingThread();
      return result;
 }

Единственное, что скорей всего саму ссылку на Consumer надо завернуть в AtomicReference, но это уж сами.


text:
Q: Image is send in request.POST but cleaned in form.cleaned_data I've a Profile form that accepts an Image to be used to display User's Profile Pic.
I don't have problems submitting the form, but when accessing the admin panel I can see that the file has not been saved.

Even thought, It is send in request.POST:

'photo': ['es_usted_inteligente.jpg']}>

SIGNUP REQUEST POST:  <QueryDict: {'csrfmiddlewaretoken': ['SXoar0hPxsKCcMgFG1lJ5XoxjCzbEEqa9x5livVw4M0m9ZB25SGKmL3IUogJnxHz'], 'first_name': ['a'], 'last_name': ['gonzales']
, 'username': ['agonzales'], 'dni': ['744484848'], 'phone_number': ['89898989'], 'birthdate_month': ['1'], 'birthdate_day': ['1'], 'birthdate_year': ['1980'], 'email': ['agon
zales@gmail.com'], 'password1': ['caballo123'], 'password2': ['caballo123'], 'shipping_address1': ['Urb. La Merced Mz.G Lot.32'], 'address_reference': ['Tienda Roja'], 'shipp
ing_department': ['San Martín'], 'shipping_province': ['El Dorado'], 'shipping_district': ['Shatoja'], 'photo': ['es_usted_inteligente.jpg']}>

profile_form.cleaned_data:

'photo': None}

  profile_form.cleaned_data: {'dni': '48494949', 'phone_number': '9898989', 'birthdate': datetime.date(1980, 1, 1), 'shipping_address1': 'Urb. La Merced Mz.G Lot.32', 'address
_reference': 'Tienda Roja', 'shipping_department': 'Lambayeque', 'shipping_province': 'Chiclayo', 'shipping_district': 'Saña', 'photo': None}

View:
@transaction.atomic
def signupView(request):
    peru = Peru.objects.all()
    department_list = set()
    province_list = set()
    district_list = set()
    for p in peru:
        department_list.add(p.departamento)
    department_list = list(department_list)
    # print("Department List: ", department_list)
    if len(department_list):
        province_list = set(Peru.objects.filter(departamento=department_list[0]).values_list("provincia", flat=True))
        # print("Provice List: ", province_list)
        province_list = list(province_list)
        # print("dfsfs", province_list)
    else:
        province_list = set()
    if len(province_list):
        district_list = set(
            Peru.objects.filter(departamento=department_list[0], provincia=province_list[0]).values_list("distrito",
                                                                                flat=True))
        # print("district List: ", district_list)
    else:
        district_list = set()

    if request.method == 'POST':

        #####

        peru = Peru.objects.all()
        department_list = set()
        province_list = set()
        district_list = set()
        for p in peru:
            department_list.add(p.departamento)
        department_list = list(department_list)

        if len(department_list):
            province_list = set(
                Peru.objects.filter(departamento__in=department_list).values_list("provincia", flat=True))

            province_list = list(province_list)

        else:
            province_list = set()
        if len(province_list):
            district_list = set(
                Peru.objects.filter(departamento__in=department_list, provincia__in=province_list).values_list(
                    "distrito",
                    flat=True))

        else:
            district_list = set()

        #####

        user_form = SignUpForm(request.POST)
        profile_form = ProfileForm(district_list, province_list, department_list, request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            username = user_form.cleaned_data.get('username')
            signup_user = User.objects.get(username=username)
            customer_group = Group.objects.get(name='Clientes')
            customer_group.user_set.add(signup_user)
            raw_password = user_form.cleaned_data.get('password1')
            user.refresh_from_db()  # This will load the Profile created by the Signal

            profile_form = ProfileForm(district_list, province_list, department_list, request.POST,
                                       instance=user.profile)  # Reload the profile form with the profile instance
            profile_form.full_clean()  # Manually clean the form this time. It is implicitly called by "is_valid()" method
            profile_form.save()  # Gracefully save the form

            user = authenticate(username=username, password=raw_password)
            login(request, user)

            return redirect('carrito_de_compras:cart_detail')

        else:
            print(user_form.errors)
            print(profile_form.errors)

    else:

        user_form = SignUpForm()

        profile_form = ProfileForm(district_list, province_list, department_list)

    return render(request, 'accounts/signup.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })

models.py:
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    birthdate = models.DateField(null=True, blank=True)
    dni = models.CharField(max_length=30, blank=True)
    phone_number = models.CharField(max_length=30, blank=True)
    shipping_address1 = models.CharField(max_length=100, blank=False)
    address_reference = models.CharField(max_length=100, blank=False)
    shipping_department = models.CharField(max_length=100, blank=False)
    shipping_province = models.CharField(max_length=100, blank=False)
    shipping_district = models.CharField(max_length=100, blank=False)
    photo = models.ImageField(upload_to='profile_pics', default='profile_pics/default_profile_pic_white.png')

    def __str__(self):
        return str(self.user.first_name) + "'s profile"

forms.py
class ProfileForm(ModelForm):
    MONTHS = {
        1:'ene', 2:'feb', 3:'mar', 4:'abr',
        5:'may', 6:'jun', 7:'jul', 8:'ago',
        9:'set', 10:'oct', 11:'nov', 12:'dic'
    }

    def __init__(self, district_list, province_list, department_list, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        self.fields['shipping_district'] = forms.ChoiceField(label='Distrito', choices=tuple([(name, name) for name in district_list]))
        self.fields['shipping_province'] = forms.ChoiceField(label='Provincia', choices=tuple([(name, name) for name in province_list]))
        self.fields['shipping_department'] = forms.ChoiceField(label='Departamento', choices=tuple([(name, name) for name in department_list]))

    dni = forms.CharField(label='DNI', max_length=100, required=True)
    phone_number = forms.CharField(label='Celular')
    birthdate = forms.DateField(label='Fecha de nacimiento', widget=SelectDateWidget(years=range(1980, 2012), months=MONTHS))
    shipping_address1 = forms.CharField(label='Dirección de envío', max_length=100, required=True)
    address_reference = forms.CharField(label='Referencia', max_length=100, required=False)
    photo = forms.ImageField(label='Foto de perfil', required=False)

    class Meta:
        model = Profile
        fields = ('dni', 'phone_number', 'birthdate', 'shipping_address1',
                  'address_reference', 'shipping_department', 'shipping_province', 'shipping_district', 'photo')

UPDATE 1:
After adding request.FILES to :

    user_form = SignUpForm(request.POST, request.FILES)
    profile_form = ProfileForm(district_list, province_list, department_list, request.POST, request.FILES)

I cannot find the attribute photo in request.POST:
SIGNUP REQUEST POST:  <QueryDict: {'csrfmiddlewaretoken': ['8xcGwGg7z86OclANaEYwdB49u5hrCjOy7gFKSgoqmhxS0CmzeBIUgnYUdRyTnzqJ'], 'first_name': ['g'], 'last_name': ['gonzales']
, 'username': ['ggonzales'], 'dni': ['45484545'], 'phone_number': ['968484848'], 'birthdate_month': ['1'], 'birthdate_day': ['1'], 'birthdate_year': ['1980'], 'email': ['ggon
zales@gmail.com'], 'password1': ['caballo123'], 'password2': ['caballo123'], 'shipping_address1': ['Urb. La Merced Mz.G Lot.32'], 'address_reference': ['Tienda Roja'], 'shipp
ing_department': ['Huancavelica'], 'shipping_province': ['Castrovirreyna'], 'shipping_district': ['Castrovirreyna']}>

But now, profile_form.cleaned_data has at least the deault pic instead of None :
Profile Cleaned Data:  {'dni': '45484545', 'phone_number': '968484848', 'birthdate': datetime.date(1980, 1, 1), 'shipping_address1': 'Urb. La Merced Mz.G Lot.32', 'address_re
ference': 'Tienda Roja', 'shipping_department': 'Huancavelica', 'shipping_province': 'Castrovirreyna', 'shipping_district': 'Castrovirreyna', 'photo': <ImageFieldFile: profil
e_pics/default_profile_pic_white.png>}

HTML for form:
 <form method="POST" enctype="multipart/form-data" action=".">
                        {% csrf_token %}

                                {{ user_form.first_name.label_tag }}

                                    {{ user_form.first_name.errors }}
                                    {{ user_form.first_name }}

                                {{ user_form.last_name.label_tag }}

                                    {{ user_form.last_name.errors }}
                                    {{ user_form.last_name }}

                                {{ user_form.username.label_tag }}

                                    {{ user_form.username.errors }}
                                    {{ user_form.username }}

                                {{ profile_form.dni.label_tag }}
                                {{ profile_form.dni }}

                                {{ profile_form.phone_number.label_tag }}
                                {{ profile_form.phone_number }}

                                {{ profile_form.birthdate.label_tag }}
                                {{ profile_form.birthdate }}

                                {{ user_form.email.label_tag }}
                                {{ user_form.email }}

                                    {{ user_form.password2.errors.0 }}
                                    {{ user_form.password2.errors.1 }}

                                {{ user_form.password1.label_tag }}

                                    {{ user_form.password1.errors }}
                                    {{ user_form.password1 }}

                                {{ user_form.password2.label_tag }}

                                    {{ user_form.password2 }}

                            {{ profile_form.shipping_address1.label_tag }}

                                {{ profile_form.shipping_address1.errors }}
                                {{ profile_form.shipping_address1 }}

                            {{ profile_form.address_reference.label_tag }}

                                {{ profile_form.address_reference.errors }}
                                {{ profile_form.address_reference }}

                            {{ profile_form.shipping_department.label_tag }}

                                {{ profile_form.shipping_department.errors }}
                                {{ profile_form.shipping_department }}

                            {{ profile_form.shipping_province.label_tag }}

                                {{ profile_form.shipping_province.errors }}
                                {{ profile_form.shipping_province }}

                            {{ profile_form.shipping_district.label_tag }}

                                {{ profile_form.shipping_district.errors }}
                                {{ profile_form.shipping_district }}

                            {{ profile_form.photo.label_tag }}

                                {{ profile_form.photo.errors }}
                                {{ profile_form.photo }}

                                <button class="btn btn-secondary" type="submit">Registrarse</button>

                </form>

A: You need to pick up files so you need user_form = SignUpForm(request.POST, request.FILES).
Also, make sure you've got enctype="multipart/form-data" within your form declaration in the hmtl.  Something like <form id="projectForm" method="POST" enctype="multipart/form-data" action="">


text:
Q: Laravel - Pass a variable with Query Builder function Using Laravel's query builder example is it possible to pass a variable to this function:
$someVariable = 1;

DB::table('users')
        ->where('name', '=', 'John')
        ->orWhere(function ($query) use ($someVariable) {
            $query->where('votes', '>', $someVariable)
                  ->where('title', '<>', 'Admin');
        })
        ->get();

It seems the function cannot access the variable outside of itself. I get an error: Undefined variable: $someVariable

A: You'll need to use the "use" keyword after your function, for variables outside of that function. If $someVariable is the one you want to use, this should work.
$someVariable = 1;

DB::table('users')
->where('name', '=', 'John')
->orWhere(function ($query) use($someVariable) {
    $query->where('votes', '>', $someVariable)->where('title', '<>', 'Admin');
})->get();

A: use Superglobals

$GLOBALS["someVariable"] = 1;
DB::table('users')
->where('name', '=', 'John')
->orWhere(function ($query) {
       $query->where('votes', '>', $GLOBALS["someVariable"])
       ->where('title', '<>', 'Admin');
})
->get();


text:
Q: Sorting Algorithm in c using pointers It seems that when sorting, insertion-sort would be more time-efficient then quick-sort when sorting a linkedlist. Is this true and why? thanks. Also do you guys know any website where I can practice my programming skill etc. thanks.

A: I think that insertion-sort would be much faster then quick-sort when sorting a linkedlist.


text:
Q: Swift - auto add a class instance to an array when initialising My code is setup in the following way:
class MyClass {

    let text: String

    init(text: String) {
        self.text = text
    }

}

var items = [MyClass]()

let item = MyClass(text: "sometext")

The idea is to get item into the items array, such as with:
items.append(item)

The main problem with this is that I initialise these items in a swift file, and I would get the error
Expressions are not allowed at the top level
Also, I'd prefer not to use this somewhere such as viewDidLoad() because there may be too many MyClass items.
I've tried this
class MyClass {

    let text: String

    static var items = [MyClass]()

    init(text: String) {
        self.text = text
        MyClass.items.append(self)
    }

}

as suggested here
However, after intialising several MyClass objects, items is still empty.
Is there any way I can do this?
EDIT: thank you for the suggestions so far. These were typos (using item rather than self, and items, rather than MyClass.items. This is how I've used it in my code. It compiles & still doesn't work, sadly.

A: Your code does not compile. This is the error-free code for the class.
class MyClass {

    let text: String

    static var items = [MyClass]()

    init(text: String) {
        self.text = text
        MyClass.items.append(self)
    }

}

The two things that were wrong in your code.

*

*You should be appending self to items, because self is the instance of Item that you create which is available inside init.

*static methods should be accessed with their class name.

Example:
let blah = MyClass(text: "blah")
let bleh = MyClass(text: "bleh")

print(MyClass.items.count) // Prints 2


text:
Q: Java - I think my boolean is defaulting to true for some reason I'm having an issue with my hangman program. When I run it, the label holding the  int variable "lives" is supposed to update when you guess a wrong letter. But for some reason it isn't. I've placed this in my code as a test mechanism, and it isn't appearing even here.
    if (used[letter] = false) {
    System.out.println("test");

However, when I place it here.. It DOES work..
if (finished == false) {
    boolean found = false;
    boolean www = false;
    System.out.println("test");
        if (used[letter] = false) {

It almost leads me to believe that used[letter] is true by default, when it really shouldn't be. The variable is declared at the very top. Any thoughts?
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;

public class Hangman implements ActionListener {
JFrame frame;
JPanel stats = new JPanel();
JLabel currentWordLA = new JLabel("Current word:");
JLabel triedLettersLA = new JLabel("Tried letters:");
JLabel triesLeftLA = new JLabel("Tries remaining:");
private String[] wordList = {"computer","java","activity","alaska","appearance","article",
   "automobile","basket","birthday","canada","central","character","chicken","chosen",
   "cutting","daily","darkness","diagram","disappear","driving","effort","establish","exact",
   "establishment","fifteen","football","foreign","frequently","frighten","function","gradually",
   "hurried","identity","importance","impossible","invented","italian","journey","lincoln",
   "london","massage","minerals","outer","paint","particles","personal","physical","progress",
   "quarter","recognise","replace","rhythm","situation","slightly","steady","stepped",
   "strike","successful","sudden","terrible","traffic","unusual","volume","yesterday" };
public String mysteryWord;
public int lives;
private boolean finished = false;
private boolean won = false;
private Button a[];
public boolean used[] = new boolean[26];

public static void main (String[] args) {
    Hangman gui = new Hangman();
    gui.go();
    }

class myDrawPanel extends JPanel {
    public void paintComponent(Graphics g) {
        setBackground(Color.white);
        g.setColor(Color.gray);
     g.fillRect(50, 200, 150, 20);
     g.fillRect(90,20,10,200);
     g.fillRect(90,20,60,10);
     g.setColor(Color.black);
     g.fillRect(145,20,5,25);
        g.setColor(Color.green);
            if (lives < 6 )
            g.drawOval(132,45,30,30);
            if (lives < 5 )
            g.drawLine(147,75,147,100);
        if (lives < 4 )
            g.drawLine(147,100,167,133);
        if (lives < 3 )
            g.drawLine(147,100,127,133);
        if (lives < 2 )
            g.drawLine(147,75,167,85);
        if (lives < 1 )
            g.drawLine(147,75,127,85);

        StringBuffer guessed = new StringBuffer();
            for (int cl = 0; cl < mysteryWord.length(); cl++) {
            if (used[(int)mysteryWord.charAt(cl)-'a'])
            guessed.append(mysteryWord.charAt(cl));
           else
              guessed.append("*");
           }
            currentWordLA.setText("Current word: " + guessed.toString());

         if (lives < 1) {
            g.setColor(Color.white);
            g.fillRect(70, 200, 200, 30);
            g.setColor(Color.black);
            g.drawString(mysteryWord.toString(),75,230);
            Font fff = new Font("Helvetica",Font.BOLD,36);
            g.setFont(fff);

            g.setColor(Color.red);
            g.drawString("You lose!",200,100);

            //finished = true;
            }

         if (won) {
            Font fff = new Font("Helvetica",Font.BOLD,36);
            g.setFont(fff);

//                Color red=new Color.red
            g.setColor(Color.red);

            g.drawString("You Win!",200,100);
            //finished = true;
            }
  }
 }

public void go() {

///////////////////////DESIGN BEGIN//////////////////////////////////////////////
    frame = new JFrame("Hangman");
    JPanel topPanel = new JPanel();
    myDrawPanel noosePanel = new myDrawPanel();
    JPanel bottomPanel = new JPanel();
    JPanel scorePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout( new GridLayout( 2, 0) );
    bottomPanel.setLayout( new GridLayout( 0, 2) );
    scorePanel.setSize(20,100);

    noosePanel.setBorder(BorderFactory.createTitledBorder("Your progress."));
    topPanel.setBorder(BorderFactory.createTitledBorder("Your arsenal."));
    scorePanel.setBorder(BorderFactory.createTitledBorder("Your score."));
frame.add(topPanel);
frame.add(bottomPanel);
    bottomPanel.add(scorePanel);
    bottomPanel.add(noosePanel);

//Just the stats panel.
    JButton restart = new JButton("Reset");

        currentWordLA.setFont(new Font("Verdana", Font.PLAIN, 10));
        currentWordLA.setForeground(Color.black);
        triedLettersLA.setFont(new Font("Verdana", Font.PLAIN, 10));
        triedLettersLA.setForeground(Color.black);
        triesLeftLA.setFont(new Font("Verdana", Font.PLAIN, 10));
        triesLeftLA.setForeground(Color.black);
        restart.setFont(new Font("Verdana", Font.PLAIN, 16));
        restart.setForeground(Color.red);

            stats.setLayout(new GridBagLayout());
            GridBagConstraints c = new GridBagConstraints();
            c.gridx = 0;
            c.gridy = 0;
            c.insets = new Insets(20,0,0,0);
            c.anchor = GridBagConstraints.LINE_START;
            stats.add(currentWordLA, c);
            c.gridx = 0;
            c.gridy = 1;
            c.anchor = GridBagConstraints.LINE_START;
            stats.add(triedLettersLA, c);
            c.gridx = 0;
            c.gridy = 2;
            c.anchor = GridBagConstraints.LINE_START;
            stats.add(triesLeftLA, c);
            c.gridx = 0;
            c.gridy = 3;
            c.anchor = GridBagConstraints.LINE_START;
            stats.add(restart, c);
            scorePanel.add(stats);
///////////////////////DESIGN END//////////////////////////////////////////////
///////////////////////ALPHABET BEGIN//////////////////////////////////////////
    int i;
    StringBuffer buffer;
    a = new Button[26];
    topPanel.setLayout( new GridLayout( 4,0, 10, 10) );
    for (i = 0; i <26; i++) {
           buffer = new StringBuffer();
            buffer.append((char)(i+'a'));
            a[i] = new Button(buffer.toString());
            a[i].setSize(100,100);
            a[i].addActionListener( this );
          topPanel.add(a[i]);
        }
///////////////////////ALPHABET END//////////////////////////////////////////
//Just shows the entire window.
    frame.setSize(500, 500);
    frame.setResizable(false);
    frame.setVisible(true);
//////////////////////GAMEPLAY BEGIN////////////////////////////////////////
    lives = 6;
    triesLeftLA.setText("Tries remaining: " + lives);
    mysteryWord = wordGen();

}

//Returns a random word from the wordList bank.
    private String wordGen() {
        return wordList[0 + (int)(Math.random() * ((63 - 0) + 1)) ]; //Make sure to set these to nonprinted chars eventually
    }

    public void consultWord(int letter) {
        if (finished == false) {
            boolean found = false;
        boolean www = false;
                if (used[letter] = false) {
                System.out.println("test");
                for (int cl = 0 ; cl < mysteryWord.length(); cl++) {
                if (mysteryWord.charAt(cl)==((char)(letter + 'a'))) {
                            found = true;
                        }
                    }
                if (found == false) {
                            lives = lives - 1;
                            triesLeftLA.setText    ("Tries remaining: " + lives);
                        }
                }

    used[letter] = true;

            for (int cl = 0; cl < mysteryWord.length(); cl++) {
            if (!used[(int)(mysteryWord.charAt(cl)) - 'a']){
                    www = true;
                }
            }
            if (www == false) {
                won = true;
            }
            frame.repaint();
    }
    }

    public void actionPerformed( ActionEvent e) {
        int i;
        for (i = 0; i < 26; i++) {
            if (e.getSource() == a[i]) {
            consultWord(i); }
  }
}
}

A: Make that:
if (used[letter] == false) {
    System.out.println("test");

A: if (used[letter] = false) {

You just set used[letter] to false. Try ==
Of course, to avoid this typo you shouldn't be using == but rather ...
if (!used[letter]) {


text:
Q: How do I install Windows 8 alongside Ubuntu 12.04 I have seen a many questions about installing Ubuntu 12.04 alongside Windows 8. I, however, will be installing Ubuntu 12.04 this weekend and plan on buying windows 8 sometime in the next few months.
I would like to know if I can install Ubuntu 12.04 now, and install windows 8 later without any problems. Every time I see how to install both, it is assumed windows 8 is installed first.
Thank You

A: The best way to go about this is to go to the following page Installing Ubuntu Alongside a Pre-Installed Windows with UEFI and see the comprehensive answer given there.

A: Use gparted (or other) to make room for Windows. Install Windows 8 onto the new partition.
Then boot from a live copy of ubuntu,
once in ubuntu from terminal run
sudo grub-install /dev/sda

This should restore your grub boot loader.

A: Is your system UEFI (and BIOS) or just BIOS. You have to be sure to install both systems in the same boot mode and how you partition also makes a difference.
If you only have BIOS or just want BIOS you must use MBR(msdos) partitioning not gpt. Ubuntu can use either gpt partitioning with UEFI or BIOS, but Windows only boots from gpt partitioned drives with UEFI.
Then you can just leave space or create a sda1, formatted NTFS with the boot flag for your install of Windows later. You may want to also have another NTFS partition for shared data which can be a logical partition. Windows only boots from primary partitions with BIOS and MBR(msdos) partitioning.
If you have and want UEFI Windows has additional partition requirements which you really should create in advance.
Windows Recommended UEFI-Based Disk-Partition Configurations
http://technet.microsoft.com/en-us/library/dd744301%28WS.10%29.aspx
Both Windows & Ubuntu will use the same efi partition which should be the first partition on the drive.


text:
Q: Chrome shows "Provisional headers are shown" under Request Headers for some requests I am writing a Chrome Extension which adds a request header. My code seems to work as expected but on some requests, Chrome says Provisional headers are shown, showing only the Referer and User-Agent:

I have checked "Disable cache" in the network inspector, and "hard" reloaded the page multiple times with a cache clear. Even with the extension disabled, I see this happen on the same certain requests when made by a parent webpage, but it is worrying that I do not see my header there when I would expect to. For example, testing on twitter.com, this request ( https://abs.twimg.com/a/1538144154/img/t1/web_sprite.png ) has the issue I'm describing, but not when loaded directly with the link in the address bar.
I'm testing my extension on bbc.co.uk, wikipedia.org and twitter.com, and each have a few requests which do this every time. My extension code in case it's relevant:
const setCustomReqHeader = (details) => {
    if (bCustomHeader) {
        const oNewHeaderEntry = {name: sHeaderName, value: sHeaderValue}
        details.requestHeaders.push(oNewHeaderEntry)
        return {requestHeaders: details.requestHeaders}
    }
    return {requestHeaders: details.requestHeaders};
}
chrome.webRequest.onBeforeSendHeaders.addListener(
    setCustomReqHeader,
    {urls: ["all_urls"]},
    ["blocking", "requestHeaders"]
);

Thanks to anyone who can help!