text:
Q: Deploy a simple VS2017 Django app to Azure - server error I've been trying to create a Django web app using VS2017 Preview (which includes Python tools for Visual Studio), and deploy the resulting app to Azure (I'm currently on the 30-day trial period to evaluate Azure).
I've done the following:

*

*Start VS2017, create a new project with the "Django Web Project" template. This creates a Django webpage with the bootstrap template - simple, and everything works well locally.

*In VS, go to Connected Services => Publish, select "Microsft Azure App Service", create a new App Service an an App Plan. The instances are created successfully.

*Click "Publish" to publish via VS WebDeploy. Everything looks good in the console and it says Publish: 1 succeeded, 0 failed, 0 skipped at the end.
This results in the standard Azure Welcome-start-page hostingstart.html showing, not the Django page. Once I remove that html file, there's only a The page cannot be displayed because an internal server error has occurred.. I've tried various things: Going to portal.azure.com "Application Settings", setting Python version from "Off" to "3.4" (I'd like 3.5 in fact, which one of MS's tutorial uses - but any will do for now) - then there's just a hostingstart-python.html showing, still no Django. I've tried adding a default web.config via "Add => New Item => Azure web.config (FastCGI)" in VS. I've tried editing that web.config with various values of WSGI_HANDLER (e.g. django.core.handlers.wsgi.WSGIHandler()) and DJANGO_SETTINGS_MODULE (e.g. mydjangopage.settings), I tried adding "wfastcgi" to requirements.txt, etc. Always just getting a server error.
I have been trying to do this for several hours now and I've read every possible Deployment help page from Microsoft, their blogs, and the web. All the information seems outdated, having missing pieces of information, or is just not working. At this point I'm quite disappointed and ready to give up. Isn't it supposed to be so simple? Create a new project in VS, hit "Publish", and it's supposed to work? (It's definitely not, I restarted from scratch multiple times and tried so many things.)

A: I had the same problem. I solved it as follows:
Create a Django Web App via the azure portal:

*

*Go to azure and hit the "plus sign" in the left upper corner for adding a resource

*Kick on "Web and Mobile"

*Click on "Show all"

*Type "Django" into the search field

*Select the one that is marked in the picture below and create the resource by following the instructions

Deploy on the newly created resource

*

*Go to Visual Studio and start the deployment

*Instead of creating a new azure resource out of VS select the one you just created for the deployment.

Wait a moment.

*

*It takes about 3 minutes until you can see you deployment. Before that you will get a default screen that looks a bit different than the one you already know.

*After that you should see the correct django page.

A: Right now, publishing support in VS 2017 is in a bit of a transition period. In the next couple of updates we want to get it back to a one-click system (and in the process, make it possible to publish Python apps from anywhere, not just within VS), but for now there are a couple of manual steps.
(I'll summarize the steps below, but the canonical documentation will be at https://aka.ms/PythonOnAppService - right now it's a blog post with these steps and some of the backstory)

*

*After creating your new site (either through the portal or through VS - publishing content is okay too), install one of the Python site extensions

(source: windows.net)

*Configure your web.config file to have the correct path to the site extension you installed in the scriptProcessor attribute (something like D:\home\python361x64\python.exe - see the description of each extension for the actual paths - VS 2017 also includes item templates to help set these up, so look through Add New Item for ideas)

*Update the WSGI_HANDLER and DJANGO_SETTINGS_MODULE variables as necessary (a typical value for WSGI_HANDLER for a Django app is myapp.wsgi.application, assuming you have a wsgi.py file in your project)

*Publish your site through VS.

*Use the console to install your packages - e.g. D:\home\python361x64\python.exe -m pip install -r requirements.txt
You may need to restart your site at this point if things were already running, but in general you can now publish quickly through VS without having to reinstall Python or any packages.
If you are deploying your site through ARM with a JSON template, you can also specify the site extension there: (from here)
"resources": [
  {
    "apiVersion": "2015-08-01",
    "name": "[parameters('siteName')]",
    "type": "Microsoft.Web/sites",
    ...
    "resources": [
      {
        "apiVersion": "2015-08-01",
        "name": "python352x64",
        "type": "siteextensions",
        "properties": { },
        "dependsOn": [
          "[resourceId('Microsoft.Web/sites', parameters('siteName'))]"
        ]
      },
    ...

A: *

*Create a WebApp on Azure (Do not enable python in Application Settings !)
From deployment option select local git repository:

From properties copy the git url:

*Copy virtualenv_proxy.py file from https://github.com/Azure-Samples/python-docs-hello-world into your folder.

*Create a file runtime.txt and write python-3.4 into it.

*Create a file web.3.4.config with content :
<configuration>
  <appSettings>
    <add key="WSGI_ALT_VIRTUALENV_HANDLER" value="django.core.wsgi.get_wsgi_application()" />
    <add key="WSGI_ALT_VIRTUALENV_ACTIVATE_THIS"
         value="D:\home\site\wwwroot\env\Scripts\python.exe" />
    <add key="pythonpath" value="%SystemDrive%\home\site\wwwroot" />
    <add key="WSGI_HANDLER" value="virtualenv_proxy.get_venv_handler()" />
    <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/>
    <add key="DJANGO_SETTINGS_MODULE" value="myModule.settings" />
  </appSettings>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <handlers>
      <add name="Python FastCGI" path="handler.fcgi" verb="*" modules="FastCgiModule" scriptProcessor="D:\Python34\python.exe|D:\Python34\Scripts\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" />
    </handlers>
    <rewrite>
      <rules>
        <rule name="Static Files" stopProcessing="true">
          <conditions>
            <add input="true" pattern="false" />
          </conditions>
        </rule>
        <rule name="Configure Python" stopProcessing="true">
          <match url="(.*)" ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_URI}" pattern="^/static/.*" ignoreCase="true" negate="true" />
          </conditions>
          <action type="Rewrite" url="handler.fcgi/{R:1}" appendQueryString="true" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

The only settings you need to change here is the value for DJANGO_SETTINGS_MODULE, replace myModule with your module name. All the over settings and paths should be exactly the same if you created an Web App.

*Push everything to the git url you got at point 1, Azure will detect and set up Python 3.4 and install all packages from requirements.txt.
After that everything should work. If not, connect using ftp and look into \LogFiles\wfastcgi.log for the error.


text:
Q: How to delete all files in google storage folder using python I have google cloud storage bucket path stored in one variable called GS_PATH
example of google cloud storage path is gs://test/one/
Under this i have few more folders and files.
How can i delete all under gs://test/one/ path using python code
Thanks,
Arjun

A: There is an API to do this:
from google.cloud import storage

my_storage = storage.Client()
bucket = my_storage.get_bucket('test')
blobs = bucket.list_blobs(prefix='one/')
for blob in blobs:
    blob.delete()

A: See https://cloud.google.com/storage/docs/deleting-objects#storage-delete-object-python for reference.
from google.cloud import storage

storage_client = storage.Client()
bucket = storage_client.get_bucket('bucket_name')

blobs = bucket.list_blobs(prefix='folder_prefix/')

for blob in blobs:
    blob.delete()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java program using arrays that outputs numbers of girls in different categories So I am doing a code for girl scout cookies. My array length is how many girl scouts there are and they each have a certain number of cookies. The program gets those two variables from the user and then at the end it shows with four different criteria how many girls sold how many cookies. My question is if there is another for loop I can use at the end where I assign girls into different categories. So what else can I do instead of for(int x : cookiesSold)?
import java.util.Scanner;

public class girlScoutCookies {

    public static  void main(String[] args) {

        int cookies1 = 0;
        int cookies2 = 0;
        int cookies3 = 0;
        int cookies4 = 0;
        int numOfGirls = 0;

        Scanner n = new Scanner(System.in);

        System.out.println("How many girls are in the girl scouts?");

        numOfGirls = n.nextInt();

        if(numOfGirls <= 0){
            System.out.println("There should be at least one girl selling cookies");
        }else{
            numOfGirls = numOfGirls;
        }

        int[] cookiesSold = new int[numOfGirls];

        for(int i = 0; i<numOfGirls;i++){
            System.out.println("What is the number of cookies the girl has sold");
            cookiesSold[i] = n.nextInt();
        }

        for(int x : cookiesSold){
            System.out.println("This is x: " +x);

            if(x >= 0 && x <= 10 ){
                 cookies1++;
            }else if(x >= 11 && x<=20 ){
                cookies2++;
            }else if(x >= 21 && x<=30 ){
                cookies3++;
            }else if(x >= 31 ){
                cookies4++;
            }
        }

        System.out.println("The number of girls that sold the following cookies are:\n 0 to 10 cookies:\t " + cookies1 + "\n 11 to 20 cookies:\t " + cookies2 + "\n 21 to 30 cookies:\t " + cookies3 + "\n 31 or more cookies: \t " +cookies4);

    }

}

A: Instead of 4 variables, use an array:
// Remove these:
int cookies1 = 0;
int cookies2 = 0;
int cookies3 = 0;
int cookies4 = 0;
// Replace with this:
int[] cookies = new int[4];

Next, use integer arithmetic to find the index from the cookiesSold value. Note that you must cap the index at 3:
// Remove all this:
if(x >= 0 && x <= 10 ){
    cookies1++;
}else if(x >= 11 && x<=20 ){
    cookies2++;
}else if(x >= 21 && x<=30 ){
    cookies3++;
}else if(x >= 31 ){
    cookies4++;
}
// Replace with just this line:
cookies[Math.min(x / 10, 3)]++;

For a more robust solution, use the length of the array, so to increase the number of slots, just change the size of the array:
cookies[Math.min(x / 10, cookies.length - 1)]++;


text:
Q: Reuse Aggregation in Select In the query below, does SQL need to calculate SUM(MY_INDICATOR) twice (once for each field it is used in) or is it optimized to perform the aggregation only once?
SELECT
  ID,
  SUM(MY_INDICATOR) AS MY_SUM,
  SUM(MY_INDICATOR) / COUNT(*) AS MY_RATE
FROM
  SOMETABLE
GROUP BY
  ID

UPDATE: After looking at some execution plans Thorsten is correct, the SQL Server optimizer will generate an execution plan that only requires SUM(MY_INDICATOR) to be executed once. No CTE is needed to optimize the query.

A: You are worried about an optimization that is rather irrelevant.  The expense of an aggregation query is in reading the data and rearranging it so common key values can be processed at the same time.  A simple sum() is not a performance issue.
That said, assuming that my_indicator is not NULL, you can simplify the logic to:
SELECT ID, SUM(MY_INDICATOR) AS MY_SUM,
       AVG(MY_INDICATOR * 1.0) AS MY_RATE
FROM SOMETABLE
GROUP BY ID;

The * 1.0 is because SQL Server does integer arithmetic -- to avoid that (even in your version) you want to convert to a number format with decimal places.
I often write this logic as:
avg(case when my_indicator = 1 then 1.0 else 0 end)

A: It would have to calculate it twice, you could do something like this so you only had to calculate it once:
SELECT ID, MY_SUM,
       MY_SUM / MY_COUNT AS MY_RATE
FROM ( SELECT ID,
              SUM(MY_INDICATOR) AS MY_SUM,
              COUNT(*) AS MY_COUNT
       FROM  SOMETABLE
       GROUP BY ID
     ) t;


text:
Q: How do I extract from a password protected zip file using VBA? I have been struggling with this problem for quite some time now, and have trawled through various forums trying to find an answer.
I have a mailbox which received 5 emails each morning which have zipped, password-protected .csv files which require opening and processing in Excel. I am semi-competent in VBA so the Excel side of things is no issue, but it would save me a lot of time if I could automatically unzip these files and save them to a folder.
These emails have the same subjects, attachments and passwords each day, and are from the same sender to the same mailbox. I have code which can automatically process and save the .zip files to a location, but I am still stuck with the problem of having to go into each one, enter the password, open the file, save it, etc.
I have refrained from attaching this code because I would like to see if there are better solutions to my one, and it is the unzipping and password entering that I really need help with. This being said if you would like me to attach my code I will be happy to do so :)

A: To expand my comment, no input is required - the password is obtained via an event so can be provided in code.
Download the demo project and DLL
In the outlook VBA editor, right click the Project in the tree, Import File and add
cUnzip.cls
mUnzip.bas

Put the DLL in \System32 (or \SysWoW64 on 64bit)
As a naive example, add a new class cWhatever:
Private WithEvents Unzip As cUnzip

Private Sub Class_Initialize()
    Set Unzip = New cUnzip
End Sub

Sub RunUnzip()
    With Unzip
        .ZipFile = "c:\blah\qqq.zip"
        .UnzipFolder = "c:\temp"
        .Unzip
    End With
End Sub

Private Sub Unzip_PasswordRequest(sPassword As String, bCancel As Boolean)
    sPassword = "password123"
End Sub

Then to run from elsewhere:
Dim x As New cWhatever
x.RunUnzip

First time you run there is an error highlighting App.EXEName, just delete the App.EXEName &


text:
Q: Symfony2 Forms - Acessing the data of the parent Form How to access the data of a parent form in the subform?
For example there are products and categories. Product and Categories are many to many. If I want to edit all Products of a Category. The editable Data of each Product depends on the Category.
Is it possible to achieve this by using Symfony Forms?
Right now I can't see any possibility as the Product has no information about the current Category (since the relation is many to many).

A: I believe there is not a way to access the parent form data in any "clean" way.
However, it IS possible.
You will have to pass it as an option to the subform from the mainform.
Example:
Main form, how you will include subform:
$builder->add('sub',   new SubType(),   array('parent_data' => $builder->getData());

If your subtype is collection, it is a little bit different:
$builder->add('subs',   'collection',   array('type' => new SubType(),
                                          'options' => array('parent_data' => $builder->getData()))
    );

Add this to subform:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver
        ->setRequired(array('parent_data'));
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $parentData = $options['parent_data'];

    ... build subform

}

Please tell me if it works, I wrote it without testing, so we can fix any possible typos.


text:
Q: What is the meaning behind FreeBSD bootloader ASCII art daemon letters? FreeBSD bootloader includes an ASCII art daemon. Is there any meaning behind the letters "s, y, o", or is just a random choice?

A: It's just basic ASCII art, much like if I wanted an arrow I could use for instance >---->.  They use the character that most resembles the shape they want for the picture they are "drawing" with character cells.

A:
The choice of letters is based on how the boot loader font renders each character

Shout out to Devin Teske for clarification!
Here's the thread.


text:
Q: PL SQL stored procedure to copy rows in the same table with modified data I am new to PL-SQL dialect. At work, I am using an old Oracle 10g DBMS, I need to select some rows from a table here called "myWorkTable", to modify some fields for each selected row and finally to insert the new rows in the same table.
In the past I did something similar with T-SQL but PL-SQL doesn't allow DDL (like CREATE and DROP) inside a block or procedure so it doesn't work. To give you an idea of what I would like to accomplish, below is my not working code in PL SQL:
DECLARE

  old VARCHAR2( 31 ) := 'oldString';
  new VARCHAR2( 31 ) := 'newString';

BEGIN

    CREATE TABLE myDB.tmp1 AS SELECT * FROM myDB.myWorkTable where myField = old;
    UPDATE myDB.tmp1 SET myField = new;
    INSERT INTO myDB.myWorkTable SELECT * FROM myDB.tmp1;
    DROP TABLE myDB.tmp1;

END;

Is there a way to accomplish the same result not using DDL inside the PL-SQL a block or a stored procedure? Thanks for your hints & tips!

A: You could just list all the columns:
INSERT INTO myDB.myWorkTable
    SELECT col1, col2, col3, 'new' as myField, . . ..
    FROM myDB.tmp1;

Then you don't have to fiddle with temporary tables.


text:
Q: Testing node js router with with chai and supertest fails I am trying to test a post request that takes in information and saves to mysql database.
Here is the router.
router.post('/dbInsert',(req,res,next)=>{
   user = req.body;
   saveUser(user).then((result)=>{
       res.send('All info saved');
    }).catch((e)=>{
       res.send('All info not saved');
   });
});

The router works since I tried to post data into it.
So now when I am trying to run the test, it says error. Here is the test.
describe('POST /dbInsert',()=>{
    it('should create a new user',(done)=>{
        var fake = {
            Owner : "3",
            firstname : "bla",
            lastname : "wassup",
            email:"unvalid@email.com",
            password : "akhjashjkdadh",
            token : "121212121"
        }
        request(app)
            .post('/dbInsert')
            .send(fake)
            .expect(200)
            .expect((res)=>{
                expect(res.body).to.include(fake);
            })

            .end((err,res)=>{
                if(err)
                    return done(err);
            });
    });
});

Here is the error.
1 failing

  1) POST /dbInsert should create a new user:
     AssertionError: expected {} to have property 'Owner'

/* Not related to the above question but just curious */
I am new to this and also wanted to ask, how can the database be cloned, as in not test on my own database but have a fake database that tests this and then gets itself deleted. I looked at spy, but din't know if thats the way to do it.

A: Supertest test is not behaving like you think. This does not unit test what you sent to your server. This tests the response from your server, so it's not going to be the object that you sent.
.expect((res)=>{
    expect(res.body).to.include(fake);
})

If you call res.send(body) in your route, you should be able to validate it like this:
.end((err, res) => {
    if (err) return done(err);
    expect(res.body).to.have.property("Owner").that.equal("3");
    return done();
})

Another issue I see is that you're not handling errors properly. In your case, you're sending a 200 in the event of an error, meaning that you don't know when it fails and that's probably why the updated validation doesn't seem to work properly.
.catch((e)=>{
       // Only difference is the message.
       res.send('All info not saved');
   });
Try this:
.catch((e)=>{
       // Now, it will be a 500 to note the failure
       res.status(500).send(e.message);
   });
This is going to timeout when successful because you're only going to call done when it there's an error. Just remove the if statement.
.end((err,res)=>{
    if(err)
        return done(err);
});

This should work:
.end(done);

The whole shibang:
router.post('/dbInsert',(req,res,next)=>{
   user = req.body;
   saveUser(user).then((result)=>{
       res.send(user);
       next();
    }).catch((e)=>{
       res.status(500).send(e.message);
       next();
   });
});

describe('POST /dbInsert',()=>{
    it('should create a new user',(done)=>{
        var fake = {
            Owner : "3",
            firstname : "bla",
            lastname : "wassup",
            email:"unvalid@email.com",
            password : "akhjashjkdadh",
            token : "121212121"
        }
        request(app)
            .post('/dbInsert')
            .send(fake)
            .expect(200)
            .end((err, res) => {
                if (err) return done(err);
                expect(res.body).to.have.property('Owner').that.equal(fake.Owner);
                done();
            });
    });
});

To test, I verified that this works:
const request = require('supertest');
const express = require('express');
const bodyParser = require('body-parser');
const expect = require('chai').expect;
const app = express();

app.use(bodyParser.json());

app.post('/user', function(req, res) {
  return res.send(req.body);
});

request(app)
  .post('/user')
  .send({
      foo: "bar"
  })
  .expect(200)
  .end(function(err, res) {
    if (err) throw err;
    expect(res.body.foo).to.equal("bar");
  });

If it's still not working, there must be something unseen going on. Try console.dir(res.body) if it doesn't work to look at the output.


text:
Q: Can I prevent TStringlist removing key value pair when value set to empty Can I prevent TStringList from removing key-value-pair when value is set to empty? I use Delphi XE8 and Lazarus which work differently. I want the pair to be left in the TStringlist object even when the value is set to an empty string. For example:
procedure TMyClass.Set(const Key, Value: String);
begin
  // FData is a TStringList object
  FData.Values[Key] := Value; // Removes pair when value is empty. Count decreases and Key is lost.
end;

Problem that I'm having is that when I compile with Delphi the pair with empty values is removed and I don't know afterwards was a value with a key never set or was it explicitly set to be an empty string. Also I can't get all the keys that have been used. Now I need to hold another collection of keys that holds information about empty ones.
MyKeyValues.Set('foo', 'bar'); // Delphi FData.Count = 1; Lazarus FData.Count = 1
MyKeyValues.Set('foo', '');    // Delphi FData.Count = 0; Lazarus FData.Count = 1

A: You can write a class helper to implement a new behaviour of the SetValue method of the TStrings class.
If you don't like a solution based on a class helper, you can use a custom class which inherits from TStringList and, again, override its Values property behaviour - the code is very similar to this helper-based implementation.
I'd prefer to use the second choice because the helper will define a new behaviour for all the TStringList objects.
type
  TStringsHelper = class helper for TStrings
    private
      function GetValue(const Name: string): string;
      procedure SetValue(const Name, Value: string); reintroduce;
    public
      property Values[const Name: string]: string read GetValue write SetValue;
  end;

function TStringsHelper.GetValue(const Name: string): string;
begin
  Result := Self.GetValue(Name);
end;

procedure TStringsHelper.SetValue(const Name, Value: string);
var
  I: Integer;
begin
  I := IndexOfName(Name);
  if I < 0 then I := Add('');
  Put(I, Name + NameValueSeparator + Value);
end;

A: What about this?
procedure TMyClass.Set(const Key, Value: String);
var
  i:integer;
begin
  i := FData.IndexOfName(Key);
  if i = -1 then
    FData.Add(Key + '=' + Value)
  else
    FData[i] := Key + '=' + Value;
end;

You can choose wether to set FData.Sorted:=true; or not.

A: TStringList doesn't have an option for that. Its behaviour is to delete an entry, when the value is empty ('').
You could implement that behaviour on you own by, for example, adding something like a prefix to your value:
procedure TMyClass.Set(const Key, Value: String);
begin
  FData.Values[Key] := '_' + Value;
end;

But that means, you also need a getter, to remove it again:
function TMyClass.Get(const Key): String;
begin
  Result := StringReplace(FData.Values[Key], '_', '', []);
end;


text:
Q: pandas.DataFrame.groupby loses index and messes up the data I have a pandas.DataFrame (named df) with the following data:
          labels               texts
0         labelA  Some Text 12345678
1         labelA  Some Text 12345678
2         labelA  Some Text 12345678
3         labelA  Some Text 12345678
4         labelB  Some Text 12345678
5         labelB  Some Text 12345678
6         labelB  Some Text 12345678
7         labelC  Some Text 12345678
8         labelC  Some Text 12345678
9         labelC  Some Text 12345678
10        labelC  Some Text 12345678
11        labelC  Some Text 12345678
12        labelC  Some Text 12345678

when I perform group by with the following (the goal is to take 2 samples from each label), the index is lost:
grouped = df.groupby('labels')
result = grouped.apply(lambda x: x.sample(n=2))
print(result)

The output becomes:
                    labels               texts
labels
labelA    0         labelA  Some Text 12345678
          0         labelA  Some Text 12345678
          0         labelB  Some Text 12345678
          0         labelB  Some Text 12345678
          0         labelC  Some Text 12345678
          0         labelC  Some Text 12345678

I would like the output becomes:
          labels               texts
0         labelA  Some Text 12345678
1         labelA  Some Text 12345678
2         labelB  Some Text 12345678
3         labelB  Some Text 12345678
4         labelC  Some Text 12345678
5         labelC  Some Text 12345678

How should I make the changes?
I tried to use result.dropout(0).reset_index() according to this answer, but it becomes:
     index         labels               texts
0        0         labelA  Some Text 12345678
1        0         labelA  Some Text 12345678
2        0         labelB  Some Text 12345678
3        0         labelB  Some Text 12345678
4        0         labelC  Some Text 12345678
5        0         labelC  Some Text 12345678

A: Add group_keys parameter to DataFrame.groupby:
grouped = df.groupby('labels', group_keys=False)
result = grouped.apply(lambda x: x.sample(n=2))
print(result)

   labels               texts
0  labelA  Some Text 12345678
1  labelA  Some Text 12345678
4  labelB  Some Text 12345678
6  labelB  Some Text 12345678
9  labelC  Some Text 12345678
8  labelC  Some Text 12345678

Another idea is remove all index and replace by original default RangeIndex:
grouped = df.groupby('labels')
result = grouped.apply(lambda x: x.sample(n=2)).reset_index(drop=True)
print(result)
   labels               texts
0  labelA  Some Text 12345678
1  labelA  Some Text 12345678
2  labelB  Some Text 12345678
3  labelB  Some Text 12345678
4  labelC  Some Text 12345678
5  labelC  Some Text 12345678


text:
Q: How can I prevent a TTY (e.g. /dev/tty1) from writing to the framebuffer (/dev/fb0)? I'm running a Raspbian Buster server with no Xserver.  I want to display wallpaper on a connected television but /dev/tty1 keeps over writing /dev/fb0 either with a blinking cursor or just refreshing randomly 60 seconds later after I make the cursor invisible (from getty@tty1.service).  My new strategy is to completely prevent /dev/tty1 from ever writing to the framebuffer.
Thanks for any help.

A: To stop /dev/tty1 from overwriting the buffer I'm using
systemctl stop getty@tty1.service and then make the cursor invisible with..
/usr/bin/tput civis > /dev/tty1
This allows me access to console after reboot should I lose access via ssh.


text:
Q: LINQ to SQL Classes, How to change column format? (DataGrid) How do you change the format of the data in a column of a LINQ to SQL classes in a DataGrid control?
I have a SQL server table column with DateTime data and it shows as you would expect, 10/19/2015 8:30:00 AM
How do you change the format to just show the date 10/19/2015
I could not see anything in the properties panel that would do this. Will this be handled in XMAL?
The code I have so far.
public partial class MainWindow : Window
    {
        HomeLINQSqlDataContext dc = new HomeLINQSqlDataContext(Properties.Settings.Default.Staff_ManagerConnectionString2);
        //TimeRecorderLINQSqlDataContext dc = new TimeRecorderLINQSqlDataContext(Properties.Settings.Default.Staff_ManagerConnectionString1);
        public MainWindow()
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

            PopulateCollection();
            if (dc.DatabaseExists()) TimeRcorderDataGrid.ItemsSource = dc.Staff_Time_TBLs;
            //if (dc.DatabaseExists()) TimeRcorderDataGrid.ItemsSource = dc.Staff_Data_TBLs;
            InitializeComponent();

        }
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            dc.SubmitChanges();
        }
        private void PopulateCollection()
        {
            ObservableCollection<FooClass> fooColl = new ObservableCollection<FooClass>();
            for (int i = 0; i <= 10; i++)
            {
                fooColl.Add(new FooClass() { Description = i.ToString(), SomeDate = DateTime.Now });
            }
            TimeRcorderDataGrid.ItemsSource = fooColl;
        }
    }
    public class FooClass
    {
        public string Description { get; set; }
        public DateTime SomeDate { get; set; }

    }

}

