问:
python run as administrator interrupt wxpython
I am developing a script that uses admin privilege I use the code beneath to acquire it, but when I add it to my script, suddenly the wxpython won't show.

What should I do to fix it?

```<code>    # Enable Adminstrator Privelaged
ASADMIN = 'asadmin'
if sys.argv[-1] != ASADMIN:
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
    try:
        shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
    except Exception as e:
        if e[-1]=="The operation was canceled by the user.":
            print "נא לאפשר הרשאות מנהלן לתוכנה"
        else:
            print "שגיאה בהפעלת המנהלן, פרטי השגיאה:\n"+str(e)
    sys.exit(0)

app = wx.App(False)
x=MainGUI(None,app)
app.MainLoop()
</code>```

答:
If I am reading this code correctly, it looks like you exit your script if the the user doesn't pass in asadmin on the command line. So when you run the script with no parameters or with the wrong string passed in, then your if statement runs. When that runs, it calls sys.exit(0) at the end, which causes the script to end there.

Thus you never reach the wxPython part of the code.

Body:
I am developing a script that uses admin privilege I use the code beneath to acquire it, but when I add it to my script, suddenly the wxpython won't show.

What should I do to fix it?

    # Enable Adminstrator Privelaged
ASADMIN = 'asadmin'
if sys.argv[-1] != ASADMIN:
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
    try:
        shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
    except Exception as e:
        if e[-1]=="The operation was canceled by the user.":
            print "נא לאפשר הרשאות מנהלן לתוכנה"
        else:
            print "שגיאה בהפעלת המנהלן, פרטי השגיאה:\n"+str(e)
    sys.exit(0)

app = wx.App(False)
x=MainGUI(None,app)
app.MainLoop()


来源: stackexchange

答:
To get the string you want:

```<code> var colonString = statesdata
   .features[0]
   .properties
   .geometry
   .coordinates[0][0]
   .map(pair => pair.reverse().join())
   .join(':');
</code>```

That is some deeply nested geoJSON.

ContentLicense: CC BY-SA 3.0

Title: JSON parse array loop

Body:
I'm trying to parse my array into representing data like this

-1.80511,53.84632:-1.80511,53.84632:-1.80511,53.84632:xxx,xxx:xxx
 lat,lng:lat,lng

so that it can be read by an api. here is the code I have so far, i can only get it into this format (coordsnew)

-1.7651,53.88566,-1.76896,53.8866,-1.77125,53.88801