XAML,
 <TabControl>
        <TabItem Header="   社員データ   " FontSize="20">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="16*"/>
                    <ColumnDefinition Width="113*"/>
                    <ColumnDefinition Width="1057*"/>
                </Grid.ColumnDefinitions>
                <DataGrid>
                    <DataGrid.Columns>
                        <DataGridTextColumn Binding="{Binding StartDate, StringFormat=\{0:dd.MM.yy \}}" />
                    </DataGrid.Columns>
                </DataGrid>
                <DataGrid Name="TimeRcorderDataGrid" Margin="0,0,0,79" Grid.ColumnSpan="3">
                    <DataGrid.Columns>
                        <DataGridTextColumn Width="Auto" />
                    </DataGrid.Columns>
                </DataGrid>
                <Button x:Name="SaveButton" Content="Save" Click="SaveButton_Click" Grid.Column="1" HorizontalAlignment="Left" Margin="10,583,0,0" VerticalAlignment="Top" Width="391" Grid.ColumnSpan="2" Height="57"/>
            </Grid>
        </TabItem>
        <TabItem Header="   入力ページ   " FontSize="20">
            <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}" Margin="10" Name="dataGrid1">
                <DataGrid.Columns>
                    <DataGridComboBoxColumn Header="Combo" Width="300"
                     SelectedItemBinding="{Binding Values}"
                     />
                </DataGrid.Columns>
            </DataGrid>
        </TabItem>

    </TabControl>

Thanks

A: If you are defining the columns explicitly (rather than relying on autoGenerateColumns) you should be able to state the format of your dates;
<DataGrid  AutoGenerateColumns="False" ... >
    <DataGrid.Columns>
        <DataGridTextColumn Header="Raised" Binding="{Binding INSERT_PROPERTY_HERE, StringFormat=\{0:dd/MM/yy\}}"/>
    </DataGrid.Columns>
 </DataGrid>

A: You can format DateTime using StringFormat in the binding. Let me show an example:
XAML:
<DataGrid Name="dataGrid" VerticalGridLinesBrush="Yellow"
   HorizontalGridLinesBrush="Yellow" AutoGenerateColumns="False">
   <DataGrid.Columns>
       <DataGridTextColumn Binding="{Binding Description}" />
       <DataGridTextColumn Binding="{Binding SomeDate, StringFormat=\{0:dd.MM.yy \}}" />
   </DataGrid.Columns>
</DataGrid>

Model:
public class FooClass
{

    public string Description { get; set; }
    public DateTime SomeDate { get; set; }
}

code-behind:
public MainWindow()
{
   Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
   InitializeComponent();
   PopulateCollection();
}

private void PopulateCollection()
{
    ObservableCollection<FooClass> fooColl = new ObservableCollection<FooClass>();
    for (int i = 0; i <= 10; i++)
    {
        fooColl.Add(new FooClass() { Description=i.ToString(), SomeDate=DateTime.Now});
    }
    dataGrid.ItemsSource = fooColl;
}

Update:
There 12 columns in the DataGrid that is imported from SQL server, only two of those columns are DateTime , No. 7 and No. 8 column. How do you specify the format to those columns?
You should explicitly declare columns of your DataGrid and write StringFormat for columns No. 7 and No. 8. For example:
<DataGrid Name="TimeRcorderDataGrid" Margin="0,0,0,79" Grid.ColumnSpan="3">
  <DataGrid.Columns>
     <DataGridTextColumn Binding="{Binding ColumnOne}" Width="Auto" />
     <DataGridTextColumn Binding="{Binding ColumnTwo}" Width="Auto" />
     <DataGridTextColumn Binding="{Binding ColumnThree}" Width="Auto" />
     <DataGridTextColumn Binding="{Binding ColumnFour}" Width="Auto" />
     <DataGridTextColumn Binding="{Binding ColumnFive}" Width="Auto" />
     <DataGridTextColumn Binding="{Binding ColumnSix}" Width="Auto" />
     <DataGridTextColumn Binding="{Binding ColumnSeven, StringFormat=\{0:dd.MM.yy \}}"}" Width="Auto" />
     <DataGridTextColumn Binding="{Binding ColumnEight, StringFormat=\{0:dd.MM.yy \}}"}" Width="Auto" />
     <DataGridTextColumn Binding="{Binding ColumnNine}" Width="Auto" />
     <DataGridTextColumn Binding="{Binding ColumnTen" Width="Auto" />
     <DataGridTextColumn Binding="{Binding ColumnEleven}" Width="Auto" />
     <DataGridTextColumn Binding="{Binding ColumnTwelve}" Width="Auto" />
  </DataGrid.Columns>
</DataGrid>


text:
Q: Unknown column 'G.Id' in 'on clause' I am getting SQL Error (1054): Unknown column 'G.Id' in 'on clause'.
What is wrong and how can be solved?
SELECT E.Id, E.Nome, A.login AS Username, E.Departamento, E.Funcao, E.Telefone, E.Fax, E.Email, A.previlegio AS Perfil, G.Nome
FROM Grupos G, Equipa E
INNER JOIN Acesso AS A
ON A.id = E.IdAcesso
INNER JOIN Grupos_has_Equipa AS H
ON H.Grupos_Id = G.Id
WHERE E.Id = '1977'
AND H.Grupo_Principal = "sim"

A: You cannot mix implicit and explicit joins in a single query.
So the solution is to rewrite
FROM Grupos G, Equipa E

part to
FROM Grupos G INNER JOIN Equipa E

PS: I also don't see a join condition that ties E and G tables. I bet you're getting a cartesian product as a result.


text:
Q: Why the Hive index can not improve the speed of my queries I have an external Hive table, which has the structure which is essentially like:
CREATE EXTERNAL TABLE foo (time double, name string, value double)
ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
LOCATION 'hfds://node/foodir

And I create an index for (name, value).
CREATE INDEX idx ON TABLE foo(name, value)
AS 'org.apache.hadoop.hive.ql.index.compact.CompactIndexHandler'
WITH DEFERRED REBUILD;
ALTER INDEX ts_idx ON trionsort REBUILD;

The query I have is:
SELETE minute, count(minute) AS mincount
FROM (SELECT round(time/60) AS minute FROM foo WHERE name = 'Foo'
and value > 100000) t2 GROUP BY minute ORDER BY mincount DESC LIMIT 1;