My current code

    var coordsnew = [];
    var i;
    for (i = 0; i < coords.length; i++) {
     coordsnew += coords[i];
                console.log(coordsnew);

My coords array data is currently formed like this

     var statesdata = {
"type": "FeatureCollection",

"features": [
{ "type": "Feature", "properties": { "Name": "BD1 1", "Description": "BD1 1 postcode sector
Details<\/a>" }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -1.7526003839732, 53.795297076485198 ], [ -1.75078461615826, 53.795607063948303 ], [ -1.75078061651426, 53.795604064354201 ], [ -1.75051864373599, 53.795500080054303 ], [ -1.74977069342604, 53.794539203056601 ], [ -1.74974469120328, 53.794412218350601 ], [ -1.7492607290865, 53.793926281950498 ], [ -1.74918471905401, 53.793471336517399 ], [ -1.74939968041321, 53.793170369115202 ], [ -1.74925067188821, 53.792542445011001 ], [ -1.74902869183461, 53.792380467011299 ], [ -1.74897763675983, 53.790929638498604 ], [ -1.74976552406105, 53.790511677309198 ], [ -1.75025545811429, 53.790349689915303 ], [ -1.75108238214196, 53.790913612609998 ], [ -1.75116539246416, 53.791395554773104 ], [ -1.75217230177679, 53.7921254555514 ], [ -1.75238127314532, 53.792044462329898 ], [ -1.75393711035648, 53.792635372231103 ], [ -1.75434805085846, 53.792400394475202 ], [ -1.75315716556359, 53.791713491060101 ], [ -1.7536130920749, 53.791275536607898 ], [ -1.75509590228284, 53.7910175474209 ], [ -1.75604581420275, 53.791646460844603 ], [ -1.75617780646011, 53.791840436265602 ], [ -1.75572287565107, 53.792179402357696 ], [ -1.75536192519302, 53.792321390401902 ], [ -1.75511998619384, 53.793075304829799 ], [ -1.75459505898236, 53.793299285383803 ], [ -1.75372115084327, 53.792977334818701 ], [ -1.75370116224194, 53.793190310007297 ], [ -1.75374816559962, 53.793404284194501 ], [ -1.75376716436202, 53.793429281000698 ], [ -1.75431110539553, 53.793587255224999 ], [ -1.75449608126177, 53.793544257847103 ], [ -1.75468606209324, 53.793633244863699 ], [ -1.75451310097882, 53.794060196877098 ], [ -1.75454309938432, 53.794108190830698 ], [ -1.75468508313808, 53.794129186485499 ], [ -1.75508202351291, 53.7938512139769 ], [ -1.75526600519453, 53.793943200719497 ], [ -1.75589992558159, 53.793869201069697 ], [ -1.75611888768616, 53.7935972302026 ], [ -1.75644384581814, 53.793534233333297 ], [ -1.75653285692984, 53.794052171178201 ], [ -1.75652885758116, 53.794056170760101 ], [ -1.75585494164085, 53.794121171996501 ], [ -1.75585194229808, 53.794128171212002 ], [ -1.75542100357864, 53.794348150996697 ], [ -1.75538800907876, 53.794384147193803 ], [ -1.75516103908185, 53.794446142888802 ], [ -1.7546371262232, 53.795013083049803 ], [ -1.75439915177408, 53.794938095018303 ], [ -1.75387121644832, 53.794961099275 ], [ -1.75351226756764, 53.795146082231298 ], [ -1.75297532691447, 53.795017104501397 ], [ -1.75291433127843, 53.794946113664501 ], [ -1.75265236634886, 53.795028107467203 ], [ -1.7526003839732, 53.795297076485198 ] ] ], [ [ [ -1.7524052922723, 53.792566400562002 ], [ -1.75210831392775, 53.7922304440348 ], [ -1.75197033209524, 53.792266441617201 ], [ -1.75092249848606, 53.793213343959003 ], [ -1.75151443343543, 53.793364318372703 ], [ -1.75168241131046, 53.793320321336203 ], [ -1.75193937541024, 53.7932043316018 ], [ -1.7524052922723, 53.792566400562002 ] ] ] ] } }

this is how the data is carried through and how it is represented in the console

        var coords = layer.feature.geometry.coordinates;
0:Array(1)
0:Array(94)
0:Array(2) [-1.75937311731598, 53.808343451011]
 0:-1.75937311731598
 1:53.808343451011

Body:
To get the string you want:

 var colonString = statesdata
   .features[0]
   .properties
   .geometry
   .coordinates[0][0]
   .map(pair => pair.reverse().join())
   .join(':');

That is some deeply nested geoJSON.


问:
Adding sublist to list in python3 not working
I have a really weird issue in Python3. I have some code that generates some different list from a list of integers (what this does exactly is not relevant).

```<code>def get_next_state(state):

    max_val = max(state)
    max_index = state.index(max_val)
    new_state = state

    for n in range(max_val + 1):
        new_state[max_index] -= 1
        new_state[(n + max_index) % len(state)] += 1

    return new_state
</code>```

Now all I want to do is add a next state to some list that keeps the states. This is my code:

```<code>l = [0, 2, 7, 0]
seen_states = []

for _ in range(10):
    print(l)
    seen_states += [l]
    l = get_next_state(l)

print(seen_states)
</code>```

For some reason list l is assigned correctly when I print it, but it is not added correctly to the list of seen states. Note that I have also tried seen_states.append(l) instead of using += [l]. Does anyone know why this happend?

Body:
I have a really weird issue in Python3. I have some code that generates some different list from a list of integers (what this does exactly is not relevant).

def get_next_state(state):

    max_val = max(state)
    max_index = state.index(max_val)
    new_state = state

    for n in range(max_val + 1):
        new_state[max_index] -= 1
        new_state[(n + max_index) % len(state)] += 1

    return new_state

Now all I want to do is add a next state to some list that keeps the states. This is my code:

l = [0, 2, 7, 0]
seen_states = []

for _ in range(10):
    print(l)
    seen_states += [l]
    l = get_next_state(l)

print(seen_states)

For some reason list l is assigned correctly when I print it, but it is not added correctly to the list of seen states. Note that I have also tried seen_states.append(l) instead of using += [l]. Does anyone know why this happend?

Body:
Using new_state = state[:] (copies the list instead of referencing the original) in the get_next_state produces the following output:

[0, 2, 7, 0]
[2, 4, 1, 2]
[3, 1, 2, 3]
[0, 2, 3, 4]
[1, 3, 4, 1]
[2, 4, 1, 2]
[3, 1, 2, 3]
[0, 2, 3, 4]
[1, 3, 4, 1]
[2, 4, 1, 2]
[[0, 2, 7, 0], [2, 4, 1, 2], [3, 1, 2, 3], [0, 2, 3, 4], [1, 3, 4, 1], [2, 4, 1, 2], [3, 1, 2, 3], [0, 2, 3, 4], [1, 3, 4, 1], [2, 4, 1, 2]]

Not sure if this is your desired output, as you did not specify what you are getting as "wrong" output


问:
Camera2 API HDR+ Auto
Does anyone know of documentation available for implementing HDR+ Auto with the Camera2 API? I have not been able to find any examples where this is used.

Open Camera uses HDR, but not HDR+ Auto.

答:
I've been looking for this ever since I found out that the ported hdr+ app doesn't work on my favorite custom ROM. You can find the original paper here. I came to know of it from the "Resources" section of this implementation.

APKs of many ported versions of the Google Camera (hdr+) are available on XDA forums, and I found a Github project for one such version here.

Title: Camera2 API HDR+ Auto


问:
body shrinks more than 100% on mobile
When I resize the browser, it works fine, but on mobile and when I inspect on mobile size the body starts to shrink. The more I reduce, the more the body shrinks.

Any Ideas?

This is my website: http://www.mydeepwellbeing.com/

答:
It ended up being the h3 tag was too large on mobile, so the title was bigger than the body.
As soon as I lowered the font-size for h3 on mobile, it worked perfectly.</p>

Title: body shrinks more than 100% on mobile


问:
Ruby SQlite SELECT Returning an Unwanted Array

I am trying to grab a couple values from an sqlite database, but instead of returning the value I am SELECT-ing, it is returning that value in an array inside of another array.

My code:

```<code>def self.find(id, database_connection)
  name = database_connection.execute("SELECT name FROM pokemon WHERE id = ?", id)
  type = database_connection.execute("SELECT type FROM pokemon WHERE id = ?", id)

  pokemon_inst = Pokemon.new(id: id, name: name, type: type, db: database_connection)
end
</code>```

The Problem:

When I run pry.binding

name outputs [["Pikachu"]]

type outputs [["electric]]

Is this working correctly? I can't imagine I should I just be calling name[0][0] to access the data, right?

答:
The execute() method wraps everything it is returning in an array, and each database row is placed in an array. So, for the single value being queried to be in two arrays is correct.

Since everything is working as it should I will be adjusting my code to this:

```<code>def self.find(id, database_connection)
  pokemon = database_connection.execute("SELECT * FROM pokemon WHERE id = ?", id).flatten
  name = pokemon[1]
  type = pokemon[2]

  pokemon_inst = Pokemon.new(id: id, name: name, type: type, db: database_connection)
end
</code>```

The adjustments are to flatten the array when it is assigned the queried data and to assign the individual values from that array.

Body:
I am trying to grab a couple values from an sqlite database, but instead of returning the value I am SELECT-ing, it is returning that value in an array inside of another array.

My code:

def self.find(id, database_connection)
  name = database_connection.execute("SELECT name FROM pokemon WHERE id = ?", id)
  type = database_connection.execute("SELECT type FROM pokemon WHERE id = ?", id)

  pokemon_inst = Pokemon.new(id: id, name: name, type: type, db: database_connection)
end

The Problem:

When I run pry.binding

name outputs [["Pikachu"]]

type outputs [["electric]]

Is this working correctly? I can't imagine I should I just be calling name[0][0] to access the data, right?

Body:
The execute() method wraps everything it is returning in an array, and each database row is placed in an array. So, for the single value being queried to be in two arrays is correct.

Since everything is working as it should I will be adjusting my code to this:

def self.find(id, database_connection)
  pokemon = database_connection.execute("SELECT * FROM pokemon WHERE id = ?", id).flatten
  name = pokemon[1]
  type = pokemon[2]

  pokemon_inst = Pokemon.new(id: id, name: name, type: type, db: database_connection)
end

The adjustments are to flatten the array when it is assigned the queried data and to assign the individual values from that array.


问:
auto closing Vaadin window after delay
I wanted to create my own message box class so that I can create different types of messages (w/o buttons e.g.). For the tray messages I want an auto close after lets say 5sec delay.

I've searched the internet: I found very old posts suggesting ProgressIndicator or some "newer" ones (4yo) with push/poll/threading. I really wonder if there is a neat solution meanwhile in Vaadin 7.6. Push/poll seemed a little too complicated for me to understand the mechanics (beginner...).

答:
Well, as noone has given the proper answer, you could do something like this with a Timer and a TimerTask:

```<code>Window wd = new Window("Your autoclosing window");
// do stuff
Timer delayer = new Timer();
retrasador.schedule(new TimerTask(){
    @Override
    public void run() {
        UI.getCurrent().access(new Runnable() {
            @Override
            public void run() {
                wd.close();
            }
        });
    }
}, 10000); // auto closes after 10 s
</code>```

Note that you should probably take care of your Timer after you're done with it.

Title: auto closing Vaadin window after delay

Body:
Well, as noone has given the proper answer, you could do something like this with a Timer and a TimerTask:

Window wd = new Window("Your autoclosing window");
// do stuff
Timer delayer = new Timer();
retrasador.schedule(new TimerTask(){
    @Override
    public void run() {
        UI.getCurrent().access(new Runnable() {
            @Override
            public void run() {
                wd.close();
            }
        });
    }
}, 10000); // auto closes after 10 s

Note that you should probably take care of your Timer after you're done with it.


问:
Operator precedence in C Definitions
Wikipedia claims that the [] operator precedes the * operator in evaluation.

Then, why does the following statement:

```<code>char *a[3];
</code>```

declare an array of 3 character pointers, rather than a pointer to an array of 3 characters as per the operator precedence?

答:
I'm confused about the question - the interpretation of the declaration matches the operator precedence.  If you want a pointer to an an array you have to use parens to 'bind the * to the indentifier' before the [] binding.

```<code>char (*a)[3];
</code>```

ContentLicense: CC BY-SA 2.5

Title: Operator precedence in C Definitions

Body:
Wikipedia claims that the [] operator precedes the * operator in evaluation.

Then, why does the following statement:

char *a[3];

declare an array of 3 character pointers, rather than a pointer to an array of 3 characters as per the operator precedence?

Body:
I'm confused about the question - the interpretation of the declaration matches the operator precedence.  If you want a pointer to an an array you have to use parens to 'bind the * to the indentifier' before the [] binding.

char (*a)[3];


问:
Cannot render byte[] as an Image in MVC 5 ASP.Net
I have a simple MVC 5 app using Northwind database. The view in question is displaying a list of categories from Categories table in Northwind. I have tried  to render the byte array using an img tag but without success.

I have looked at MVC How to display a byte array image from model and tried using a custom html helper but even that did not work

Is there something I am missing in my approach when converting a byte[] to an image?

Tried following ( look at img tag for what I tried)

```<code>@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.CategoryName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Description)
        </td>
        <td>
            <img src="@String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(item.Picture))" />
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.CategoryID }) |
            @Html.ActionLink("Details", "Details", new { id=item.CategoryID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.CategoryID })
        </td>
    </tr>
}
</code>```

EF Category class

```<code>public partial class Category
{
    public int CategoryID { get; set; }

    [Required]
    [StringLength(15)]
    public string CategoryName { get; set; }

    [Column(TypeName = "ntext")]
    public string Description { get; set; }

    [Column(TypeName = "image")]
    public byte[] Picture { get; set; }
}
</code>```

Action method

```<code>  public class CategoriesController : Controller
  {
        private NorthwindDB db = new NorthwindDB();

        // GET: Categories
        public ActionResult Index()
        {
            return View(db.Categories.ToList());
        }
  }
</code>```

答:
I figured out that it is not easy the convert Nortwind image to format base64 string. I found a source. According to explanation, "Northwind images were created with Microsoft Access so they have a 78 byte OLE header". So, we should remove the headers. Firstly, modify Category entity.

```<code>public partial class Category
{
    public int CategoryID { get; set; }

    [Required]
    [StringLength(15)]
    public string CategoryName { get; set; }

    [Column(TypeName = "ntext")]
    public string Description { get; set; }

    [Column(TypeName = "image")]
    public byte[] Picture { get; set; }

    [NotMapped]
    public string Base64String
    {
        get
        {
            var base64Str = string.Empty;
            using (var ms = new MemoryStream())
            {
                int offset = 78;
                ms.Write(Picture, offset, Picture.Length - offset);
                var bmp = new System.Drawing.Bitmap(ms);
                using (var jpegms = new MemoryStream())
                {
                    bmp.Save(jpegms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    base64Str = Convert.ToBase64String(jpegms.ToArray());
                }
            }
            return base64Str;
        }
    }
}
</code>```

And then put the Base64String property inside img attribute.

```<code><img src="@String.Format("data:image/jpg;base64,{0}", item.Base64String)" />
</code>```

Body:
I have a simple MVC 5 app using Northwind database. The view in question is displaying a list of categories from Categories table in Northwind. I have tried  to render the byte array using an img tag but without success.

I have looked at MVC How to display a byte array image from model and tried using a custom html helper but even that did not work

Is there something I am missing in my approach when converting a byte[] to an image?

Tried following ( look at img tag for what I tried)

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.CategoryName)

            @Html.DisplayFor(modelItem => item.Description)

            @Html.ActionLink("Edit", "Edit", new { id=item.CategoryID }) |
            @Html.ActionLink("Details", "Details", new { id=item.CategoryID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.CategoryID })

}

EF Category class

public partial class Category
{
    public int CategoryID { get; set; }

    [Required]
    [StringLength(15)]
    public string CategoryName { get; set; }

    [Column(TypeName = "ntext")]
    public string Description { get; set; }

    [Column(TypeName = "image")]
    public byte[] Picture { get; set; }
}

Action method

  public class CategoriesController : Controller
  {
        private NorthwindDB db = new NorthwindDB();

        // GET: Categories
        public ActionResult Index()
        {
            return View(db.Categories.ToList());
        }
  }

Body:
I figured out that it is not easy the convert Nortwind image to format base64 string. I found a source. According to explanation, "Northwind images were created with Microsoft Access so they have a 78 byte OLE header". So, we should remove the headers. Firstly, modify Category entity.

public partial class Category
{
    public int CategoryID { get; set; }

    [Required]
    [StringLength(15)]
    public string CategoryName { get; set; }

    [Column(TypeName = "ntext")]
    public string Description { get; set; }

    [Column(TypeName = "image")]
    public byte[] Picture { get; set; }

    [NotMapped]
    public string Base64String
    {
        get
        {
            var base64Str = string.Empty;
            using (var ms = new MemoryStream())
            {
                int offset = 78;
                ms.Write(Picture, offset, Picture.Length - offset);
                var bmp = new System.Drawing.Bitmap(ms);
                using (var jpegms = new MemoryStream())
                {
                    bmp.Save(jpegms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    base64Str = Convert.ToBase64String(jpegms.ToArray());
                }
            }
            return base64Str;
        }
    }
}

And then put the Base64String property inside img attribute.

<img src="@String.Format("data:image/jpg;base64,{0}", item.Base64String)" />


问:
How to check status-code of URL of the application in protractor test?
I am using request package to request the url and using deferred promise :

```<code>getMonitoredPageName = function () {
    var deferredExecutor = protractor.promise.defer();
    var defer = protractor.promise.defer();

    request('http://google.com',
    function (error, response, body) {
        if (error || response.statusCode ==400) {
            defer.reject(response.statusCode);
        } else {
            defer.fulfill(response.statusCode);
        }
    });

    return defer.promise;
}
</code>```

And i am calling above function from test as :

```<code>  it('should log the page name of every page view in the wizard', function () {

    // We opened the first page of the wizard and we expect it to have been logged
    expect(heartBeatNotification.getMonitoredPageName()).toBeTruthy(true);
    //expect(heartBeatNotification.getMonitoredPageName()).toBe(400);
    //browser.controlFlow().execute(heartBeatNotification.getMonitoredPageName);

})
</code>```

Problem is test case always succeeds no matter what url has given. Need to write test case to check Application is running or not.

答:
Any non-zero status code will be "truthy" so you need to adjust your test case.  Make it check that the response is either explicitly 200, or maybe even just check thats its anything 2xx because that's still successful.

```<code>expect(heartBeatNotification.getMonitoredPageName()).toEqual(200);
</code>```

Or just check that its greater than 200 or less than 300 etc.

```<code>expect(heartBeatNotification.getMonitoredPageName()).toBeGreaterThanOrEqual(200);
expect(heartBeatNotification.getMonitoredPageName()).toBeLessThan(300);
</code>```

Also, minor note, you might want to review the logic on your first if block.

```<code>    if (error || response.statusCode ==400) {
        defer.reject(response.statusCode);
    }
</code>```

If there was an error, there might not be a response.statusCode (not positive).  Might be better to just reject with the error itself

Body:
I am using request package to request the url and using deferred promise :

getMonitoredPageName = function () {
    var deferredExecutor = protractor.promise.defer();
    var defer = protractor.promise.defer();

    request('http://google.com',
    function (error, response, body) {
        if (error || response.statusCode ==400) {
            defer.reject(response.statusCode);
        } else {
            defer.fulfill(response.statusCode);
        }
    });

    return defer.promise;
}

And i am calling above function from test as :

  it('should log the page name of every page view in the wizard', function () {

    // We opened the first page of the wizard and we expect it to have been logged
    expect(heartBeatNotification.getMonitoredPageName()).toBeTruthy(true);
    //expect(heartBeatNotification.getMonitoredPageName()).toBe(400);
    //browser.controlFlow().execute(heartBeatNotification.getMonitoredPageName);

})

Problem is test case always succeeds no matter what url has given. Need to write test case to check Application is running or not.

Body:
Any non-zero status code will be "truthy" so you need to adjust your test case.  Make it check that the response is either explicitly 200, or maybe even just check thats its anything 2xx because that's still successful.

expect(heartBeatNotification.getMonitoredPageName()).toEqual(200);

Or just check that its greater than 200 or less than 300 etc.

expect(heartBeatNotification.getMonitoredPageName()).toBeGreaterThanOrEqual(200);
expect(heartBeatNotification.getMonitoredPageName()).toBeLessThan(300);

Also, minor note, you might want to review the logic on your first if block.

    if (error || response.statusCode ==400) {
        defer.reject(response.statusCode);
    }

If there was an error, there might not be a response.statusCode (not positive).  Might be better to just reject with the error itself


问:
Create one more peer node using hyperledger-composer
I implemented hyperledger composer tutorial and create a simple business network definition and deploy it on through composer and implement it's rest API's through composer-rest-server. Now I want to add one more peer to it on a different local machine which can access blockchain I created previously, so my question is How can I achieve that a different peer node (another local machine) connected to blockchain I created in the composer tutorial?</p>

答:
you can check the S/Overflow link provided by Ahmed Nasser relating to adding your peer to an existing Fabric network.

Once you have your Fabric network up and running, and all of your network configuration / resolution / docker configuration tested and working, you can come to Composer to define the connection info, such as adding additional peers (and therefore create the requisite business network cards that contain that info).

This single organisation tutorial can give you an idea of what's involved - it builds upon a Fabric network that was already created (a simple, one-peer Fabric blockchain Dev environment) ..see here ->  https://hyperledger.github.io/composer/tutorials/deploy-to-fabric-single-org.html

It obviously refers to 'localhost' in this scenario - obviously, you are creating something on an IP network, so you will need IP addresses/ host resolution as appropriate.


问:
VBA Replace not working for numbers over 1.0
I'm trying to make a macro that takes the selected cells, replace the "." with ",", then changes it to double, divides it by 2 and rounds it off.

Examples of cells:

0.910   1.000

```<code>For Each Cell In Selection
    Cell.Value = Replace(Cell, ".", ",")
    Cell = CDbl(Cell.Value)
    Cell = Cell / 2
    Cell = Round(Cell, 4)
Next Cell
</code>```

I'm expecting to get:

0.4550  0.5000

The problem is that if I have a number greater than 1.0 it just removes the "." and doesn't replace it with anything and since the cells have 3 decimals, I suddenly get 1000 instead of 1.

So I get:

0.4550  500

Any suggestions of what goes wrong?

答:
How about:</p>

```<code>Sub foo2()
Dim cell As Range
Dim value As Double
    For Each cell In Selection
        cell = Application.RoundUp(cell, 1)
        cell = CStr(cell.value)
        cell.NumberFormat = "@"
        If cell.value <> "1" Then
            cell.value = cell.value & "00"
        Else
            cell.value = cell.value & ",000"
        End If
        cell.value = Replace(cell.value, ".", ",")
    Next cell
End Sub
</code>```

Body:
I'm trying to make a macro that takes the selected cells, replace the "." with ",", then changes it to double, divides it by 2 and rounds it off.

Examples of cells:

0.910   1.000

For Each Cell In Selection
    Cell.Value = Replace(Cell, ".", ",")
    Cell = CDbl(Cell.Value)
    Cell = Cell / 2
    Cell = Round(Cell, 4)
Next Cell

I'm expecting to get:

0.4550  0.5000

The problem is that if I have a number greater than 1.0 it just removes the "." and doesn't replace it with anything and since the cells have 3 decimals, I suddenly get 1000 instead of 1.

So I get:

0.4550  500

Any suggestions of what goes wrong?

Body:
How about:

Sub foo2()
Dim cell As Range
Dim value As Double
    For Each cell In Selection
        cell = Application.RoundUp(cell, 1)
        cell = CStr(cell.value)
        cell.NumberFormat = "@"
        If cell.value <> "1" Then
            cell.value = cell.value & "00"
        Else
            cell.value = cell.value & ",000"
        End If
        cell.value = Replace(cell.value, ".", ",")
    Next cell
End Sub


问:
Extract and sort data from a workbook to another with VBA
So my question is simple "How to extract and sort data from a workbook to another"?

I have a document ( let's name it "devices" ) sent over the network, as a result of an another document ( "devices used" ), which sorts some devices used by people in that day. it doesn't arrange the data.

What I wanna do is take that data from that document, and sort it as a table in another workbook.

I know I have to declare the workbook and the sheets, but how to extract and sort the data it's out of my power of knowledge ( yes, I'm new to vba ).

Regards,
Alex

答:
i think you should start by declaring the Sub Procedures. The first thing there according to your problem should be to declare each workbook required for your task.

The second thing you should do is to declare a for loop statement that would check if of your criteria and if it matches your request, move it by simple using Range statements.

Hope this helps,
Alex


问:
Fit QLabel height without WordWrap
I need to do a manual word wrap because the native wordWrap from Qt splits in wrong places. I've already done the wrap to my text, but the content wasn't showing all the content. The QLabel was cutting the top and the bottom like the image:

Can I fit the Qlabel to the height of the text inside it without wordWrap?

答:
I write it as height scalable :

```<code>QLabel lbl;
int count = 0;
QString str = "";

// set lbl text
lbl.setText("hfdsf\ncsad\nfsc\dajkjkjkjhhkdkca\n925");
str = lbl.text();

for(int i = 0;i < str.length();i++)
    if(str.at(i).cell() == '\n')
        count++;

// resize lbl (width and height)
lbl.resize(lbl.fontMetrics().width("this is the max-length line in qlabel")
         , lbl.fontMetrics().height() * (count + 1));
</code>```

Notice : this work if you change QLable font face or size! just in height scalable (before every thing set your QLabel frameShape to BOX).

if you want do width scalable-content, you should do these steps :

read QLabel(lbl object) text as line to line

calculate every line length

select maximum of line length

use of QLabel::fontMetrics().width(QString str) for investigate str size in width

I hope this can help you...

ContentLicense: CC BY-SA 4.0

Title: Fit QLabel height without WordWrap

Body:
I write it as height scalable :

QLabel lbl;
int count = 0;
QString str = "";

// set lbl text
lbl.setText("hfdsf\ncsad\nfsc\dajkjkjkjhhkdkca\n925");
str = lbl.text();

for(int i = 0;i < str.length();i++)
    if(str.at(i).cell() == '\n')
        count++;

// resize lbl (width and height)
lbl.resize(lbl.fontMetrics().width("this is the max-length line in qlabel")
         , lbl.fontMetrics().height() * (count + 1));

Notice : this work if you change QLable font face or size! just in height scalable (before every thing set your QLabel frameShape to BOX).

if you want do width scalable-content, you should do these steps :

read QLabel(lbl object) text as line to line

calculate every line length

select maximum of line length

use of QLabel::fontMetrics().width(QString str) for investigate str size in width

I hope this can help you...


问:
Vectorise a code to transform a vector into a matrix
I have a vector A of dimension Nx1 in MATLAB, e.g.

```<code>N = 5;
A = [1
     2
     3
     4
     5];
</code>```

I want to construct a matrix B of dimension (N-1) x N such that:

for i=1,...,N, B(:,i) contains the rows 1,2,...,i-1,i+1,...,N of A.

In the example above,

```<code>B = [2 1 1 1 1
     3 3 2 2 2
     4 4 4 3 3
     5 5 5 5 4]
</code>```

This code does what I want:

```<code> B=zeros(N-1,N);
 for i=1:N
     if i>1 && i<N
         B(:,i)=[A(1:i-1); A(i+1:end)];
     elseif i==1
         B(:,i)=A(i+1:end);
     elseif i==N
         B(:,i)=A(1:i-1);
     end
 end
</code>```

But I want to vectorise it. Any help?

答:
This is what nchoosek generates with a clockwise 90 degree rotation.

```<code>B = rot90(nchoosek(A,N-1),-1);
</code>```

Body:
I have a vector A of dimension Nx1 in MATLAB, e.g.

N = 5;
A = [1
     2
     3
     4
     5];

I want to construct a matrix B of dimension (N-1) x N such that:

for i=1,...,N, B(:,i) contains the rows 1,2,...,i-1,i+1,...,N of A.

In the example above,

B = [2 1 1 1 1
     3 3 2 2 2
     4 4 4 3 3
     5 5 5 5 4]

This code does what I want:

 B=zeros(N-1,N);
 for i=1:N
     if i>1 && i<N
         B(:,i)=[A(1:i-1); A(i+1:end)];
     elseif i==1
         B(:,i)=A(i+1:end);
     elseif i==N
         B(:,i)=A(1:i-1);
     end
 end

But I want to vectorise it. Any help?

Body:
This is what nchoosek generates with a clockwise 90 degree rotation.

B = rot90(nchoosek(A,N-1),-1);


问:
How can I plot the surface of a structure which is given by vectors in python?

I would like to plot the surface of my data which is given by 3D vectors in cartesian coordinates x,y,z. The data can not be represented by a smooth function.

So first we generate some dummy data with the function eq_points(N_count, r) which returns an array points with the x,y,z coordinates of each point on the surface of our object. The quantity omega is the solid angle, and not of interest right now.

```<code>#credit to Markus Deserno from MPI
#https://www.cmu.edu/biolphys/deserno/pdf/sphere_equi.pdf
def eq_points(N_count, r):
    points = []
    a = 4*np.pi*r**2/N_count
    d = np.sqrt(a)
    M_theta = int(np.pi/d)
    d_theta = np.pi/M_theta
    d_phi = a/d_theta
    for m in range(M_theta):
        theta = np.pi*(m+0.5)/M_theta
        M_phi = int(2*np.pi*np.sin(theta)/d_phi)
        for n in range(M_phi):
            phi = 2*np.pi*n/M_phi

            points.append(np.array([r*np.sin(theta)*np.cos(phi),
                                    r*np.sin(theta)*np.sin(phi),
                                    r*np.cos(theta)]))

    omega = 4*np.pi/N_count

    return np.array(points), omega

#starting plotting sequence

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

points, omega = eq_points(400, 1.)

ax.scatter(points[:,0], points[:,1], points[:,2])
ax.scatter(0., 0., 0., c="r")
ax.set_xlabel(r'$x$ axis')
ax.set_ylabel(r'$y$ axis')
ax.set_zlabel(r'$Z$ axis')

plt.savefig("./sphere.png", format="png", dpi=300)
plt.clf()
</code>```

The result is a sphere shown in the following figure.  The blue points mark the data from the points array, while the red point is the origin.

I would like to get something like this
taken from here. However the data in the mplot3d tutorial is always a result of a smooth function. Except to the ax.scatter() function which I used for my sphere plot.

So in the end my goal would be to plot some data showing only its surface. This data is produced by changing the radial distance to the origin of each blue point. Further more it would be necessary to make sure each point is in contact with the surface. How are the surfaces which are plotted here e.g. in plot_surface() constructed in detail? Some actual live data looks like this:

答:
I would suggest finding the hull, and then plotting the simplices (i.e. the triangles forming the hull). Make sure to update the x,y,z-limits appropriately.

```<code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from scipy.spatial import ConvexHull

N = 1000
pts = np.random.randn(N, 3)

# exclude outliers
# obviously, this is data dependent
cutoff = 3.
is_outlier = np.any(np.abs(pts) > cutoff, axis=1)
pts = pts[~is_outlier]

# plot points
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(pts[:,0], pts[:,1], pts[:,2])

ax.set_xlim(-(cutoff +1), cutoff+1)
ax.set_ylim(-(cutoff +1), cutoff+1)
ax.set_zlim(-(cutoff +1), cutoff+1)
</code>```

```<code># get and plot hull
hull = ConvexHull(pts)

fig = plt.figure()
ax = Axes3D(fig)
vertices = [pts[s] for s in hull.simplices]
triangles = Poly3DCollection(vertices, edgecolor='k')
ax.add_collection3d(triangles)

ax.set_xlim(-(cutoff +1), cutoff+1)
ax.set_ylim(-(cutoff +1), cutoff+1)
ax.set_zlim(-(cutoff +1), cutoff+1)
plt.show()
</code>```

Body:
I would like to plot the surface of my data which is given by 3D vectors in cartesian coordinates x,y,z. The data can not be represented by a smooth function.

So first we generate some dummy data with the function eq_points(N_count, r) which returns an array points with the x,y,z coordinates of each point on the surface of our object. The quantity omega is the solid angle, and not of interest right now.

#credit to Markus Deserno from MPI
#https://www.cmu.edu/biolphys/deserno/pdf/sphere_equi.pdf
def eq_points(N_count, r):
    points = []
    a = 4*np.pi*r**2/N_count
    d = np.sqrt(a)
    M_theta = int(np.pi/d)
    d_theta = np.pi/M_theta
    d_phi = a/d_theta
    for m in range(M_theta):
        theta = np.pi*(m+0.5)/M_theta
        M_phi = int(2*np.pi*np.sin(theta)/d_phi)
        for n in range(M_phi):
            phi = 2*np.pi*n/M_phi

            points.append(np.array([r*np.sin(theta)*np.cos(phi),
                                    r*np.sin(theta)*np.sin(phi),
                                    r*np.cos(theta)]))

    omega = 4*np.pi/N_count

    return np.array(points), omega

#starting plotting sequence

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

points, omega = eq_points(400, 1.)

ax.scatter(points[:,0], points[:,1], points[:,2])
ax.scatter(0., 0., 0., c="r")
ax.set_xlabel(r'$x$ axis')
ax.set_ylabel(r'$y$ axis')
ax.set_zlabel(r'$Z$ axis')

plt.savefig("./sphere.png", format="png", dpi=300)
plt.clf()

The result is a sphere shown in the following figure.  The blue points mark the data from the points array, while the red point is the origin.

I would like to get something like this
taken from here. However the data in the mplot3d tutorial is always a result of a smooth function. Except to the ax.scatter() function which I used for my sphere plot.

So in the end my goal would be to plot some data showing only its surface. This data is produced by changing the radial distance to the origin of each blue point. Further more it would be necessary to make sure each point is in contact with the surface. How are the surfaces which are plotted here e.g. in plot_surface() constructed in detail? Some actual live data looks like this:

Body:
I would suggest finding the hull, and then plotting the simplices (i.e. the triangles forming the hull). Make sure to update the x,y,z-limits appropriately.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from scipy.spatial import ConvexHull

N = 1000
pts = np.random.randn(N, 3)

# exclude outliers
# obviously, this is data dependent
cutoff = 3.
is_outlier = np.any(np.abs(pts) > cutoff, axis=1)
pts = pts[~is_outlier]

# plot points
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(pts[:,0], pts[:,1], pts[:,2])

ax.set_xlim(-(cutoff +1), cutoff+1)
ax.set_ylim(-(cutoff +1), cutoff+1)
ax.set_zlim(-(cutoff +1), cutoff+1)

# get and plot hull
hull = ConvexHull(pts)

fig = plt.figure()
ax = Axes3D(fig)
vertices = [pts[s] for s in hull.simplices]
triangles = Poly3DCollection(vertices, edgecolor='k')
ax.add_collection3d(triangles)

ax.set_xlim(-(cutoff +1), cutoff+1)
ax.set_ylim(-(cutoff +1), cutoff+1)
ax.set_zlim(-(cutoff +1), cutoff+1)
plt.show()


问:
I cant cast in onclicklistener
I have 2 simple different classes that one extends another.
my first class is:

```<code>public class MyObject {}
</code>```

without something in it.

and another:

```<code>public class People extends MyObject{
public  String UserId;

public void setUserId(String userId) {
    UserId = userId;
}

public String getUserId() {
    return UserId;
}
}
</code>```

I was going to cast myobject to people in my adapter and in onBindViewHolder method,and I could do it well and worked,as below:

```<code>   @Override
public void onBindViewHolder(final RecyclerViewHolder holder, int position) {

        final People people = (People) array.get(position);
        //array is:ArrayList<MyObject> array
        ...}
</code>```

but the problem is when I'm going to do this cast in the same class but in onclicklistener like this:

```<code>holder.rlsearchitem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            People people1= (People) savedPeopleArray.get(i);
            //savedPeopleArray is:ArrayList<MyObject> savedPeopleArray
            ....
            }
        });
</code>```

I get this error:

```<code>com.example.qa.setGet.MyObject cannot be cast to com.example.qa.setGet.People
</code>```

why do I get this error even though I used this cast before and it worked?!

答:
It because you insert values inside ArrayList array as People, for example:
private List<MyObject> array = new ArrayList()

and then somewhere you insert

```<code>final MyObject obj = new People();
array.add(obj)
</code>```

in short you insert runtime object People inside array, so downcasting is no problem.

but in ArrayList savedPeopleArray you insert MyObject, for example like this:

```<code>final MyObject obj = new MyObject();
savedPeopleArray = new MyObject();
</code>```

at runtime element of savedPeopleArray is instance with type MyObject, so it is not possible to downcasting to People since the value is MyObject
To prevent ClassCastException you can use instance before casting, for example

```<code>MyObject obj= savedPeopleArray.get(i);
if (obj instanceof People){
   People people = (People) obj;
}
</code>```

I think this SO link will help you understand more about upcasting/downcasting in java What is the difference between up-casting and down-casting with respect to class variable

Title: I cant cast in onclicklistener

Body:
I have 2 simple different classes that one extends another.
my first class is:

public class MyObject {}

without something in it.

and another:

public class People extends MyObject{
public  String UserId;

public void setUserId(String userId) {
    UserId = userId;
}

public String getUserId() {
    return UserId;
}
}

I was going to cast myobject to people in my adapter and in onBindViewHolder method,and I could do it well and worked,as below:

   @Override
public void onBindViewHolder(final RecyclerViewHolder holder, int position) {

        final People people = (People) array.get(position);
        //array is:ArrayList<MyObject> array
        ...}

but the problem is when I'm going to do this cast in the same class but in onclicklistener like this:

holder.rlsearchitem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            People people1= (People) savedPeopleArray.get(i);
            //savedPeopleArray is:ArrayList<MyObject> savedPeopleArray
            ....
            }
        });

I get this error:

com.example.qa.setGet.MyObject cannot be cast to com.example.qa.setGet.People

why do I get this error even though I used this cast before and it worked?!

Body:
It because you insert values inside ArrayList array as People, for example:
private List<MyObject> array = new ArrayList()

and then somewhere you insert

final MyObject obj = new People();
array.add(obj)

in short you insert runtime object People inside array, so downcasting is no problem.

but in ArrayList savedPeopleArray you insert MyObject, for example like this:

final MyObject obj = new MyObject();
savedPeopleArray = new MyObject();

at runtime element of savedPeopleArray is instance with type MyObject, so it is not possible to downcasting to People since the value is MyObject
To prevent ClassCastException you can use instance before casting, for example

MyObject obj= savedPeopleArray.get(i);
if (obj instanceof People){
   People people = (People) obj;
}

I think this SO link will help you understand more about upcasting/downcasting in java What is the difference between up-casting and down-casting with respect to class variable


问:
How to clear all the jobs from Sidekiq?
I am using sidekiq for background tasks in Rails application. Now the numbers of jobs becomes more, so I want to clear all the jobs. I tried the following command in console

```<code>Sidekiq::Queue.new.clear
</code>```

but it was giving following error.

```<code>NameError: uninitialized constant Sidekiq::Queue
</code>```

How do I clear all the jobs from sidekiq?

答:
As of latest Sidekiq, just blow it up:

```<code>require 'sidekiq/api'

q = Sidekiq::Queue.new
q.
</code>```

Yes, the command to clear all is literally a bomb emoji.  Also works for Sidekiq::RetrySet.

Or if you're no fun you can use q.clear

Title: How to clear all the jobs from Sidekiq?

Body:
I am using sidekiq for background tasks in Rails application. Now the numbers of jobs becomes more, so I want to clear all the jobs. I tried the following command in console

Sidekiq::Queue.new.clear

but it was giving following error.

NameError: uninitialized constant Sidekiq::Queue

How do I clear all the jobs from sidekiq?

Body:
As of latest Sidekiq, just blow it up:

require 'sidekiq/api'

q = Sidekiq::Queue.new
q.

Yes, the command to clear all is literally a bomb emoji.  Also works for Sidekiq::RetrySet.

Or if you're no fun you can use q.clear


问:
Boto3 folder sync under new S3 'folder'
So, before anyone tells me about the flat structure of S3, I already know, but the fact is you can create 'folders' in S3. My objective with this Python code is to create a new folder named using the date of running and appending the user's input to this (which is the createS3Folder function) - I then want to sync a folder in a local directory to this folder.

The problem is that my upload_files function creates a new folder in S3 that exactly emulates the folder structure of my local set up.

Can anyone suggest how I would just sync the folder into the newly created one without changing names?

```<code>import sys
import boto3
import datetime
import os

teamName = raw_input("Please enter the name of your project: ")
bucketFolderName = ""

def createS3Folder():
    date = datetime.date.today().strftime("%Y") + "." +
    datetime.date.today().strftime("%B") + "." +
    datetime.date.today().strftime("%d")
    date1 = datetime.date.today()
    date = str(date1) + "/" #In order to generate a file, you must
    put "/" at the end of key
    bucketFolderName = date + teamName + "/"
    client = boto3.client('s3')
    client.put_object(Bucket='MY_BUCKET',Key=bucketFolderName)
    upload_files('/Users/local/directory/to/sync')

def upload_files(path):
    session = boto3.Session()
    s3 = session.resource('s3')
    bucket = s3.Bucket('MY_BUCKET')
    for subdir, dirs, files in os.walk(path):
        for file in files:
            full_path = os.path.join(subdir, file)
            with open(full_path, 'rb') as data:
                bucket.put_object(Key=bucketFolderName, Body=data)

def main():
    createS3Folder()

if __name__ == "__main__":
    main()
</code>```

答:
"the fact is you can create 'folders' in S3"

No, you can't.

You can create an empty object that looks like a folder in the console, but it is still not a folder, it still has no meaning, it is still unnecessary, and if you delete it via the API, all the files you thought were "in" the folder will still be in the bucket.  (If you delete it from the console, all the contents are deleted from the bucket, because the console explicitly deletes every object starting with that key prefix.)

The folder you are creating is not a container and cannot have anything inside it, because S3 does not have folders that are containers.

If I want to store a file cat.png and make it look like it's in the hat/ folder, you simply set the object key to hat/cat.png.  This has exactly the same effect as observed in the console, whether or not the hat/ folder was explicitly created or not.

To so what you want, you simply build the desired object key for each object with string manipulation, including your common prefix ("folder name") and / delimiters.  Any folder structure the / delimiters imply will be displayed in the console as a result.

Title: Boto3 folder sync under new S3 'folder'

Body:
So, before anyone tells me about the flat structure of S3, I already know, but the fact is you can create 'folders' in S3. My objective with this Python code is to create a new folder named using the date of running and appending the user's input to this (which is the createS3Folder function) - I then want to sync a folder in a local directory to this folder.

The problem is that my upload_files function creates a new folder in S3 that exactly emulates the folder structure of my local set up.

Can anyone suggest how I would just sync the folder into the newly created one without changing names?

import sys
import boto3
import datetime
import os

teamName = raw_input("Please enter the name of your project: ")
bucketFolderName = ""

def createS3Folder():
    date = datetime.date.today().strftime("%Y") + "." +
    datetime.date.today().strftime("%B") + "." +
    datetime.date.today().strftime("%d")
    date1 = datetime.date.today()
    date = str(date1) + "/" #In order to generate a file, you must
    put "/" at the end of key
    bucketFolderName = date + teamName + "/"
    client = boto3.client('s3')
    client.put_object(Bucket='MY_BUCKET',Key=bucketFolderName)
    upload_files('/Users/local/directory/to/sync')

def upload_files(path):
    session = boto3.Session()
    s3 = session.resource('s3')
    bucket = s3.Bucket('MY_BUCKET')
    for subdir, dirs, files in os.walk(path):
        for file in files:
            full_path = os.path.join(subdir, file)
            with open(full_path, 'rb') as data:
                bucket.put_object(Key=bucketFolderName, Body=data)

def main():
    createS3Folder()

if __name__ == "__main__":
    main()


问:
Change button text on click
So, I followed an online course from www.code.org to accomodate myself with JavaScript. I used elements such as setProperty(); and onEvent();. I used an online editor to add a button and the following code to change the button's text when the user clicks it:

```<code>onEvent("button1","click", function()
 {
  setProperty("button1","text","Hello there!");
 });
</code>```

My question is: How can I do this thing in HTML, by using the <button> tag?

答:
This would most likely be the equivalent: a combination of adding a click event listener to the button and changing its text in the callback's function body via texContent.

document.getElementById('button1').addEventListener('click', function() {
  this.textContent = 'Hello there!';
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="button1">Click Me</button></code>```

Title: Change button text on click

Body:
So, I followed an online course from www.code.org to accomodate myself with JavaScript. I used elements such as setProperty(); and onEvent();. I used an online editor to add a button and the following code to change the button's text when the user clicks it:

onEvent("button1","click", function()
 {
  setProperty("button1","text","Hello there!");
 });

My question is: How can I do this thing in HTML, by using the <button> tag?

Body:
This would most likely be the equivalent: a combination of adding a click event listener to the button and changing its text in the callback's function body via texContent.

document.getElementById('button1').addEventListener('click', function() {
  this.textContent = 'Hello there!';
});

<button id="button1">Click Me</button>


问:
replace a nested for loop with mapply
I am a beginner in R. I am working on linear programming using R studio's Cplex to solve a model. One of the constraint in my model is Xl(i,j,t) <= D(i,j,t). I am able to do this with nested for loop with a small dimension (16X16X6). But I want to run my model a lot bigger model, more like 2500X2500X60. I need to save memory and run it faster than the nested for loop.  I thought about using apply but I don't know how to make it work. Any help would be greatly appreciated!

```<code>location <-16
horizon <-6
Amat <- NULL
Xe_null <- array(0, dim = c(locations, locations, horizon))
Xl_null <- array(0, dim = c(locations, locations, horizon))
Xl      <- array(0, dim = c(locations, locations, horizon))
Xl <- Xl_null
for (t in 1:horizon) {
  for (j in 1:locations) {
    for (i in 1:locations) {
      Xl[i,j,t] <- 1
      Amat <- rbind(Amat, c(as.vector(Xe_null), as.vector(Xl)))
      Xl <- Xl_null
 } } }
dim(Amat) # 1536 3072
</code>```

Here is another constraint.

```<code>R       <- array(, dim=c(locations, horizon, horizon))
R_null  <- array(, dim=c(locations, horizon, horizon))
R <- R_null
Xe <- Xe_null
Xl <- Xl_null
#
for (t in 1:(horizon-1)) {
  for (tp in (t+1):horizon) {
    for (j in 1:locations)     {
      for (i in 1:locations)      {
        if ((tp-t) ==Travel_time[i,j])
        {
          Xe[i,j,t]=1
          Xl[i,j,t]=1
        }
      }
      R[j,tp,t] = 1
      R[j,tp,t+1] = -1
      Amat <- rbind(Amat, c(as.vector(Xe), as.vector(Xl),as.vector(R)))
      }
  }
}
</code>```

I try to do this:

```<code>Xl = function(ii,jj,tt){1}
t =c(1:horizon)
i =c(1:locations)
j =c(1:locations)
output_Xl = apply(expand.grid(i,j,t),1,function(x,y,h) Xl(x[1],x[2],x[3]))
Xl_new <- array(output_Xl, dim = c(locations, locations, horizon))
Amat <- rbind(Amat, c(as.vector(Xe_null), as.vector(Xl_new)))
dim(Amat) # 1 3072
</code>```

答:
You can get the same output with</p>

```<code>T <- horizon*locations*locations
Bmat <- cbind(matrix(0, nrow=T, ncol=T), diag(1, nrow=T, ncol=T))
identical(Amat, Bmat)
# TRUE
</code>```

Title: replace a nested for loop with mapply

Body:
I am a beginner in R. I am working on linear programming using R studio's Cplex to solve a model. One of the constraint in my model is Xl(i,j,t) <= D(i,j,t). I am able to do this with nested for loop with a small dimension (16X16X6). But I want to run my model a lot bigger model, more like 2500X2500X60. I need to save memory and run it faster than the nested for loop.  I thought about using apply but I don't know how to make it work. Any help would be greatly appreciated!

location <-16
horizon <-6
Amat <- NULL
Xe_null <- array(0, dim = c(locations, locations, horizon))
Xl_null <- array(0, dim = c(locations, locations, horizon))
Xl      <- array(0, dim = c(locations, locations, horizon))
Xl <- Xl_null
for (t in 1:horizon) {
  for (j in 1:locations) {
    for (i in 1:locations) {
      Xl[i,j,t] <- 1
      Amat <- rbind(Amat, c(as.vector(Xe_null), as.vector(Xl)))
      Xl <- Xl_null
 } } }
dim(Amat) # 1536 3072

Here is another constraint.

R       <- array(, dim=c(locations, horizon, horizon))
R_null  <- array(, dim=c(locations, horizon, horizon))
R <- R_null
Xe <- Xe_null
Xl <- Xl_null
#
for (t in 1:(horizon-1)) {
  for (tp in (t+1):horizon) {
    for (j in 1:locations)     {
      for (i in 1:locations)      {
        if ((tp-t) ==Travel_time[i,j])
        {
          Xe[i,j,t]=1
          Xl[i,j,t]=1
        }
      }
      R[j,tp,t] = 1
      R[j,tp,t+1] = -1
      Amat <- rbind(Amat, c(as.vector(Xe), as.vector(Xl),as.vector(R)))
      }
  }
}

I try to do this:

Xl = function(ii,jj,tt){1}
t =c(1:horizon)
i =c(1:locations)
j =c(1:locations)
output_Xl = apply(expand.grid(i,j,t),1,function(x,y,h) Xl(x[1],x[2],x[3]))
Xl_new <- array(output_Xl, dim = c(locations, locations, horizon))
Amat <- rbind(Amat, c(as.vector(Xe_null), as.vector(Xl_new)))
dim(Amat) # 1 3072

Body:
You can get the same output with

T <- horizon*locations*locations
Bmat <- cbind(matrix(0, nrow=T, ncol=T), diag(1, nrow=T, ncol=T))
identical(Amat, Bmat)
# TRUE


问:
How do I hide/show a DIV inside a grid ItemTemplate?
I want to set individual DIVs inside a grid visible/hidden programmatically like so, but it isn't working. How would you fix this code?

```<code>            foreach (DataGridItem dgItem in dgW.Items)
            {

                HtmlGenericControl dvGoodRow =
                    (HtmlGenericControl)dgItem.FindControl("dvGoodRow");
                HtmlGenericControl dvBadRow =
                    (HtmlGenericControl)dgItem.FindControl("dvBadRow");

                dvGoodRow.Visible = true;
                dvBadRow.Visible = false;
            }
</code>```

Debug sessions show that the Visible attribute I set above does take effect at least in my watch window, but visually on the browser I see no change. I have a grid like the one below:

```<code><asp:datagrid id="dgW" AutoGenerateColumns="False" ShowHeader="False" ShowFooter="False" runat="server" DataKeyField="SID" CellPadding="0" GridLines="None" AllowSorting="True" OnItemDataBound="dgW_ItemDataBound">
    <HeaderStyle />
    <FooterStyle>
    </FooterStyle>
    <Columns>
        <asp:TemplateColumn HeaderText="SID" SortExpression="SID">
            <ItemTemplate>
                <asp:Label ID="lblSID" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SID") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
            </FooterTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="Extension" SortExpression="ExtensionStopDate">
            <ItemTemplate>
                <asp:Label id="lblExtensionStopDate" Runat="server" text='<%# String.Format("{0:MM/dd/yyyy}", DataBinder.Eval(Container.DataItem, "ExtensionStopDate"))%>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
            </FooterTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn>
            <ItemTemplate>
                <div id="dvGoodRow" runat="server" hidden>
                    <div>
                        <asp:Label runat="server" ID="lblGoodRow">
                            <i id="icnGoodRow" runat="server"></i>
                        </asp:Label>
                    </div>
                </div>
                <div id="dvBadRow" runat="server" hidden>
                    <div>
                        <asp:Label runat="server" ID="lblBadRow">
                            <i id="icnBadRow" runat="server"></i>
                        </asp:Label>
                    </div>
                </div>
            </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:datagrid>
</code>```

答:
Here's what I ended up doing to fix the code: I switched to showing/hiding ASP.NET Panels instead of DIVs!

```<code>            <asp:TemplateColumn>
                <ItemTemplate>
                    <asp:Panel runat="server" ID="pnlGoodRow" Visible="False">
                        <div id="dvGoodRow">
                            <asp:Label runat="server" ID="lblGoodRow">
                                <i id="icnGoodRow" runat="server"></i>
                            </asp:Label>
                        </div>
                    </asp:Panel>
                    <asp:Panel runat="server" ID="pnlBadRow" Visible="False">
                        <div id="dvBadRow">
                            <asp:Label runat="server" ID="lblBadRow">
                                <i id="icnBadRow" runat="server"></i>
                            </asp:Label>
                        </div>
                    </asp:Panel>
                </ItemTemplate>
            </asp:TemplateColumn>
</code>```

So in the code, I now hide/show the Panel elements instead of DIVs:

```<code>        foreach (DataGridItem dgItem in dgW.Items)
        {
            System.Web.UI.WebControls.Panel pnlGoodRow =
                (System.Web.UI.WebControls.Panel)dgItem.FindControl("pnlGoodRow");
            System.Web.UI.WebControls.Panel pnlBadRow =
                (System.Web.UI.WebControls.Panel)dgItem.FindControl("pnlBadRow");

            pnlGoodRow.Visible = true;
            pnlBadRow.Visible = false;
        }
</code>```

This works!

Body:
I want to set individual DIVs inside a grid visible/hidden programmatically like so, but it isn't working. How would you fix this code?

            foreach (DataGridItem dgItem in dgW.Items)
            {

                HtmlGenericControl dvGoodRow =
                    (HtmlGenericControl)dgItem.FindControl("dvGoodRow");
                HtmlGenericControl dvBadRow =
                    (HtmlGenericControl)dgItem.FindControl("dvBadRow");

                dvGoodRow.Visible = true;
                dvBadRow.Visible = false;
            }

Debug sessions show that the Visible attribute I set above does take effect at least in my watch window, but visually on the browser I see no change. I have a grid like the one below:

<asp:datagrid id="dgW" AutoGenerateColumns="False" ShowHeader="False" ShowFooter="False" runat="server" DataKeyField="SID" CellPadding="0" GridLines="None" AllowSorting="True" OnItemDataBound="dgW_ItemDataBound">
    <HeaderStyle />
    <FooterStyle>
    </FooterStyle>
    <Columns>
        <asp:TemplateColumn HeaderText="SID" SortExpression="SID">
            <ItemTemplate>
                <asp:Label ID="lblSID" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SID") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
            </FooterTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="Extension" SortExpression="ExtensionStopDate">
            <ItemTemplate>
                <asp:Label id="lblExtensionStopDate" Runat="server" text='<%# String.Format("{0:MM/dd/yyyy}", DataBinder.Eval(Container.DataItem, "ExtensionStopDate"))%>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
            </FooterTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn>
            <ItemTemplate>

                        <asp:Label runat="server" ID="lblGoodRow">

                        </asp:Label>

                        <asp:Label runat="server" ID="lblBadRow">

                        </asp:Label>

            </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:datagrid>

Body:
Here's what I ended up doing to fix the code: I switched to showing/hiding ASP.NET Panels instead of DIVs!

            <asp:TemplateColumn>
                <ItemTemplate>
                    <asp:Panel runat="server" ID="pnlGoodRow" Visible="False">
                        <div id="dvGoodRow">
                            <asp:Label runat="server" ID="lblGoodRow">
                                <i id="icnGoodRow" runat="server"></i>
                            </asp:Label>
                        </div>
                    </asp:Panel>
                    <asp:Panel runat="server" ID="pnlBadRow" Visible="False">
                        <div id="dvBadRow">
                            <asp:Label runat="server" ID="lblBadRow">
                                <i id="icnBadRow" runat="server"></i>
                            </asp:Label>
                        </div>
                    </asp:Panel>
                </ItemTemplate>
            </asp:TemplateColumn>

So in the code, I now hide/show the Panel elements instead of DIVs:

        foreach (DataGridItem dgItem in dgW.Items)
        {
            System.Web.UI.WebControls.Panel pnlGoodRow =
                (System.Web.UI.WebControls.Panel)dgItem.FindControl("pnlGoodRow");
            System.Web.UI.WebControls.Panel pnlBadRow =
                (System.Web.UI.WebControls.Panel)dgItem.FindControl("pnlBadRow");

            pnlGoodRow.Visible = true;
            pnlBadRow.Visible = false;
        }

This works!


问:
AdWords Scripts. report ORDER BY not working
This function suppose to show in which hours adverts are clicked more often.
It works fine however I have problem with sorting it by "HourOfDay". When I add ORDER BY HourOfDay to the end of the query I get en error.

```<code>function exportReportToSpreadsheet() {
  var spreadsheet = SpreadsheetApp.create('INSERT_REPORT_NAME_HERE');

  var report = AdWordsApp.report("SELECT Clicks, Impressions, AverageCpc, HourOfDay FROM ACCOUNT_PERFORMANCE_REPORT DURING LAST_MONTH ORDER BY HourOfDay");

  report.exportToSheet(spreadsheet.getActiveSheet());
  Logger.log("Report available at " + spreadsheet.getUrl());
 }

exportReportToSpreadsheet();
</code>```

Anyone knows what is wrong with ORDER BY in AdWordsApp.report ?
https://developers.google.com/adwords/scripts/docs/reference/adwordsapp/adwordsapp_report
According to AWQL query language documentation it should work as expected.
https://developers.google.com/adwords/api/docs/guides/awql#using_awql_with_reports

BUG?

答:
You cannot sort reports. From the AWQL documentation:

ORDER BY and LIMIT (sorting and paging) are NOT supported for reports.
  Including these clauses in a query will generate an error.

Ordering is only possible when you use the different entities` selectors, e.g. to iterate over campaigns sorted by cost you could do

```<code>campaignIterator = AdWordsApp
    .campaigns()
    .forDateRange("LAST_MONTH")
    .orderBy("Clicks DESC");
</code>```

Body:
This function suppose to show in which hours adverts are clicked more often.
It works fine however I have problem with sorting it by "HourOfDay". When I add ORDER BY HourOfDay to the end of the query I get en error.

function exportReportToSpreadsheet() {
  var spreadsheet = SpreadsheetApp.create('INSERT_REPORT_NAME_HERE');

  var report = AdWordsApp.report("SELECT Clicks, Impressions, AverageCpc, HourOfDay FROM ACCOUNT_PERFORMANCE_REPORT DURING LAST_MONTH ORDER BY HourOfDay");

  report.exportToSheet(spreadsheet.getActiveSheet());
  Logger.log("Report available at " + spreadsheet.getUrl());
 }

exportReportToSpreadsheet();

Anyone knows what is wrong with ORDER BY in AdWordsApp.report ?
https://developers.google.com/adwords/scripts/docs/reference/adwordsapp/adwordsapp_report
According to AWQL query language documentation it should work as expected.
https://developers.google.com/adwords/api/docs/guides/awql#using_awql_with_reports

BUG?

Body:
You cannot sort reports. From the AWQL documentation:

ORDER BY and LIMIT (sorting and paging) are NOT supported for reports.
  Including these clauses in a query will generate an error.

Ordering is only possible when you use the different entities` selectors, e.g. to iterate over campaigns sorted by cost you could do

campaignIterator = AdWordsApp
    .campaigns()
    .forDateRange("LAST_MONTH")
    .orderBy("Clicks DESC");


问:
Testing (RSpec) with Devise's confirmable module
It's my understanding that Rails' testing environment is torn down and rebuilt before each test...so how do I test a controller that requires that a user be logged in and that user can't be created without Device's confirmable module getting in the way?

Devise's recommended method (below) creates a new user which is then sent an email by Devise's confirmable module. How do I get around this so I'm not 'creating' a user each time...or if I am I can get an object to test w/out "simulating" a new email for each spec?

```<code> before(:each) do
    @user = Factory.create(:user)
    sign_in @user
  end
</code>```

I'm sure I'm overlooking something painfully obvious as this must be a very common spec for anyone using Devise with confirmable...

答:
If you are using factory_girl to generate your models, you can use after_create to confirm each new user.

```<code>Factory.define :confirmed_user, :parent => :user do |f|
  f.after_create { |user| user.confirm! }
end
</code>```

Body:
It's my understanding that Rails' testing environment is torn down and rebuilt before each test...so how do I test a controller that requires that a user be logged in and that user can't be created without Device's confirmable module getting in the way?

Devise's recommended method (below) creates a new user which is then sent an email by Devise's confirmable module. How do I get around this so I'm not 'creating' a user each time...or if I am I can get an object to test w/out "simulating" a new email for each spec?

 before(:each) do
    @user = Factory.create(:user)
    sign_in @user
  end

I'm sure I'm overlooking something painfully obvious as this must be a very common spec for anyone using Devise with confirmable...

Body:
If you are using factory_girl to generate your models, you can use after_create to confirm each new user.

Factory.define :confirmed_user, :parent => :user do |f|
  f.after_create { |user| user.confirm! }
end


问:
how to use multiple query in sql
I want to show count and row table in one query, but when I run this it shows 0 rows and it does not show the count.</p>

```<code>   <?php

   include "connect_db.php";
   $query = "SELECT COUNT(*) AS numberOfRows FROM wp_cf7_data, wp_cf7_data_entry WHERE wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'
   UNION
   SELECT * FROM wp_cf7_data, wp_cf7_data_entry WHERE wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'
   ";

   $result = mysqli_query($conn, $query);

   if (mysqli_num_rows($result) > 0) {
       // output data of each row
       while($row = mysqli_fetch_assoc($result)) {
         echo $row['numberOfRows'];
           echo "id: " . $row["id"]. " - Name: " . $row["cf7_id"]. " " . $row["name"]. "<br>";

       }
   } else {
       echo "0 results";
   }

   mysqli_close($conn);
   ?>
</code>```

答:
Your query seems potentially wrong .. because  could not have the same number of column in the two select you use for union try using a cooresponding number of column sin both the query

```<code>$query = "SELECT COUNT(*) AS numberOfRows
      FROM wp_cf7_data, wp_cf7_data_entry
      WHERE wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'
      UNION
      SELECT count(*)
      FROM wp_cf7_data, wp_cf7_data_entry
      WHERE wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'
</code>```

";

Title: how to use multiple query in sql

Body:
I want to show count and row table in one query, but when I run this it shows 0 rows and it does not show the count.

   <?php

   include "connect_db.php";
   $query = "SELECT COUNT(*) AS numberOfRows FROM wp_cf7_data, wp_cf7_data_entry WHERE wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'
   UNION
   SELECT * FROM wp_cf7_data, wp_cf7_data_entry WHERE wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'
   ";

   $result = mysqli_query($conn, $query);

   if (mysqli_num_rows($result) > 0) {
       // output data of each row
       while($row = mysqli_fetch_assoc($result)) {
         echo $row['numberOfRows'];
           echo "id: " . $row["id"]. " - Name: " . $row["cf7_id"]. " " . $row["name"]. "
";

       }
   } else {
       echo "0 results";
   }

   mysqli_close($conn);
   ?>

Body:
Your query seems potentially wrong .. because  could not have the same number of column in the two select you use for union try using a cooresponding number of column sin both the query

$query = "SELECT COUNT(*) AS numberOfRows
      FROM wp_cf7_data, wp_cf7_data_entry
      WHERE wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'
      UNION
      SELECT count(*)
      FROM wp_cf7_data, wp_cf7_data_entry
      WHERE wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'

";


问:
Is CQRS tied up to Event Sourcing?
I recently read a lot about CQRS and for me it seems like it's closely tied up to Event Sourcing.

But like this answer said https://stackoverflow.com/a/9217461/277067
For me Event SOurcing seems a bit too complicated/scary for a beginners like me ("what ? my object current state is nto stored anywhere ??").

So i'd like to know if indeed they are tied up or if there is any tools/famework that would help for doing cqrs (event observer, command handler) without the complicated part of event sourcing.

Thanks

答:
Short answer: No, CQRS and event-sourcing are not tied to each other.

Long answer: No, CQRS and event-sourcing are not tied to each other, and they aren't tied as well to domain-driven design (DDD).

If you want to define what CQRS, event-sourcing and DDD are in a few words, you may come up with explanations as the following ones (yes of course, they are over-simplified, but that's exactly the point here):

CQRS is a design pattern that separates writing state from reading state (commands vs queries).

Event-sourcing is a way to store data in a database, where the deltas are stored rather than the actual state.

DDD is a method to make communication on the domain easier within interdisciplinary teams.

Each of them works without the others very well. E.g., you can model a domain using DDD, and then implement it without CQRS or event-sourcing. You may also do event-sourcing without ever needing DDD or CQRS. And so on…

But: The three concepts play very well together, which is why they are often called together within a single sentence. So, no they aren't tied to each other, but they make a lot of sense in combination with each other.

The following picture shows how they may interact with each other:

(The image is taken from the documentation of wolkenkit, a CQRS and event-sourcing framework for JavaScript and Node.js.)

CQRS describes that you send commands to the write model, and that you receive events and subscribe to queries from the read model.

Event-sourcing is used with the write model to store the events that are published as result of the commands the client sends.

DDD is used within the write model to turn commands into events and to run the appropriate logic.

Title: Is CQRS tied up to Event Sourcing?


问:
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured
I want to connect MySQL database to my django project, but it is throwing an error :

"django.core.exceptions.ImproperlyConfigured: Requested setting
  USE_I18N, but settings are not configured. You must either define the
  environment variable DJANGO_SETTINGS_MODULE or call
  settings.configure() before accessing settings."

Trace:

```<code> (myenv) LIBINGLADWINs-MacBook-Air:libinrenold$ django-admin dbshell
Traceback (most recent call last):
  File "/Users/libinrenold/Desktop/djangoworks/myenv/bin/django-admin", line 11, in <module>
    sys.exit(execute_from_command_line())
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 322, in execute
    saved_locale = translation.get_language()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 195, in get_language
    return _trans.get_language()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 59, in __getattr__
    if settings.USE_I18N:
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
    self._setup(name)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 39, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
</code>```

settings.py.

```<code>  DATABASES = {
        'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'user',
        'PASSWORD': 'root',
        'HOST':'',
        'PORT': '',
        }
     }
</code>```

答:
put this in top of settings.py
this will configure django for you </p>

```<code>import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", __file__)
import django
django.setup()
</code>```

Body:
I want to connect MySQL database to my django project, but it is throwing an error :

"django.core.exceptions.ImproperlyConfigured: Requested setting
  USE_I18N, but settings are not configured. You must either define the
  environment variable DJANGO_SETTINGS_MODULE or call
  settings.configure() before accessing settings."

Trace:

 (myenv) LIBINGLADWINs-MacBook-Air:libinrenold$ django-admin dbshell
Traceback (most recent call last):
  File "/Users/libinrenold/Desktop/djangoworks/myenv/bin/django-admin", line 11, in <module>
    sys.exit(execute_from_command_line())
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 322, in execute
    saved_locale = translation.get_language()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 195, in get_language
    return _trans.get_language()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 59, in __getattr__
    if settings.USE_I18N:
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
    self._setup(name)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 39, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

settings.py.

  DATABASES = {
        'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'user',
        'PASSWORD': 'root',
        'HOST':'',
        'PORT': '',
        }
     }

Body:
put this in top of settings.py
this will configure django for you

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", __file__)
import django
django.setup()


问:
Writing a list to new excel xlsx with dataframes
I am having some trouble finding the best way to write a list to a loaded excel sheet and then saving the result as an xlsx. What I want my code to do is to take the lists that I have created and put them in specific columns of the loaded workbook. I think there is probably an easier way to do this using dataframes, but I do not know how. Ideally, I would like to save the formatting of the loaded workbook.

```<code>col_test = [1L, 2L, 3L, 4L, 5L]
</code>```

My code is this

```<code>import xlrt
from xlrd import open_workbook
rb = open_workbook("Excel FDT Master_01_update.xlsx")
s = rb.sheet_by_name('INPUT')
r = 5
for test in col_test:
    s.cell(row = r, column = 1).value = test
    r += 1
rb.save('didthiswork.xlsx')
</code>```

答:
That error means that Python could not find a parameter named row in the definition of cell. If I'm not mistaken this is the xlrd module. Let's take a look at the API documentation for Sheet.cell() which you are attempting to call here.

```<code>cell(rowx, colx)
</code>```

Cell object in the given row and column.

It appears that you've simply misnamed the parameters. Changing the line to the following should fix this.

```<code>s.cell(rowx = r, colx = 1).value = test
</code>```

It goes without saying that Python cannot make guesses as to what you meant to type, so whenever you get an error about something not existing when you're sure it does, like the parameter names here, make sure to read the documentation and check for typos. Also, in the future post all relevant info you can find, such as the function definition and the names of the modules you are using.

Body:
I am having some trouble finding the best way to write a list to a loaded excel sheet and then saving the result as an xlsx. What I want my code to do is to take the lists that I have created and put them in specific columns of the loaded workbook. I think there is probably an easier way to do this using dataframes, but I do not know how. Ideally, I would like to save the formatting of the loaded workbook.

col_test = [1L, 2L, 3L, 4L, 5L]

My code is this

import xlrt
from xlrd import open_workbook
rb = open_workbook("Excel FDT Master_01_update.xlsx")
s = rb.sheet_by_name('INPUT')
r = 5
for test in col_test:
    s.cell(row = r, column = 1).value = test
    r += 1
rb.save('didthiswork.xlsx')

Body:
That error means that Python could not find a parameter named row in the definition of cell. If I'm not mistaken this is the xlrd module. Let's take a look at the API documentation for Sheet.cell() which you are attempting to call here.

cell(rowx, colx)

Cell object in the given row and column.

It appears that you've simply misnamed the parameters. Changing the line to the following should fix this.

s.cell(rowx = r, colx = 1).value = test

It goes without saying that Python cannot make guesses as to what you meant to type, so whenever you get an error about something not existing when you're sure it does, like the parameter names here, make sure to read the documentation and check for typos. Also, in the future post all relevant info you can find, such as the function definition and the names of the modules you are using.


问:
How to achieve "Add to desktop" in Google Chrome functionality in command line?
I want to create Google App shortcuts with command line parameter --load-and-launch-app. My intention is to have script which will create app shortcuts for multiple sites.

I have this manifest.json from shortuct to Google Play Music, but if I edit it to my custom page, it's not working. Is there some different command to use, or is it simple not possible currently in Chrome? If so is there a place to add feature request for such command line parameter?

Or does somone know an alternative with full chrome app?

Add to desktop is really great functionality, but it's really painful to create the shortcuts manually (if you need to add it to new pc, etc.)

```<code>{
   "app": {
      "icon_color": "#FF5621",
      "launch": {
         "web_url": "https://play.google.com/music/listen?authuser#/now"
      },
      "linked_icons": [ {
         "size": 16,
         "url": "https://play-music.gstatic.com/fe/c817b6f34e9ba8b2803df9213bccc658/favicon_16x16.png"
      }, {
         "size": 32,
         "url": "https://play-music.gstatic.com/fe/c817b6f34e9ba8b2803df9213bccc658/favicon_32x32.png"
      }, {
         "size": 48,
         "url": "https://play-music.gstatic.com/fe/c817b6f34e9ba8b2803df9213bccc658/favicon_96x96.png"
      }, {
         "size": 64,
         "url": "https://play-music.gstatic.com/fe/c817b6f34e9ba8b2803df9213bccc658/favicon_96x96.png"
      }, {
         "size": 96,
         "url": "https://play-music.gstatic.com/fe/c817b6f34e9ba8b2803df9213bccc658/favicon_96x96.png"
      }, {
         "size": 128,
         "url": "https://play-music.gstatic.com/fe/c817b6f34e9ba8b2803df9213bccc658/favicon_96x96.png"
      }, {
         "size": 256,
         "url": "https://play-music.gstatic.com/fe/c817b6f34e9ba8b2803df9213bccc658/favicon_96x96.png"
      } ]
   },
   "description": "Přístup k více než 35 milionům skladeb na požádání bez reklam. Cokoliv si stáhněte a poslouchejte i bez připojení k síti. Přidejte až 50 000 svých skladeb a poslouchejte je kdekoliv.",
   "icons": {
      "128": "icons/128.png",
      "16": "icons/16.png",
      "256": "icons/256.png",
      "32": "icons/32.png",
      "48": "icons/48.png",
      "64": "icons/64.png",
      "96": "icons/96.png"
   },
   "key": "2HZ3mPKf/kG5Q7oBOeugSfs4rKcBvUy6o+msiKPGJS0=",
   "name": "Google Music",
   "version": "2016.11.11.24057"
}
</code>```

答: As far as I'm aware, you can't. I use an Acer Chromebook 15 and all putting things on the desktop does is remove it from the "shelf" at the bottom.</p>

Body:
I want to create Google App shortcuts with command line parameter --load-and-launch-app. My intention is to have script which will create app shortcuts for multiple sites.

I have this manifest.json from shortuct to Google Play Music, but if I edit it to my custom page, it's not working. Is there some different command to use, or is it simple not possible currently in Chrome? If so is there a place to add feature request for such command line parameter?

Or does somone know an alternative with full chrome app?

Add to desktop is really great functionality, but it's really painful to create the shortcuts manually (if you need to add it to new pc, etc.)

{
   "app": {
      "icon_color": "#FF5621",
      "launch": {
         "web_url": "https://play.google.com/music/listen?authuser#/now"
      },
      "linked_icons": [ {
         "size": 16,
         "url": "https://play-music.gstatic.com/fe/c817b6f34e9ba8b2803df9213bccc658/favicon_16x16.png"
      }, {
         "size": 32,
         "url": "https://play-music.gstatic.com/fe/c817b6f34e9ba8b2803df9213bccc658/favicon_32x32.png"
      }, {
         "size": 48,
         "url": "https://play-music.gstatic.com/fe/c817b6f34e9ba8b2803df9213bccc658/favicon_96x96.png"
      }, {
         "size": 64,
         "url": "https://play-music.gstatic.com/fe/c817b6f34e9ba8b2803df9213bccc658/favicon_96x96.png"
      }, {
         "size": 96,
         "url": "https://play-music.gstatic.com/fe/c817b6f34e9ba8b2803df9213bccc658/favicon_96x96.png"
      }, {
         "size": 128,
         "url": "https://play-music.gstatic.com/fe/c817b6f34e9ba8b2803df9213bccc658/favicon_96x96.png"
      }, {
         "size": 256,
         "url": "https://play-music.gstatic.com/fe/c817b6f34e9ba8b2803df9213bccc658/favicon_96x96.png"
      } ]
   },
   "description": "Přístup k více než 35 milionům skladeb na požádání bez reklam. Cokoliv si stáhněte a poslouchejte i bez připojení k síti. Přidejte až 50 000 svých skladeb a poslouchejte je kdekoliv.",
   "icons": {
      "128": "icons/128.png",
      "16": "icons/16.png",
      "256": "icons/256.png",
      "32": "icons/32.png",
      "48": "icons/48.png",
      "64": "icons/64.png",
      "96": "icons/96.png"
   },
   "key": "2HZ3mPKf/kG5Q7oBOeugSfs4rKcBvUy6o+msiKPGJS0=",
   "name": "Google Music",
   "version": "2016.11.11.24057"
}


问:
Excel data into grid
I was just wondering if there is a way to paste data from a excel table into a grid in extjs (sencha). Maybe with the ctrl + v option or a way to load the data from the excel too.

Thanks guys.

答: You can use the XSLX.js library to read and write XSLX files, and map the resulting javascript objects to records for your grids. However, I am not sure how to combine that external library with Sencha Architect.</p>

Title: Excel data into grid


问:
null pointer to canvas.drawPath()
So I am just trying to create a simple draw view where a user can draw on the screen. However after hours of research I still seem to be having trouble solving why, when I call canvas.drawPath() in my onDraw() method, the app crashes. (I have omitted touch methods here)

```<code>public class DrawTing extends View{

private Bitmap bm;
private Canvas canv;
private Path path;
Context context;
private Paint paint1;
private Paint paint;

public DrawTing(Context c) {
    super(c);
    this.context = c;
}

public DrawTing(Context c, AttributeSet attrs) {
    super(c, attrs);
    this.context = c;
}

public DrawTing(Context c, AttributeSet attrs, int defStyle) {
    super(c, attrs, defStyle);
    this.context = c;

    path = new Path();

    paint = new Paint();
    paint.setDither(true);
    paint.setAntiAlias(true);
    paint.setColor(Color.GREEN);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeJoin(Paint.Join.ROUND);
    paint.setStrokeWidth(10f);

}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    canv = new Canvas(bm);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawPath(path, paint);      //NPE here

    //Things I have tried along with canvas.drawPath()

    //canvas = this.canv
    //canvas = canv;
    //canvas = new Canvas();
    //canvas.drawRect(0,0, getWidth(), getHeight(), paint);
    //canvas.drawColor(0xFFAAAAAA);
    //canvas.drawBitmap(bm,0,0, paint);

}
</code>```

My logcat is displaying this error message:

```<code> FATAL EXCEPTION: main
                                                              Process:
 com.ting.cian.ting, PID: 7989

 java.lang.NullPointerException: Attempt to read from field 'boolean
 android.graphics.Path.isSimplePath' on a null object reference
                                                                  at
 android.graphics.BaseCanvas.drawPath(BaseCanvas.java:295)
                                                                  at
 android.graphics.Canvas.drawPath(Canvas.java:1652)
                                                                  at
 com.ting.cian.ting.DrawTing.onDraw(DrawTing.java:124)
                                                                  at
 android.view.View.draw(View.java:19119)
                                                                  at
 android.view.View.updateDisplayListIfDirty(View.java:18069)
                                                                  at
 android.view.View.draw(View.java:18847)
                                                                  at
 android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                  at
 android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                  at
 android.view.View.updateDisplayListIfDirty(View.java:18060)
                                                                  at
 android.view.View.draw(View.java:18847)
 ...
</code>```

Thanks for your time!

答:
You are creating only in the third constructor a path and paint object. The two other constructors do not initialize the path and paint variables.
Depending on which constructor is used this results in a NullPointerException.

To solve this, add

```<code>path = new Path();

paint = new Paint();
paint.setDither(true);
paint.setAntiAlias(true);
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(10f);
</code>```

to the other constructors as well.

Title: null pointer to canvas.drawPath()

Body:
So I am just trying to create a simple draw view where a user can draw on the screen. However after hours of research I still seem to be having trouble solving why, when I call canvas.drawPath() in my onDraw() method, the app crashes. (I have omitted touch methods here)

public class DrawTing extends View{

private Bitmap bm;
private Canvas canv;
private Path path;
Context context;
private Paint paint1;
private Paint paint;

public DrawTing(Context c) {
    super(c);
    this.context = c;
}

public DrawTing(Context c, AttributeSet attrs) {
    super(c, attrs);
    this.context = c;
}

public DrawTing(Context c, AttributeSet attrs, int defStyle) {
    super(c, attrs, defStyle);
    this.context = c;

    path = new Path();

    paint = new Paint();
    paint.setDither(true);
    paint.setAntiAlias(true);
    paint.setColor(Color.GREEN);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeJoin(Paint.Join.ROUND);
    paint.setStrokeWidth(10f);

}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    canv = new Canvas(bm);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawPath(path, paint);      //NPE here

    //Things I have tried along with canvas.drawPath()

    //canvas = this.canv
    //canvas = canv;
    //canvas = new Canvas();
    //canvas.drawRect(0,0, getWidth(), getHeight(), paint);
    //canvas.drawColor(0xFFAAAAAA);
    //canvas.drawBitmap(bm,0,0, paint);

}

My logcat is displaying this error message:

 FATAL EXCEPTION: main
                                                              Process:
 com.ting.cian.ting, PID: 7989

 java.lang.NullPointerException: Attempt to read from field 'boolean
 android.graphics.Path.isSimplePath' on a null object reference
                                                                  at
 android.graphics.BaseCanvas.drawPath(BaseCanvas.java:295)
                                                                  at
 android.graphics.Canvas.drawPath(Canvas.java:1652)
                                                                  at
 com.ting.cian.ting.DrawTing.onDraw(DrawTing.java:124)
                                                                  at
 android.view.View.draw(View.java:19119)
                                                                  at
 android.view.View.updateDisplayListIfDirty(View.java:18069)
                                                                  at
 android.view.View.draw(View.java:18847)
                                                                  at
 android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                  at
 android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                  at
 android.view.View.updateDisplayListIfDirty(View.java:18060)
                                                                  at
 android.view.View.draw(View.java:18847)
 ...

Thanks for your time!

Body:
You are creating only in the third constructor a path and paint object. The two other constructors do not initialize the path and paint variables.
Depending on which constructor is used this results in a NullPointerException.

To solve this, add

path = new Path();

paint = new Paint();
paint.setDither(true);
paint.setAntiAlias(true);
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(10f);

to the other constructors as well.


问:
Table-like image grid in CSS (but with a twist)
I want to create a table-like image grid. Each thumbnail image (size and orientation vary) is meant to sit centered in it's own DIV. Each row should contain four images, after that I want an automatic "line break" to happen, caused by the size of the enclosing TD, with the result looking like this:

XXXX

XXXX

XX

The code below works as intended in Firefox, Opera, Safari, Chrome. But in Internet Explorer 7/8/9 I run into two problems:

1) Images are not vertically centered, they sit at the top of the DIV.

2) The "line break" does not happen. The row of images disappears out of sight to the right...

CSS:

```<code>.outer-div {display: inline; float:left; clear:right;}

.inner-div
{
width: 220px;
height: 220px;
display: table-cell;
vertical-align: middle;
}
</code>```

HTML:

```<code><div class="outer-div"><div class="inner-div">img.jpg</div></div>
</code>```

答:
You could add this to the .inner-div CSS:

```<code>*display:inline;
zoom:1;
</code>```

I think what's happening is IE doesn't recognize the display:table-cell, so you need to use a hack (or some other method of telling only IE to use display:inline with zoom:1).

Body:
I want to create a table-like image grid. Each thumbnail image (size and orientation vary) is meant to sit centered in it's own DIV. Each row should contain four images, after that I want an automatic "line break" to happen, caused by the size of the enclosing TD, with the result looking like this:

XXXX

XXXX

XX

The code below works as intended in Firefox, Opera, Safari, Chrome. But in Internet Explorer 7/8/9 I run into two problems:

1) Images are not vertically centered, they sit at the top of the DIV.

2) The "line break" does not happen. The row of images disappears out of sight to the right...

CSS:

.outer-div {display: inline; float:left; clear:right;}

.inner-div
{
width: 220px;
height: 220px;
display: table-cell;
vertical-align: middle;
}

HTML:

img.jpg

Body:
You could add this to the .inner-div CSS:

*display:inline;
zoom:1;

I think what's happening is IE doesn't recognize the display:table-cell, so you need to use a hack (or some other method of telling only IE to use display:inline with zoom:1).