However, although the rows that satisfy the conditions (name = 'Foo' and value > 100000) might only contribut less than 0.1% of all rows. This Hive query still runs against the whole dataset and the speed is comparable to running on a table without index.
Is there anything wrong with the index scheme or the query?
The output of running EXPLAIN SELECT...
[rn14n21] out: OK
[rn14n21] out: ABSTRACT SYNTAX TREE:
[rn14n21] out:   (TOK_QUERY (TOK_FROM (TOK_SUBQUERY (TOK_QUERY (TOK_FROM (TOK_TABREF (TOK_TABNAME log))) (TOK_INSERT (TOK_DESTINATION (TOK_DIR TOK_TMP_FILE)) (TOK_SELECT (TOK_SELEXPR (TOK_FUNCTION round (/ (TOK_TABLE_OR_COL time) 60)) hour)) (TOK_WHERE (> (TOK_TABLE_OR_COL value) 1000000)))) t2)) (TOK_INSERT (TOK_DESTINATION (TOK_DIR TOK_TMP_FILE)) (TOK_SELECT (TOK_SELEXPR (TOK_TABLE_OR_COL hour)) (TOK_SELEXPR (TOK_FUNCTION count (TOK_TABLE_OR_COL hour)) hrcount)) (TOK_GROUPBY (TOK_TABLE_OR_COL hour)) (TOK_ORDERBY (TOK_TABSORTCOLNAMEDESC (TOK_TABLE_OR_COL hrcount))) (TOK_LIMIT 3)))
[rn14n21] out:
[rn14n21] out: STAGE DEPENDENCIES:
[rn14n21] out:   Stage-1 is a root stage
[rn14n21] out:   Stage-2 depends on stages: Stage-1
[rn14n21] out:   Stage-0 is a root stage
[rn14n21] out:
[rn14n21] out: STAGE PLANS:
[rn14n21] out:   Stage: Stage-1
[rn14n21] out:     Map Reduce
[rn14n21] out:       Alias -> Map Operator Tree:
[rn14n21] out:         t2:log
[rn14n21] out:           TableScan
[rn14n21] out:             alias: log
[rn14n21] out:             Filter Operator
[rn14n21] out:               predicate:
[rn14n21] out:                   expr: (value > 1000000.0)
[rn14n21] out:                   type: boolean
[rn14n21] out:               Select Operator
[rn14n21] out:                 expressions:
[rn14n21] out:                       expr: round((time / 60))
[rn14n21] out:                       type: double
[rn14n21] out:                 outputColumnNames: _col0
[rn14n21] out:                 Group By Operator
[rn14n21] out:                   aggregations:
[rn14n21] out:                         expr: count(_col0)
[rn14n21] out:                   bucketGroup: false
[rn14n21] out:                   keys:
[rn14n21] out:                         expr: _col0
[rn14n21] out:                         type: double
[rn14n21] out:                   mode: hash
[rn14n21] out:                   outputColumnNames: _col0, _col1
[rn14n21] out:                   Reduce Output Operator
[rn14n21] out:                     key expressions:
[rn14n21] out:                           expr: _col0
[rn14n21] out:                           type: double
[rn14n21] out:                     sort order: +
[rn14n21] out:                     Map-reduce partition columns:
[rn14n21] out:                           expr: _col0
[rn14n21] out:                           type: double
[rn14n21] out:                     tag: -1
[rn14n21] out:                     value expressions:
[rn14n21] out:                           expr: _col1
[rn14n21] out:                           type: bigint
[rn14n21] out:       Reduce Operator Tree:
[rn14n21] out:         Group By Operator
[rn14n21] out:           aggregations:
[rn14n21] out:                 expr: count(VALUE._col0)
[rn14n21] out:           bucketGroup: false
[rn14n21] out:           keys:
[rn14n21] out:                 expr: KEY._col0
[rn14n21] out:                 type: double
[rn14n21] out:           mode: mergepartial
[rn14n21] out:           outputColumnNames: _col0, _col1
[rn14n21] out:           Select Operator
[rn14n21] out:             expressions:
[rn14n21] out:                   expr: _col0
[rn14n21] out:                   type: double
[rn14n21] out:                   expr: _col1
[rn14n21] out:                   type: bigint
[rn14n21] out:             outputColumnNames: _col0, _col1
[rn14n21] out:             File Output Operator
[rn14n21] out:               compressed: false
[rn14n21] out:               GlobalTableId: 0
[rn14n21] out:               table:
[rn14n21] out:                   input format: org.apache.hadoop.mapred.SequenceFileInputFormat
[rn14n21] out:                   output format: org.apache.hadoop.hive.ql.io.HiveSequenceFileOutputFormat
[rn14n21] out:
[rn14n21] out:   Stage: Stage-2
[rn14n21] out:     Map Reduce
[rn14n21] out:       Alias -> Map Operator Tree:
[rn14n21] out:         hdfs://rn14n21/tmp/hive-lei/hive_2013-09-12_21-19-33_247_861290513429832428/-mr-10002
[rn14n21] out:             Reduce Output Operator
[rn14n21] out:               key expressions:
[rn14n21] out:                     expr: _col1
[rn14n21] out:                     type: bigint
[rn14n21] out:               sort order: -
[rn14n21] out:               tag: -1
[rn14n21] out:               value expressions:
[rn14n21] out:                     expr: _col0
[rn14n21] out:                     type: double
[rn14n21] out:                     expr: _col1
[rn14n21] out:                     type: bigint
[rn14n21] out:       Reduce Operator Tree:
[rn14n21] out:         Extract
[rn14n21] out:           Limit
[rn14n21] out:             File Output Operator
[rn14n21] out:               compressed: false
[rn14n21] out:               GlobalTableId: 0
[rn14n21] out:               table:
[rn14n21] out:                   input format: org.apache.hadoop.mapred.TextInputFormat
[rn14n21] out:                   output format: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
[rn14n21] out:
[rn14n21] out:   Stage: Stage-0
[rn14n21] out:     Fetch Operator
[rn14n21] out:       limit: 3
[rn14n21] out:
[rn14n21] out:
[rn14n21] out: Time taken: 11.284 seconds, Fetched: 99 row(s)


text:
Q: Chef Apache2 recipe failing during server build I've been rebuilding our Chef master server to run in a T2 instance, which means moving it into a VPC. The old master is running 11.10.4 and the new one I've been tinkering with is running 11.16.4. I've gotten close to having it build a proper server within the VPC but it gets hung up setting up Apache.

ohai[reload_users] action reload[2014-11-25T08:13:58-06:00] ERROR: Encountered error while running plugins: #<Ohai::Exceptions::AttributeNotFound : No such attribute: 'passwd'

Specifically it doesn't seem to like this code in the recipe
if node[:etc][:passwd][:apache] == nil
    ohai "reload_users" do
        plugin "passwd"
        action :reload
    end
end

I've looked around and found this article on ohai

In Ohai 6 passwd plugin (named passwd.rb) sets the 'current_user' attribute and in order to use this
  data one needs to know this fact.
  require_plugin("passwd")
With Ohai 7, user interaction is now based on the attribute names. Only specify the names of the attributes for which you would like to collect data. Ohai 7 figures out which plugins are required and then collects the data.
In Ohai 7 one doesn't need to know the underlying details to find out current_user
  depends 'currentuser'

Looks close... but it fails if I replace plugin "passwd" with depends 'currentuser' it also fails.
I think I'm using Ohai 7 (gem list shows ohai (7.4.0)). I'm not a ruby guy so it's a bit fuzzy there. What exactly is this code supposed to be doing? This is custom added to the repo from the old Opscode cookbooks. Our cookbook was written largely by someone else who no longer works for our company and doesn't know the answer to this either. If I comment it out it works just fine and installs Apache but I would be remiss to just delete some code without understanding it.

A: With OHAI 7, you don't need (and can't) reload plugins on the basis of the filename where the specific function is provided. Instead, you reload it based on the specific attribute you want to reload.
Thus, while the attributes in node['etc']['passwd'] still are provided by a plugin named passwd.rb, you can't reload it that way. Instead, you want to reload the data in node['etc'], regardless from which files it is filled.
You can reload the password data by using this code in your recipe:
ohai "reload_users" do
  plugin "etc"
  action :reload
end

This is taken from the documentation at https://docs.getchef.com/ohai.html#id3.


text:
Q: Specify specific value in the plot How I can specify only check from data column in the plot.
Data
data           x-axis y-axis      result
abc                2    1         negative
abc                3    1         negative
check              1    1         positive
abc                4    1         positive

Code
 ax1=sns.scatterplot(data=df, x="x-axis", y="y-axis", hue="result",markers= 'x',s=950,label=None,  )
    #ax1.set(xlabel=None, ylabel=None, xticklabels=[], yticklabels=[])
    ax1.set_yticks((0, 1, 2, 3, 4, 5, 6, 7, 8), minor=0)
    ax1.set_xticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], minor=False)
    #plt.legend(bboxche_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    plt.setp(ax1.get_legend().get_texts(), fontsize='14') # for legend text
    ax1.plot()

Plot

A: df['data']=='check'] use this to specify the data during  plotting


text:
Q: Automatic partition mounting fails after improper shutdown of Mac OS X Since I frequently use both Linux and Mac OS X, I am using a shared HFS+ partition as /home in Linux and /Users in OS X. From day one, OS X was smart enough to automatically mount this partition on boot and, after some minor tweaks, my shared home directory works great.
When my computer is not shutdown properly (e.g. manually restarted after a kernel panic), OS X no longer automatically mounts the partition. This causes the operating system to regenerate a number of settings (e.g. default browser, Finder sidebar) that are not restored after manually mounting my home directory and re-logging.
How can I force OS X to always mount my home partition, even if it is after a failed shutdown?


text:
Q: Não consigo clonar um projeto pelo Git e Visual Studio 2017 Quando eu tento clonar um projeto por dentro do Visual Studio 2017(Enterprise e Community - tentei os dois), tenho esse erro:

Git process failed unexpectedly. CloneCommand.ExecuteClone

Acho que pode ser minha máquina, mas não sei responder ao certo.

A: Este erro parece ser um bug de uma versão do Visual Studio.
Tente as seguintes opções:

*

*Atualizar seu Visual Studio.

*Desinstalar sua versão do Git, remover o Visual Studio via Visual Studio Seteup, instalar a versão mais recente do Git e reinstalar o Visual Studio.

*Como sugerido pelo Jefferson, fazer o clone do repositório por linha de comando ou usando outra ferramenta.

Se nada disto funcionar, recomendo ler a seguinte thread, pois a causa deste problema parece ser bem variada e as soluções bem diferentes. Todas aparentemente relacionadas a problemas de configuração do próprio Visual Studio.


text:
Q: What is the building photographed in this stock wallpaper? I'm sure I've seen a picture of the full building somewhere. The image is a blue-tinted display of the building's facade - facing into a blue sky. It's a part of the stock wallpapers in Ubuntu 10.10 (Maverick).
Can someone help me identify this building? I can't be the first - or the only - person to be interested in knowing.

A: It is the Walt Disney Concert hall in Los Angeles, designed by Frank Gehry.
From the photographer's site: http://edltphoto.com/2010/09/ubuntu-blue/

My photo of a portion of the Walt
  Disney Concert hall in Downtown Los
  Angeles.

A full sized picture of the concert hall is included below, a description is found here


text:
Q: Trim a specific field and replace in Unix Shell Script I have a file with below data:
5773|2015-11-19|2016418|O|2015-11-06|C|AB1CD|826|826|CDE|2015-11-19|22222222222222222222222222222|ABCD|AB|30
5773|2015-11-19|2016418|O|2015-11-06|C|AB1CD|826|826|CDE|2015-11-19|88888888888888888888888888888|ABCD|AB|30
5773|2015-11-19|2016418|O|2015-11-06|C|AB1CD|826|826|CDE|2015-11-19|22222222222222222222222222222|ABCD|AB|30
5773|2015-11-19|2016418|O|2015-11-06|C|AB1CD|826|826|CDE|2015-11-19|55555555555555555555555555555|ABCD|AB|30

The data is separated with control-A character but I have replaced here with | as I was unable to post data with control-A.
I want to trim 22222222222222222222222222222 value and want first 5 value so our final output data should be like this:
5773|2015-11-19|2016418|O|2015-11-06|C|AB1CD|826|826|CDE|2015-11-19|22222|ABCD|AB|30
5773|2015-11-19|2016418|O|2015-11-06|C|AB1CD|826|826|CDE|2015-11-19|88888|ABCD|AB|30
5773|2015-11-19|2016418|O|2015-11-06|C|AB1CD|826|826|CDE|2015-11-19|22222|ABCD|AB|30
5773|2015-11-19|2016418|O|2015-11-06|C|AB1CD|826|826|CDE|2015-11-19|55555|ABCD|AB|30

Looking some help in this.

A: You could do it with awk like so:
awk -F\| 'BEGIN {OFS="|"};{$12=substr($12,1,5)};1'

-F sets the field separator to |, then before starting to process text we use the BEGIN block to set the output field separator (OFS) to | as well.  Then we replace the value in the 12th field with the first 5 characters of that field for each record.
You can give the filename to process as another argument on the command line, which is what you probably want, or use this in a pipeline if you have a process that is generating the file you want to update.
Thanks to Stéphane Chazelas for fixing some issues I had and making it more POSIX-y.  In particular, for fixing my start index from 0 to 1.  GNU's documentation includes the following line that let me get away with the bug:

If start is less than one, substr() treats it as if it was one.

but 1 is the index of the first character, and so it should be used, especially for people not using gawk. For instance with mawk:
$ mawk 'BEGIN{print substr("1234567", 0, 5)}'
1234
$ mawk 'BEGIN{print substr("1234567", 1, 5)}'
12345

A: With awk:
awk 'BEGIN{FS=OFS="\1"}; {$12=substr($12,1,5)}; 1' file

*

*BEGIN{...}: runs before processing starts

*FS=OFS="\1": sets the input and output field separator to ^A. According to Wiktionary ^A is the "first character of a message header", whose Octal-value is 1.

*{$12=substr($12,1,5)}: trims the 12th field.

*1: prints (default action) the record.

A: sed 's/\([^|]\{0,5\}\)[^|]*/\1/12' <in >out

...or w/ a GNU or BSD sed:
sed -E 's/([^|]{0,5})[^|]*/\1/12' <in >out

5773|2015-11-19|2016418|O|2015-11-06|C|AB1CD|826|826|CDE|2015-11-19|22222|ABCD|AB|30
5773|2015-11-19|2016418|O|2015-11-06|C|AB1CD|826|826|CDE|2015-11-19|88888|ABCD|AB|30
5773|2015-11-19|2016418|O|2015-11-06|C|AB1CD|826|826|CDE|2015-11-19|22222|ABCD|AB|30
5773|2015-11-19|2016418|O|2015-11-06|C|AB1CD|826|826|CDE|2015-11-19|55555|ABCD|AB|30

It's pretty simple: of the 12th possible occurrence on an input line of a sequence of any number of not-pipe characters, retain only a maximum of 5.


text:
Q: How does legal@ work? Some users have already complained on Meta.SE that they didn't receive answers on legal issues. I also sent two messages to legal (at) stackoverflow (dot) com from different emails last month, but didn't receive any response. Even something like "please wait" or "your message is incorrect" was not received by me.
How does legal (at) stackoverflow (dot) com work? What is the average response time? Are incorrect/incomplete messages silently ignored? If yes, why isn't any automatic reply sent, something like "your message is incorrect"?
In general, how can I protect my rights if this email is not working? Is the start of a real lawsuit against Stack Exchange Inc. the only way?

A: I heard back from the legal team:

The legal@ email address is definitely monitored. Privacy/data related requests are routed appropriately and handled. That said, we are not currently resourced to send confirmation messages for all emails that are sent. We try our best to respond to questions that do not ask for legal advice. Stack cannot provide legal advice as that is against licensing laws, so those submissions do not receive a reply.
However, please understand that legal@ cannot respond to every message (a lot of pure obvious spam comes in and has to be manually filtered), but we do respond to all messages that ask questions we are permitted to answer. We also act on all messages that require action.
If you have reason to believe your data request was mistakenly or accidentally not handled, please email legal@ with information about your original request and details describing why you believe it may have been missed. Otherwise, please know that we are on it.


text:
Q: CTRL + C in Visual Studio terminal does nothing 50% of the time. Bug or feature? How do you kill a running terminal in VS Code? Half the time Ctrl+C does nothing and I have to close the application. Is this a bug or a feature?

A: Click the trash can to kill the process running in the terminal
by closing the terminal window
OR
Press Ctrl + Z to get your command prompt back, but the process will need to be killed in the system monitor on your computer.
This is neither a bug nor a feature of VS Code; VS Code is merely providing an interface for the computer's command line controls. The reason Ctrl + C doesn't always work has to do with the process on your computer not hearing your command, which is the process's fault, not the command line interface's.

A: What I needed to do, to get this working for me is adding the following keybinding in keybindings.json
{
  "key": "cmd+c",
  "command": "workbench.action.terminal.sendSequence",
  "args": {
    "text": "\u0003"
  },
  "when": "terminalFocus"
}

Got the info here

A: As of VSCode 1.42, pressing ctrl+c twice in a row consistently exits the running process in the terminal.
For reference, my system is Mac OS running Catalina.  This seems to be specific to the VS code terminal, as running the same process in the system terminal only requires one press.


text:
Q: numerical errors in R I need to compare numbers. But there are many numerical errors in some comparisons. I know they are errors because analytical results are known. Of course when analytical results are known numerical evaluations are not needed, but I want to know how to resolve these problems numerically. Examples are shown below...
> x <- seq(0,1,length=11)
> x[8]
[1] 0.7
> x[8]==0.7
[1] FALSE
>
> x <- round(seq(1,0,length=21),2)
> x[3]==0.9
[1] TRUE
> x[5]==0.8
[1] TRUE
> (x[3]+x[5])/2
[1] 0.85
> (x[3]+x[5])/2==0.85
[1] FALSE


text:
Q: Add or remove dropdown elements from the javascript or jquery I have dropdownlist whose value is filled using the value of the other drop down. The problem here is that i need to bind the value of the second when the value of the first changes. I need to do it from the javascript.
Only thing i need to do is remove and add the select options in the second dropdown as the first dropdown changes.
How can i do this?
Thanks in advance.

A: Not too sure exactly what you want with the limited information provided but here is a solution that I think you are looking for:
HTML:
<select id="primary">
    <option value="one">One</option>
    <option value="two">Two</option>
</select>
<select id="secondary"></select>

jQuery:
var opts = {
    'one':['a','b','c'],
    'two':['d','e','f']
};

$('#primary').change(function(){
    var select = [];
    $.each(opts[this.value], function(k, v){
        select.push('<option>'+ v +'</option>');
    });
    $('#secondary').html(select.join(''));
});

Demo: http://jsfiddle.net/28TQZ/

A: $("#dropdownlist1").change(function () {
    var selected = $("#dropdownlist1 option:selected");
    //clear
    $("#dropdownlist2").html("");
    $("#dropdownlist2").append($("<option/>").text(selected.text()).val(selected.val()));
})

A: *

*Create all the drop downs you need, but only add options to the first one. The next ones only have a "default" value.

*On selecting the first drop down, you use jQuery to get the values for the second drop down, based on the value selected in the first drop down:
$.post('ajax/aj_populate2nddropdown.php', $("#firstdropdown").val(), function(result) {
$('div.placedaround2nddropdown').html(result);
});

*The file ajax/aj_populate2nddropdown.php collects the values of the second drop down, and returns them, inserted as options into the dropdown.

A: One simple way to do it is to just have a main dropdown and a bunch of secondary dropdowns that start hidden.  when you choose something from the first, then you unhide the related second one

A: Try this If you are trying at client side
Replace your controls with asp.net server controls


text:
Q: Android: Redirect to a URL with my custom scheme doesn't work I guess there are some answers on SOF for such a topic, but still something doesn't work with me.
The thing that mattters is that I get a redirect within WebView from some site to a URL kind of "myapp://something". In before, this redirect is made by site's API where the app is already registered to get a URL callback with the scheme mentioned above. Redirect is logged, URL "myapp://something" is confirmed there, but, for example, redirect to http://some.host inside WebView can be led to external browser or (when WebViewClient.shouldOverrideUrlLoading is set to return false) to the same WebView, making it try to open the URL instead of making system send an intent.
In both cases mentioned above, a redirect to myapp://something leads to nowhere, although my intent filter for the activity I created for handling it is set up like that:
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT"/>
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="myapp" />
</intent-filter>

That's a kind of solution proposed in Android url override doesn't work on redirect
and in http://developer.appcelerator.com/question/120393/custom-url-scheme---iphone--android
Could someone tell me, is it a bug of WebView with no working redirects or my intent filter is not set up properly?

A: Okay, I finally got the answer. Someway that's impossible to redirect from WebView to a custom scheme URL. That's why an explicit Intent call should be made, with this custom-schemed URL string as additional data.
In code, this looks like that:

WebView.setWebViewClient(new WebViewClient() {

      public boolean shouldOverrideUrlLoading(WebView view, String url) {
      //called for any redirect to stay inside the WebView

          if (url.contains("myapp")) { //checking the URL for scheme required
                                       //and sending it within an explicit Intent
              Intent myapp_intent = new Intent(Intent.ACTION_VIEW);
              myapp_intent.setData(Uri.parse(url));
              myapp_intent.putExtra("fullurl", url);
              startActivity(myapp_intent);

              return true; //this might be unnecessary because another Activity
                           //start had already been called

          }
          view.loadUrl(url); //handling non-customschemed redirects inside the WebView
          return false; // then it is not handled by default action
 }

So maybe this is a bug or a feature of WebView, I don't know. But in this case an explicit Intent call is the only thing that works stable and perfectly well.


text:
Q: Chrome Extension to run javascript unit tests is there currently any chrome / browser extension to unit test javascript on a page?
just to be clear, i'm not looking to test the extension itself, rather a tool to run tests on the current page.

A: Use the built-in assert method of the console object in Chrome or most other browsers to run simple unit tests, such as the following:
console.assert(!isFinite(Math.PI),"Math.PI is finite",Math.PI)

References

*

*Chromium Command Line API Reference


text:
Q: How to sort hash entries by keys when formatting Perl source code? Looking at perltidy I don't see such an option. Is there any tool which does this?

A: I prefer to sort my keys "logically". Fields like 'name' and 'id' come first, sometimes something like 'long name' or 'description' after name.
If you need to do something like this, you could use a editor with a shell facility to

*

*pass the data into a perl program

*eval the selection

*use Data::Dumper and set $Data::Dumper::Sortkeys = 1;

*And then do Data::Dumper->Dump( [ $eval_hash ], [ '$VAR1' ] )

*Strip off the front part s/\A[^=]+=\s+//

*Replace the selection with the output


text:
Q: Prove f(x) = max_i x_i is convex I want to prove $f(x) = \max_i x_i$ is convex on $\mathbb{R}^n$, where $n$ is finite. Can you verify if my attempt at a proof is correct? Thanks in advance!
My attempt:
First off, we prove that $$f(ax) = a f(x) \forall x \in \mathbb{R}^n, a \geq 0$$
Suppose this weren't true, because $\max_i a x_i > a \max_i x_i$. Then there exists an $i$ such that $a x_i > a \max_i x_i$. But by definition, $x_i \leq \max_i x_i$ and we can just multiply both sides by $a \geq 0$ to get $a x_i \leq a \max_i x_i$, and of course $x_i \leq a x_i \leq a \max_i x_i$, a contradiction.
Conversely, suppose this weren't true because $\max_i a x_i < a \max_i x_i$. Then:

*

*there exists an $i$ such that $x_i > x_j \forall j \neq i$

*there exists a $j$ such that $a x_j > a x_k \forall k \neq j$, i.e. $x_j > x_k \forall k \neq j$

*$a x_i < a x_j$, i.e. $x_i < x_j$.

However 1. and 2. lead to $i = j$, so $x_i = x_j$, another contradiction. So $f(ax) = af(x)$.
Second, we want to prove that $$f(x + y) \leq f(x) + f(y) \forall x \in \mathbb{R}^n$$ To do this, we observe that $\forall i \in \{1, ..., n\}, x_i \leq f(x)$. So if $x_i \leq f(x), y_i \leq f(y)$, by adding inequalities we get $$x_i + y_i \leq f(x) + f(y)$$.
Now, the definition of a convex function $f: \mathbb{R}^n \rightarrow \mathbb{R}$ is $$f(tx + (1 - t)y) \leq tf(x) + (1-t) f(y) \forall t \in [0, 1], x, y \in \mathbb{R}^n$$
But $$\max_i (tx + (1 - t)y)_i \leq \max_i (tx)_i + \max_i ((1-t)y)_i = t \max_i x_i + (1 - t) \max_i y_i$$
So $f(x)$ is convex.

A: @copper.hat confirmed that this proof is correct. Thanks!


text:
Q: How to set NBSP shortcut in Linux How can I change the keyboard combination for a non-breaking space (NBSP) from shift+space to something else?
It took a while for me to figure this out: when coding, I run into issues related to using an NBSP accidentally, for example at … = "…. Python for example complains about invalid character in identifier here. That is because I leave Shift pressed while typing all the characters, which makes the spaces be NBSPs.
This happens only on my computer running Manjaro Gnome, in any application (Firefox, Evolution, gedit, Atom, LibreOffice, …). On my other computer running OSX the combination of Shift+Space does not change the regular space character.
According to the NBSP WP entry this is not even the default key combination to generate an NBSP, but I can not remember me changing this anywhere.
So this is why I am asking where this setting could be placed, or how I can change this in Manjaro Gnome 17.1 Hakoila?

A: In the "Keyboard" control panel, "Layout" tab, "Options..." button, there is an entry for "Using space key to input non-breaking space". Shift is the second level, there is a separate option to assign the third level, and fourth level is second+third level.

A: The setting Ignacio talks about is actually placed in Gnome Tweaks at Keyboard and Mouse -> Additional Layout Options > Using space key to input non-breaking space. I set it to 3rd level and hope I will never hit this by accident.


text:
Q: How to use Switch in SQL Server I want to use CASE in my stored procedure. I am getting some syntax error in my code:
select
   case @Temp
   when 1 then (@selectoneCount=@selectoneCount+1)
   when 2 then (@selectoneCount=@selectoneCount+1)
   end

When running, I'm getting:

incorrect syntax near '='.

at this line here:
@selectoneCount = @selectoneCount + 1

near the equal.
Actually I am getting return value from a another sp into @temp and then if @temp =1 then I want to increment the count of @SelectoneCount by 1 and so on.
Please let me know what is the correct syntax.

A: The CASE is just a "switch" to return a value - not to execute a whole code block.
You need to change your code to something like this:
SELECT
   @selectoneCount = CASE @Temp
                         WHEN 1 THEN @selectoneCount + 1
                         WHEN 2 THEN @selectoneCount + 1
                     END

If @temp is set to none of those values (1 or 2), then you'll get back a NULL

A: This is a select statement, so each branch of the case must return something. If you want to perform actions, just use an if.

A:     select
       @selectoneCount = case @Temp
       when 1 then (@selectoneCount+1)
       when 2 then (@selectoneCount+1)
       end

   select  @selectoneCount

A:
Actually i am getting return value from a another sp into @temp and then it @temp =1 then i want to inc the count of @SelectoneCount by 1 and so on. Please let me know what is the correct syntax.

What's wrong with:
IF @Temp = 1 --Or @Temp = 2 also?
BEGIN
    SET @SelectoneCount = @SelectoneCount + 1
END

(Although this does reek of being procedural code - not usually the best way to use SQL)


text:
Q: How to typeset a text like a beamer enumerate item, rectangle style I would like to format a text so that it looks like an enumerate item.
In the example below, you can see that I would like a list that consists of the items 1,2,n. I would like the "n" to be typeset like the 1 and the 2, i.e. with a blue background.
\documentclass{beamer}

\usetheme{Madrid}
\useinnertheme{rectangles}
\setbeamertemplate{blocks}[default]

\begin{document}
    \begin{frame}
        \begin{enumerate}
            \item Item one
            \item Item two
            \item[n] Item n
        \end{enumerate}
    \end{frame}
\end{document}

Thanks!

A: \documentclass{beamer}

\usetheme{Madrid}
\useinnertheme{rectangles}
\setbeamertemplate{blocks}[default]

\newcommand{\mysquare}[1]{
  \hbox{%
    \usebeamerfont*{item projected}%
    \usebeamercolor[bg]{item projected}%
    \vrule width2.25ex height1.85ex depth.4ex%
    \hskip-2.25ex%
    \hbox to2.25ex{%
      \hfil%
      \color{fg}#1%
      \hfil}%
  }%
}

\begin{document}
    \begin{frame}
        \begin{enumerate}
            \item Item one
            \item Item two
            \item[\mysquare{n}] Item n
        \end{enumerate}
    \end{frame}
\end{document}


text:
Q: How to Merge Multiple Database files in SQLite? I have multiple database files which exist in multiple locations with exactly similar structure. I understand the attach function can be used to connect multiple files to one database connection, however, this treats them as seperate databases. I want to do something like:
SELECT uid, name FROM ALL_DATABASES.Users;

Also,
SELECT uid, name FROM DB1.Users UNION SELECT uid, name FROM DB2.Users ;

is NOT a valid answer because I have an arbitrary number of database files that I need to merge. Lastly, the database files, must stay seperate. anyone know how to accomplish this?
EDIT: an answer gave me the idea: would it be possible to create a view which is a combination of all the different tables? Is it possible to query for all database files and which databases they 'mount' and then use that inside the view query to create the 'master table'?

A: Because SQLite imposes a limit on the number of databases that can be attached at one time, there is no way to do what you want in a single query.
If the number can be guaranteed to be within SQLite's limit (which violates the definition of "arbitrary"), there's nothing that prevents you from generating a query with the right set of UNIONs at the time you need to execute it.
To support truly arbitrary numbers of tables, your only real option is to create a table in an unrelated database and repeatedly INSERT rows from each candidate:
ATTACH DATABASE '/path/to/candidate/database' AS candidate;
INSERT INTO some_table (uid, name) SELECT uid, name FROM candidate.User;
DETACH DATABASE candidate;

A: Some cleverness in the schema would take care of this.
You will generally have 2 types of tables: reference tables, and dynamic tables.
Reference tables have the same content across all databases, for example country codes, department codes, etc.
Dynamic data is data that will be unique to each DB, for example time series, sales statistics,etc.
The reference data should be maintained in a master DB, and replicated to the dynamic databases after changes.
The dynamic tables should all have a column for DB_ID, which would be part of a compound primary key, for example your time series might use db_id,measurement_id,time_stamp. You could also use a hash on DB_ID to generate primary keys, use same pk generator for all tables in DB.  When merging these from different DBS , the data will be unique.
So you will have 3 types of databases:

*

*Reference master -> replicated to all others

*individual dynamic -> replicated to full dynamic

*full dynamic -> replicated from reference master and all individual dynamic.
Then, it is up to you how you will do this replication, pseudo-realtime or brute force, truncate and rebuild the full dynamic every day or as needed.


text:
Q: Почему необходимо указать doubleValue (без него не выполняется), ведь автораспарковка должна сработать? package main;

public class alfa <pablo extends Number> {

pablo[] nums;

alfa (pablo[] o) {

    nums=o;
}

   double average() {

        double sum = 0.0;
        for(int i=0; i<nums.length; i++){
        sum += nums[i].doubleValue();
        }
        return sum/nums.length;
   }

   public static void main (String[] args) {

       Integer inums[] = { 1, 2, 3, 4, 5 };
       alfa <Integer> alo = new alfa <Integer>(inums);

       double v = alo.average();

       System.out.println("Znacenie : " + v);
   }
}

A: Автоматически распаковаться в double может только java.lang.Double. А у вас какие-то pablo в массиве хранятся...

A: Автораспаковка работает только так
Integer iOb = 100; // автоматически упаковывает значение типа int
int i = iOb; // автораспаковка

И тоже самое для остальных типов.
Преобразовать между Integer и double нельзя
int     a = 1;
Integer b = 1;

double  c = (double) a;   // OK
Double  d = (Double) b;   // NOT ON.

Вы задаете требование для pablo быть Number. И вы можете считывать только через метод doubleValue, так как шаблонный класс alfa может быть объявлен с любым типом унаследованным от Number.


text:
Q: ¿Cómo obtener frecuencias de una lista de números mayores a cierto umbral? Tengo un archivo.dat que tiene datos de precipitacion (un dato por dia) durante 56 años, dispuestos de la siguiente manera:
dia mes año precipitacion

1 1 1956 50
2 1 1956 2
3 1 1956 0
4 1 1956 0
5 1 1956 100

Necesito armar un script en Python que me diga la cantidad de veces por año que se supero cierto umbral de precipitacion (por ejemplo que se supero el numero 50 correspondiente a la cuarta columna). Estoy tratando de ver como puedo armar una tabla de frecuencia de tal manera de que me queden los datos de la siguiente manera:
Año    Frecuencia
1958   6
1959   2
1960   5

y asi sucesivamente.

A: Esto debe solucionar tu pregunta
tolerancia = 50 # se contaran los mayores a este numero
resultado = { }

with open('archivo.dat') as archivo_leido:
    for line in archivo_leido:
        line_to_list = line.split();
        if len(line_to_list) == 4:
            if (not line_to_list[2] in resultado) and (int(line_to_list[3]) > tolerancia):
                resultado[line_to_list[2]] = 1
            elif int(line_to_list[3]) > tolerancia:
                resultado[line_to_list[2]] += 1
            else:
                pass

# Imprimir resultados
for n in resultado:
    print(n, resultado[n])

Prueba archivo.dat
1 1 1956 50

2 1 1956 2
3 1 1956 0
4 1 1956 0

5 1 1956 100
6 1 1956 85
7 1 1956 35
8 1 1957 45
9 1 1958 56
10 1 1959 120
11 1 1959 100
12 1 1959 30
13 1 1959 66

Resultado:
1956 2
1958 1
1959 3

A: Dependiendo de como administres los datos, la solución puede llegar a ser muy distinta.
1. Python basico
Si tuvieras una lista de listas o tuplas con esta información, una forma bastante simple sería usar una comprensión de listas para filtrar los valores que superen el umbral y la clase Counter para contar las ocurrencias:
lista = [
  (1, 1, 1956, 50),
  (2, 1, 1956, 2),
  (3, 1, 1956, 0),
  (4, 1, 1956, 0),
  (5, 1, 1956, 100)
]

from collections import Counter
umbral = 30
c = dict(Counter([elemento[2] for elemento in lista if elemento[3] > umbral]))
print(c)

> {1956: 2}

Esto te retornará un diccionario con los años y la cantidad de veces que se ha superado el umbral
2. Pandas
Si usas pandas para administrar tus datos (lo cual es sumamente recomendable) la solución podría ser:
import pandas as pd

lista = [
  (1, 1, 1956, 50),
  (2, 1, 1956, 2),
  (3, 1, 1956, 0),
  (4, 1, 1956, 0),
  (5, 1, 1956, 100)
]

umbral = 30

df = pd.DataFrame(lista, columns=['dia', 'mes', 'anio', 'precipitacion'])

# Filtramos las filas que superan el umbral
superiores = df.loc[df['precipitacion'] > umbral]

# agrupamos por año y contamos la cantidad de los mismos
print(superiores.groupby(['anio']).size())

anio
1956    2
dtype: int64


text:
Q: How to access contact information outside salesforce environment I want to access salesforce data like(contact information ) outside salesforce environment in javascript how i can access salesforce data. I have a javascript file on my computer now i want to retrive salesforce contact in my javascript and show on html page how i can accomplish this task i have urgent requirement to complete task.(any help appriciable)Thanks in advance.

A: Mohan,
there are few good javascript libraries that will help you to integrate with salesforce and access the data using REST APIs..
here's a good start for integrating force.com via javascript
https://developer.salesforce.com/page/JavaScript
you can use the Force.com JavaScript REST Toolkit


text:
Q: How to disable username validation in Grav? Grav version is 1.1.5
I removed every validation logic and validation pattern in source code, but it does not work, I still got error when I create a user.
The error message name is USERNAME_NOT_VALID, I search this in all source code and delete related code, but it still display on screen when I got error. I don't understand where the message from.
diff --git a/user/plugins/admin/pages/admin/register.md b/user/plugins/admin/pages/admin/register.md
index ff0b13b..fc0cf6e 100644
--- a/user/plugins/admin/pages/admin/register.md
+++ b/user/plugins/admin/pages/admin/register.md
@@ -9,7 +9,7 @@ form:
       validate:
         required: true
         message: PLUGIN_LOGIN.USERNAME_NOT_VALID
-        pattern: '^[a-z0-9_-]{3,16}$'
+        pattern: ''

     - name: email
       type: email
@@ -27,7 +27,7 @@ form:
       validate:
         required: true
         message: PLUGIN_ADMIN.PASSWORD_VALIDATION_MESSAGE
-        pattern: '(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}'
+        pattern: ''

     - name: password2
       type: password
@@ -36,7 +36,7 @@ form:
       validate:
         required: true
         message: PLUGIN_ADMIN.PASSWORD_VALIDATION_MESSAGE
-        pattern: '(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}'
+        pattern: ''

     - name: fullname
       type: text
diff --git a/user/plugins/login/pages/register.md b/user/plugins/login/pages/register.md
index c4088e2..0391367 100644
--- a/user/plugins/login/pages/register.md
+++ b/user/plugins/login/pages/register.md
@@ -12,7 +12,7 @@ form:
       validate:
         required: true
         message: PLUGIN_LOGIN.USERNAME_NOT_VALID
-        pattern: '^[a-z0-9_-]{3,16}$'
+        pattern: ''

     -
       name: email
@@ -31,7 +31,7 @@ form:
       validate:
         required: true
         message: PLUGIN_LOGIN.PASSWORD_VALIDATION_MESSAGE
-        pattern: '(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}'
+        pattern: ''

     -
       name: password2
@@ -41,7 +41,7 @@ form:
       validate:
         required: true
         message: PLUGIN_LOGIN.PASSWORD_VALIDATION_MESSAGE
-        pattern: '(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}'
+        pattern: ''

   buttons:
       -
diff --git a/user/plugins/login/pages/reset.md b/user/plugins/login/pages/reset.md
index e5f82e4..8300d2a 100644
--- a/user/plugins/login/pages/reset.md
+++ b/user/plugins/login/pages/reset.md
@@ -20,7 +20,7 @@ form:
           validate:
             required: true
             message: PLUGIN_LOGIN.PASSWORD_VALIDATION_MESSAGE
-            pattern: '(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}'
+            pattern: ''

         - name: token
           type: hidden

diff --git a/user/plugins/login/cli/ChangePasswordCommand.php b/user/plugins/login/cli/ChangePasswordCommand.php
index d15abb7..5bde6cc 100644
--- a/user/plugins/login/cli/ChangePasswordCommand.php
+++ b/user/plugins/login/cli/ChangePasswordCommand.php
@@ -134,9 +134,6 @@ class ChangePasswordCommand extends ConsoleCommand
     {
         switch ($type) {
             case 'user':
-                if (!preg_match('/^[a-z0-9_-]{3,16}$/', $value)) {
-                    throw new \RuntimeException('Username should be between 3 and 16 characters, including lowercase letters, numbers, underscores, and hyphens. Uppercase letters, spaces, and special characters are not allowed');
-                }
                 if (!file_exists(self::getGrav()['locator']->findResource('account://' . $value . YAML_EXT))) {
                     throw new \RuntimeException('Username "' . $value . '" does not exist, please pick another username');
                 }
@@ -144,10 +141,6 @@ class ChangePasswordCommand extends ConsoleCommand
                 break;

             case 'password1':
-                if (!preg_match('/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/', $value)) {
-                    throw new \RuntimeException('Password must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters');
-                }
-
                 break;

             case 'password2':
diff --git a/user/plugins/login/cli/ChangeUserStateCommand.php b/user/plugins/login/cli/ChangeUserStateCommand.php
index 40f9dc6..90adee6 100644
--- a/user/plugins/login/cli/ChangeUserStateCommand.php
+++ b/user/plugins/login/cli/ChangeUserStateCommand.php
@@ -133,9 +133,6 @@ class ChangeUserStateCommand extends ConsoleCommand
     {
         switch ($type) {
             case 'user':
-                if (!preg_match('/^[a-z0-9_-]{3,16}$/', $value)) {
-                    throw new \RuntimeException('Username should be between 3 and 16 characters, including lowercase letters, numbers, underscores, and hyphens. Uppercase letters, spaces, and special characters are not allowed');
-                }
                 if (!file_exists(self::getGrav()['locator']->findResource('account://' . $value . YAML_EXT))) {
                     throw new \RuntimeException('Username "' . $value . '" does not exist, please pick another username');
                 }
diff --git a/user/plugins/login/cli/NewUserCommand.php b/user/plugins/login/cli/NewUserCommand.php
index 17dbf48..728adda 100644
--- a/user/plugins/login/cli/NewUserCommand.php
+++ b/user/plugins/login/cli/NewUserCommand.php
@@ -237,9 +237,6 @@ class NewUserCommand extends ConsoleCommand
     {
         switch ($type) {
             case 'user':
-                if (!preg_match('/^[a-z0-9_-]{3,16}$/', $value)) {
-                    throw new \RuntimeException('Username should be between 3 and 16 characters, including lowercase letters, numbers, underscores, and hyphens. Uppercase letters, spaces, and special characters are not allowed');
-                }
                 if (file_exists(Grav::instance()['locator']->findResource('account://' . $value . YAML_EXT))) {
                     throw new \RuntimeException('Username "' . $value . '" already exists, please pick another username');
                 }
@@ -247,10 +244,6 @@ class NewUserCommand extends ConsoleCommand
                 break;

             case 'password1':
-                if (!preg_match('/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/', $value)) {
-                    throw new \RuntimeException('Password must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters');
-                }
-
                 break;

             case 'password2':

A: There is already a way to change that is directly included in Grav without touching the source code.
If you go in admin panel, under Configuration, there is an item called "Advanced" where you can customize respectively "Username Regex" and "Password Regex"
By default, username regex is ^[a-z0-9_-]{3,16}$ and can be, as stated by @Scuzzy in a comment, changed to ^(.*)^ to accept every character.
BTW security and readability wise, I recommend you to not use that regex unless you want unsernames like ^=-èö on your website.
I recommend you to avoid touching Grav source code directly, because every changes can be reverted everytime you update Grav. If you really want to change something in the source, consider creating it as a plugin (even for personnal use) so you keep the ability to update.


text:
Q: Does the wind gust over the ocean? It is easy to observe that on a windy day, the wind does not blow for several hours at constant speed, then gradually subside.  Instead, on a time scale of seconds or tens of seconds, there are stronger gusts of wind followed by lulls.
Presumably this is an effect of turbulence.  If so, is this turbulence due to the complicated geometry around me - buildings, trees, hills, etc.?  If we removed these features and had wind blowing over a flat ocean surface or a flat plain for hundreds of miles, would we still observe the wind to blow in the same sorts of gusts, or should I expect a more steady flow?

A: I believe you're exactly right: it's the complexity of hills, buildings, trees, asphalt, water, etc that make surface winds complicated.  As you go higher in the atmosphere, these surface effects disappear and the winds become much more steady.  You can see this in the winds aloft forecasts issued by the FAA for use in aviation:

http://aviationweather.gov/adds/winds/

In the upper left there is a drop-down box allowing you to select altitudes from the surface (SFC) to 48,000 feet (FL480).  As you go up in altitude, the relatively chaotic surface winds blend into a much smoother (and faster!) flow.
I assume the effect is similar at sea, given the simpler boundary conditions.
(I admit this does not directly address your question of, "how variable are the winds at sea"? I too am curious to hear an authoritive answer.)

A: Strangely enough Nasa thinks that winds gust stronger over the oceans than over land.

Wind tends to blow stronger over the ocean than over land. The ocean presents a smooth surface over which wind can glide without interruption, while hills, mountains, and forests tend to slow or channel wind over land.

This map is interesting.
I have watched gusts sweeping over calm seas , where one can predict the arrival of wind from the observed disturbance in the distance.  So both land and ocean have changing winds, but which is stronger in producing gusts, as defined rigorously, is not obvious.

A: anecdotally from my sailing experience around a coast, and the conventional sailing knowledge:
A wind that has travelled over the sea to get there is more even that one that has come off off the land.
P.S. The statement above: "Wind tends to blow stronger over the ocean than over land"
 does not imply that it is more gusty

A: Even if the surface is perfectly smooth, you'll still get  boundary layer turbulence.
But yes, winds coming off the ocean do tend to be more laminar.

A: Do not you think that the various pieces of land and sea can warm up faster or slower and so the air over them does change temperature, and consequently, areas with different pressures are formed.
The water is warming up faster than land in the morning, and therefore there is higher pressure over water than over land, and wind is blowing from sea to the land - this is morning breeze.
Similarly, rocks and soil will warm up at different rates.
Maybe this local differences in air pressure trigger gusts.
And gusts are some kind of disturbances which can have an influence on wind speed.

A: I think wind Gust stronger over land due to funnelling through valleys ect. But the wind blows stronger on a constant basis at sea


text:
Q: Why does the + sign in the Html will never works? I am trying to create the rowspan and the colspan at the same time within the one tables. But, I think I will need to use my + sign and my scope html variables.
I believe the scope html variables is to force put down or to force put right hand side of your own tables.

<!DOCTYPE html>

                C1,R1,headings
                C2,R1,headings
                C3,R1,headings
                C4,R1,headings

                    stretching from C1,R2 into
                    the C2,R3

                    C3,R2,textAfterwards

                    C4,R2,textAfterwards

                    C3,R3,textAfterwards

                    C4,R3,textAfterwards

A: You can have rowspan and colspan at the same time like this:

The confusion is that you seem to think they will be only applied if you use a + sign, but that's mistaken.


text:
Q: Linq to SQL: Equivalent of Array.SequenceEqual Let's say I have this method:
public T GetByID(object[] pKeys)
{
    DbQuery<T> dbq = mContext.GetDbSet<T>();
    return dbq.SingleOrDefault(ent => ent.PrimaryKey.SequenceEqual(pKeys));
}

ent.PrimaryKey is an object[].
Of course, this doesn't work because of the SequenceEqual(). I could maybe use Contains but this would not preserve order: {1, 2} is NOT equal to {2, 1}.
I could also use AsEnumerable() first and then use some logics but that would load the whole table in memory, which is unacceptable.
Is there a way to achieve this?
Edit
I've made the method generic. Because that's what it really is and it makes more sens with the primary key being an array.
I also point out that the goal of the method here could be achieved with mContext.GetDbSet().Find(pKeys). This, however, complicates the use of dbq.Include(property) or mContext.Entry(wanted).Collection(property).Load() for parent.child properties which is another matter not related to the question.

A: Without reproducible code it is a little tough to test any particular solution, but the first thing that came to my mind (and compiled/tested in notepad) is
public T GetByID(object[] pKeys)
{
    DbQuery<T> dbq = mContext.GetDbSet<T>();

    for (var i = 0; i < pKeys.length; i++)
    {
        dbq = dbq.Where(ent => ent.PrimaryKey[i] == pKeys[i]);
    }

    return dbq.SingleOrDefault();
}


text:
Q: Is there any workaround to install a gmail add-on developed by other in a gmail.com account? At this moment, you can install your own add-ons and add-ons from other developer if your account and its account are of the same domain, but if the domain is not from an institution and they are standard gmail accounts.
In the other hand anyone with a gmail account can copy scripts and manifest from one add-on and create one to use, but it is not a good experience.
I know that Google plans to open the add-ons market but is there a workaround to do this now?
Thank you very much


text:
Q: VirtualPathProvider with ASP.Net MVC I have implemented VirtualPathProvider class so I can keep all my views in the database instead of FileSystem of web server.
It seems MVC requests aspx page correctly from Database, but unable to request related codebehind .cs files and throws error as unable to load the code-behind class file.
This virtualPathProvider works like charm with normal Web Form.
Are there any specific changes I will have to make to MVC framework or any other stuff?

A: ASP.NET MVC is a type of Web Application project. Thus all the code-behind is compiled into an assembly before deployment. It's not like a WebSite project when at the time of the request, the code-behind is compiled.
What that means is that your views have an "Inherits" declaration. The type that they inherit must exist somewhere. If your pages inherit from ViewPage, you're set. If they inherit from ViewPage of T, then you've got issues. The CLR syntax for defining a generic type is ugly. Check out this post for more info.
Here's an example of the syntax:
System.Web.Mvc.ViewPage`1[ [System.Int32,mscorlib] ]


text:
Q: Combine datetime and timezone columns in a Pandas DataFrame (tz_localize from column) As already answered (Converting time zone pandas dataframe), Pandas provides means to localize datetime columns (tz_localize) and convert time zones (tz_convert) to a predefined time zone. For example:
df["localized_time"] = df.time.tz_localize(pytz.utc).tz_convert("Some/Timezone")

However, both functions accept the time zone itself as an argument. What if the time zone comes from another column in the same data frame? For example:
   time                 timezone        ...
0  2022-04-11 12:24:43  "Europe/Paris"  ...
1  2022-04-11 04:22:12  "US/Eastern"    ...
...

Is there a simple way to combine the "time" column (already a datetime type) with the time zone taken the "timezone" column (string)?

A: Yes, it is possible, e.g. by:
df["localized_time"] = df.time.dt.tz_localize(pytz.utc)

df['new'] = df.apply(lambda x: x["localized_time"].tz_convert(x["timezone"]), 1)
print (df)
                 time      timezone            localized_time  \
0 2022-04-11 12:24:43  Europe/Paris 2022-04-11 12:24:43+00:00
1 2022-04-11 04:22:12    US/Eastern 2022-04-11 04:22:12+00:00

                         new
0  2022-04-11 14:24:43+02:00
1  2022-04-11 00:22:12-04:00

But because there are different timezones get objects instead datetimes dtype:
print (df.dtypes)
time                   datetime64[ns]
timezone                       object
localized_time    datetime64[ns, UTC]
new                            object
dtype: object


text:
Q: http.Request r.FormValue returns nothing/map[] I have the following Go code:
package main

import (
  "encoding/json"
  "fmt"
  "github.com/gorilla/mux"
  "github.com/gorilla/handlers"
  "log"
  "net/http"
  "io/ioutil"
)

type rLog struct {
  Method string
  URI string
  FormParam string
}

func commonMiddleware(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Header().Add("Content-Type", "application/json")
    formBs, err := ioutil.ReadAll(r.Body)
    if err != nil {
      log.Fatalf("Failed to decode postFormByteSlice: %v", err)
    }
    rl := rLog{Method: r.Method, URI: r.RequestURI, FormParam: string(formBs)}
    log.Printf("%+v", rl)
    next.ServeHTTP(w, r)
  })
}

func main() {
  port := ":3000"
  var router = mux.NewRouter()
  router.Use(commonMiddleware)
  router.HandleFunc("/m/{msg}", handleMessage).Methods("GET")
  router.HandleFunc("/n/", handleNumber).Methods("POST")

  headersOk := handlers.AllowedHeaders([]string{"Authorization"})
  originsOk := handlers.AllowedOrigins([]string{"*"})
  methodsOk := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS"})

  fmt.Printf("Server is running at http://localhost%s\n", port)
  log.Fatal(http.ListenAndServe(port, handlers.CORS(originsOk, headersOk, methodsOk)(router)))
}

func handleMessage(w http.ResponseWriter, r *http.Request) {
  vars := mux.Vars(r)
  message := vars["msg"]
  response := map[string]string{"message": message}
  json.NewEncoder(w).Encode(response)
}

func handleNumber(w http.ResponseWriter, r *http.Request) {
  log.Println(r.FormValue("name")) // this returns nothing
  response := map[string]string{"name": "1"} // dummy response
  json.NewEncoder(w).Encode(response)
}

What I try to do here is very simple.

*

*I want to log all POST form data (it's done inside the commonMiddleware)

*Access the form data inside the handleNumber i.e. name (and many more later) and do some logic with it.

The problem that I have right now is, the log.Println(r.FormValue("name")) returns nothing and I really wonder why that happened.

I've tried adding r.ParseForm() before log.Println(r.FormValue("name")). But it didn't work.
And, when I add log.Println(r.Form) line, it returns map[].
What did I missed here?

A: You truing to read r.Body twice, first in commonMiddleware with  ioutil.ReadAll(r.Body) and then in handleNumber with r.ParseForm(). You can't. It's io.Reader, you can't read it two times. You can instead, for example, r.ParseForm() in middlewear and then use parsed form data. In middlewear r.PosrForm.Encode() to log, and in handler r.FormValue() or r.Form.Get() to extract. I think something like this should do
func commonMiddleware(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Header().Add("Content-Type", "application/json")
    err:=r.ParseForm() //parse in middleware, data will be contained in r.PostForm
    if err != nil {
      log.Fatalf("Failed to decode postFormByteSlice: %v", err)
    }
    rl := rLog{Method: r.Method, URI: r.RequestURI, FormParam: r.PostForm.Encode()} //url.Values.Encode() stringifys form data
    log.Printf("%+v", rl)
    next.ServeHTTP(w, r)
  })
}

func main() {
  port := ":3000"
  var router = mux.NewRouter()
  router.Use(commonMiddleware)
  router.HandleFunc("/m/{msg}", handleMessage).Methods("GET")
  router.HandleFunc("/n/", handleNumber).Methods("POST")
}

func handleNumber(w http.ResponseWriter, r *http.Request) {
  log.Println(r.PostForm.Get("name")) // or just r.Form.Get("name") or r.FormValue("name")
  response := map[string]string{"name": "1"} // dummy response
  json.NewEncoder(w).Encode(response)
}


text:
Q: Waiting for my class to initialize (or how to wait for a Future to complete)? Futures in Dart are the bane of my existence.
I have a class, which calls an async (Future) function to start up the database instance like so:
class DataManager {
  bool DbIsReady = false;
  Db _db;

  DataManager() {
    init_mongo_db();
  }

  void init_mongo_db() {
    print("Initializing MongoDB");
    _db = new Db("mongodb://127.0.0.1/test");
    _db.open().then((_) {
      DbIsReady = true;
    });
  }

  Future<List> attemptLogin(String username, String password) {
    users = _db.collection("users");

    return // ... rest of code cut out for clarity
  }
}

This works OK server-side because when the server first starts up, the database is initialized. By the time a user actually attempts to log in, the database has been initialized and all is well. However, this fails miserably when I try to create an integration test for this. When I create the class, the database isn't yet initialized, so running the AttemptLogin routine fails.
DataManager db = new DataManager();
// This fails miserably, because db hasn't initialized yet.
db.AttemptLogin("test", "test");

Worse, the code uses the Dart DI framework, so I don't actually have direct control over the initialization of the DataManager class. This is the actual setup of the class:
setUp(() {
  app.addModule(new Module()
            ..bind(DataManager)
  app.setUp();
});

And then this is the call to test the login functionality, which ultimately calls the attemptLogin function which fails:
var req = new MockRequest("/user/login", contentType: 'JSON', method:'POST',
    body:JSON.encode(
      {"username" : 'test',
       "password" : 'test' }));

How does one deal with the async nature of the the database init and still do mock testing?  Specifically, is there a way to force the attemptLogin() Future to somehow wait for the completion of the DataManager class initialization?
Thanks for your help,
Greg

A: If your class has asynchronous setup, you can't use a normal constructor.
In that case, I'd just use a factory method returning a future:

class DataManager {
  final Db _db;
  DataManager._(this._db);
  static Future<DataManager> createNew() {
    var db = new Db("mongodb://127.0.0.1/test");
    return db.open().then((_) => new DataManager._(db));
  }
  ...
};

I don't know how you hook that into your dependency injection framework, but I guess it can do something with static methods.

A: what about using @lrn s solution like
setUp(() {
  return DataManager.createNew().then((dm) {
    app.addModule(new Module()
            ..bind(DataManager, toValue: dm);
    app.setUp();
  }
});

This way you already pass an initialized DataManager instance into the DI. If you request it later on you always can be sure it is already initialized.


text:
Q: Is "paiement" an english word? I'm wondering if the paiement word is an English word. It looks like a French word.
Could you confirm that paiement is an English word?

A: Paiement is a French word, English word is Payment.
Such words are used a lot in Louisiana(and other places which were French colonies or places closer to France).


text: Q: QED breaking of parity invariance QED is invariant under P,T,C for the Lagrangian containing operators of dimension equal or smaller than 4. I was wondering, what are the possible parity-breaking terms in QED with dimension smaller or equal than 6?


text:
Q: Gradle Android, exclude dependency from another module I have an Android app, who I want to unit test. With the MVP pattern, I was able to extract a lot of classes outside of the "android world" in order to test them as plain unit tests (with Junit) inside a separate module[1].
However, I would like to log some messages from those classes. So I have tried to use slf4j-api with the android binding. With the intention to provide the simple binding on my tests.
But the "test" module start with complaining that there are two slf4j binding in the classpath and that he is using the android-binding.
So my question is, How can I exclude the slf4j-android dependency from the "test" module ?
Here is the build.gradle of my "test" module
evaluationDependsOn(":app")

apply plugin: 'java'

dependencies {
    def app = project(':app')

    testCompile project(path: ':app', configuration: 'debugCompile')

    def debugVariant = app.android.applicationVariants.find({it.name == 'debug'})
    testCompile debugVariant.javaCompile.classpath
    testCompile debugVariant.javaCompile.outputs.files
    testCompile files(app.plugins.findPlugin("com.android.application").getBootClasspath())

    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    testCompile 'org.powermock:powermock-api-mockito:1.6.1'
    testCompile 'org.assertj:assertj-core:1.7.1'

}

[1] http://blog.blundell-apps.com/how-to-run-robolectric-junit-tests-in-android-studio/

A: Use the "exclude" attribute to remove dependent libraries.  Something like the following:
testCompile 'junit:junit:4.12' {
    exclude 'slf4j-android'
}
I'm not sure which library you need to exclude it from.  To find out, use gradle to list the library dependencies.
gradle dependencies