问:
Deleting Blobs from azure storage mvc
When trying to delete, or copy a blob from my Azure storage, after successfully uploading it, I get the following 404 error. I cannot see why it is not finding the blob from my storage system, due to successfull upload and successfull downloading. Here is my code to delete that does not work;
I tried setting the "            CloudBlockBlob blob = container.GetBlockBlobReference(path);
" to a file I knew was there "2020Resume.pdf" and it still didnt work

```<code>// GET: DocumentUps/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            DocumentUps documentUps = db.DocumentUps.Find(id);
            Distributee distributees = db.Distributees.Find(id);
            if (documentUps == null)
            {
                return HttpNotFound();
            }
            return View(documentUps);
        }

        // POST: DocumentUps/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        DocumentUps documentUps = db.DocumentUps.Find(id);
        Distributee distributees = db.Distributees.Find(id);

        string attachmnt = documentUps.Attachment.ToString();
        if (attachmnt.Contains('.'))
            attachmnt = attachmnt.Substring(0, attachmnt.LastIndexOf('.'));

        var fileName = documentUps.DocumentId.ToString() + documentUps.RevisionId.ToString() + attachmnt;

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("filestorageideagen_AzureStorageConnectionString"));
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("documentuploader");
        CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
        blob.Delete();

        if (distributees != null)
        {
            db.Distributees.Remove(distributees);
        }
        db.DocumentUps.Remove(documentUps);
        db.SaveChanges();

        return RedirectToAction("Index");
    }
</code>```

The error

```<code>Server Error in '/' Application.

The remote server returned an error: (404) Not Found.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (404) Not Found.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[WebException: The remote server returned an error: (404) Not Found.]
   System.Net.HttpWebRequest.GetResponse() +1399
   Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync(RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) +1150

[StorageException: The remote server returned an error: (404) Not Found.]
   Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync(RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) +4559
   Microsoft.WindowsAzure.Storage.Blob.CloudBlob.Delete(DeleteSnapshotsOption deleteSnapshotsOption, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) +62
   Integrated_Project.Controllers.MyDocumentUpsController.DeleteConfirmed(Int32 id) +336
   lambda_method(Closure , ControllerBase , Object[] ) +97
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9765121
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</code>```

答: Turns out the error was in the database query, my revision ID was being changed to 0 and some point and was not searching for the correct file</p>

Title: Deleting Blobs from azure storage mvc

Body:
When trying to delete, or copy a blob from my Azure storage, after successfully uploading it, I get the following 404 error. I cannot see why it is not finding the blob from my storage system, due to successfull upload and successfull downloading. Here is my code to delete that does not work;
I tried setting the "            CloudBlockBlob blob = container.GetBlockBlobReference(path);
" to a file I knew was there "2020Resume.pdf" and it still didnt work

// GET: DocumentUps/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            DocumentUps documentUps = db.DocumentUps.Find(id);
            Distributee distributees = db.Distributees.Find(id);
            if (documentUps == null)
            {
                return HttpNotFound();
            }
            return View(documentUps);
        }

        // POST: DocumentUps/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        DocumentUps documentUps = db.DocumentUps.Find(id);
        Distributee distributees = db.Distributees.Find(id);

        string attachmnt = documentUps.Attachment.ToString();
        if (attachmnt.Contains('.'))
            attachmnt = attachmnt.Substring(0, attachmnt.LastIndexOf('.'));

        var fileName = documentUps.DocumentId.ToString() + documentUps.RevisionId.ToString() + attachmnt;

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("filestorageideagen_AzureStorageConnectionString"));
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("documentuploader");
        CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
        blob.Delete();

        if (distributees != null)
        {
            db.Distributees.Remove(distributees);
        }
        db.DocumentUps.Remove(documentUps);
        db.SaveChanges();

        return RedirectToAction("Index");
    }

The error

Server Error in '/' Application.

The remote server returned an error: (404) Not Found.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (404) Not Found.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[WebException: The remote server returned an error: (404) Not Found.]
   System.Net.HttpWebRequest.GetResponse() +1399
   Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync(RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) +1150

[StorageException: The remote server returned an error: (404) Not Found.]
   Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync(RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) +4559
   Microsoft.WindowsAzure.Storage.Blob.CloudBlob.Delete(DeleteSnapshotsOption deleteSnapshotsOption, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) +62
   Integrated_Project.Controllers.MyDocumentUpsController.DeleteConfirmed(Int32 id) +336
   lambda_method(Closure , ControllerBase , Object[] ) +97
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9765121
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155


来源: stackexchange

问:
Assign a particular ID to each item in a list and generate a new list with repeated IDs
I have 2 lists, each have 5 items in them. But the items in the 'start' list are lists:

```<code>start = [[3606,5599,6312,7897], [2394], [84,1046], [1046], [1]]

id = ['AB022430', 'AB024537', 'AB043103', 'AB051349', 'AB051628']
</code>```

I would like to created a new list with the format (I'm thinking via a pandas df or using 'zip'):

```<code>AB022430    3606
AB022430    5559
AB022430    6312
AB022430    7897
AB024537    2394
etc..
</code>```

I essentially want repeating IDs.

答:
I'd suggest you do

```<code>from itertools import chain

start = [[3606,5599,6312,7897], [2394], [84,1046], [1046], [1]]
id = ['AB022430', 'AB024537', 'AB043103', 'AB051349', 'AB051628']

chained_start = chain(*start) # Unpack the list and use
# chain to "chain" the sub lists into a new one

ziped_info = zip(id, start) # Zip the lists together
</code>```

Or in one line:

```<code>ziped_info = zip(id, chain(*start))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have 2 lists, each have 5 items in them. But the items in the 'start' list are lists:

start = [[3606,5599,6312,7897], [2394], [84,1046], [1046], [1]]

id = ['AB022430', 'AB024537', 'AB043103', 'AB051349', 'AB051628']

I would like to created a new list with the format (I'm thinking via a pandas df or using 'zip'):

AB022430    3606
AB022430    5559
AB022430    6312
AB022430    7897
AB024537    2394
etc..

I essentially want repeating IDs.

Body:
I'd suggest you do

from itertools import chain

start = [[3606,5599,6312,7897], [2394], [84,1046], [1046], [1]]
id = ['AB022430', 'AB024537', 'AB043103', 'AB051349', 'AB051628']

chained_start = chain(*start) # Unpack the list and use
# chain to "chain" the sub lists into a new one

ziped_info = zip(id, start) # Zip the lists together

Or in one line:

ziped_info = zip(id, chain(*start))


问:
Summernote image upload not working in codeigniter
I have integrated summernote in my website (built with Codeigniter) and for texts it is working fine. But for image upload, there arises the following problem.

Summernote reads the image as base64. Now this works perfectly fine for small images, but once images are large, the image finally does not render due to the huge string created by the base64 in the database.

So I am trying to save the image in my server and then use the link of that image.

Following are the codes:
Script for summernote:

```<code><script type="text/javascript">
$(document).ready(function() {
  $('#summernote').summernote({
    height: 300,
    onImageUpload: function(files) {
            sendFile(files[0]);
        }
  });
  function sendFile(file) {
        data = new FormData();
        data.append("files", file);
        upload_url = "<?php echo base_url(); ?>" + "general/upload_image";
        $.ajax({
            data: data,
            type: "POST",
            url: upload_url,
            cache: false,
            contentType: false,
            processData: false,
            success: function(url) {
                 $(this).summernote("insertImage", url);

            }
        });
    }
});
</code>```

the php upload_image function:

```<code>public function upload_image()
{
    if ($_FILES['file']['name']) {
        if (!$_FILES['file']['error']) {
            $name = md5(rand(100, 200));
            $ext = explode('.', $_FILES['file']['name']);
            $filename = $name . '.' . $ext[1];
            $destination = 'http://sitename.com/dist/img/blogimg/' . $filename; //change this directory
            $location = $_FILES["file"]["tmp_name"];
            move_uploaded_file($location, $destination);
            echo 'http://sitename.com/dist/img/blogimg/' . $filename;//change this URL
        }
        else
        {
            echo  $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
        }
    }
}
</code>```

now, when I click on insert image in summernote or drag and drop an image multiple instances of the following error is shown in the console:

```<code>>Uncaught TypeError: Cannot read property 'nodeType' of undefined
</code>```

This is what I want to achieve,
N.B. This editor is for a blog.
1. User clicks on insert image and uploads an image from his computer.
2. the image is shown in the editor (but not uploaded to server at this step).
3. When user clicks on submit button, then the image should be saved as an image file in a predefined folder.
4. When the page renders the it should have

```<code><img src="mysite.com/path_to_image">
</code>```

now it is something like

```<code><img src="data:image/jpeg;base64,/9j/4AAQSkZJR....">)
</code>```

Please note, I tried using onImageUpload within callbacks but the result was nothing was actually happening, neither the image was geting uploaded to the editor nor to the folder in the server.

Where am I going wrong....?? Please help me fix this...

答:
Okay, although I could not find a solution to my problem, I have implemented an alternation solution and it works perfectly, although pt. 3 is not catered to and the image is uploaded to the server in an earlier step. That too can be catered with some js scripts...Will do that later... What I did is I targeted the summernote ids and classes and added my codes in place of theirs...

I removed their upload image field by this code:

```
</div>
</div>
</p>

<p>Next I inserted my HTML below their insert link field this way:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.getElementsByClassName('note-group-image-url')[0].insertAdjacentHTML('afterend','<p class="sober"><p>Click here to upoad image</p></i></p>');</code>```

Next I handled the image upload through a modal and wrote a custom js script that copied the image url to the field of .note-image-url

Also I had to customise the javascript of the insert image button of summernote with js so that users can directly click on insert image.

Body:
Okay, although I could not find a solution to my problem, I have implemented an alternation solution and it works perfectly, although pt. 3 is not catered to and the image is uploaded to the server in an earlier step. That too can be catered with some js scripts...Will do that later... What I did is I targeted the summernote ids and classes and added my codes in place of theirs...

I removed their upload image field by this code:

<style>
/*to disable the upload image from computer uncomment this css code.*/
 .note-group-select-from-files {
  display: none;
}

</style>

Next I inserted my HTML below their insert link field this way:

document.getElementsByClassName('note-group-image-url')[0].insertAdjacentHTML('afterend','<p class="sober"><a href="#" data-toggle="modal" data-target="#imageModal"><p>Click here to upoad image</p></i></a></p>');

Next I handled the image upload through a modal and wrote a custom js script that copied the image url to the field of .note-image-url

Also I had to customise the javascript of the insert image button of summernote with js so that users can directly click on insert image.


问:
how to get marker position in jvm map
I am using jvm plugin for map and I have created a labelbox for it. But When I click the marker, it shows labelbox far away. So I need a way to get position of marker (x, y) so the labelbox can be positioned at correct place.
Thanks</p>

答:
Let say you have correctly initialized a map inside a container div called "map", and ypu can get it:

```<code>var mapObj = $('#map').vectorMap('get','mapObject');
</code>```

I assume you have created your custom "labelbox" outside the map, so you can try to get the position of a marker element as follows:

Inside the onMarkerClick handler use the code of the marker:

```<code>var style = mapObj.markers[code].element.shape.style.current;
var x = style.cx;
var y = style.cy;
</code>```

Up to you to add some custom logic to keep your custom "labelbox" fully inside the map, if needed.

Title: how to get marker position in jvm map

Body:
Let say you have correctly initialized a map inside a container div called "map", and ypu can get it:

var mapObj = $('#map').vectorMap('get','mapObject');

I assume you have created your custom "labelbox" outside the map, so you can try to get the position of a marker element as follows:

Inside the onMarkerClick handler use the code of the marker:

var style = mapObj.markers[code].element.shape.style.current;
var x = style.cx;
var y = style.cy;

Up to you to add some custom logic to keep your custom "labelbox" fully inside the map, if needed.


问:
How to name optionmenu boxes in a for loop
At the moment each option menu box replaces the previous one so if write ent1.get() i dont get the value within any box, how can i distinguish betweeen each optionmenu and therefor retrieve each value distinctly? Ideally calling them all by a different name decided by their position in the grid.</p>

```<code>  for x in range (xval):#creating the matrix
        for y in range (yval):
            variable = StringVar(root)
            ent1 = OptionMenu(root, variable, *inputvalues)#creating the dropdown menus
            ent1.config(width=3)
            ent1.grid(row=(y+1), column=x)
</code>```

答:
Not sure if I understand correctly but if you are trying to create different StringVar's in a single loop, you could use the variable.format() method to make sure each StringVar is saved as a unique variable.

Thus the following loop will create StringVar's that are saved into variables ent1, ent2, ent3, etc. This will allow you to call them separately later on..

```<code>for x in range (xval):#creating the matrix
        for y in range (yval):
            variable = StringVar(root)
            ent["ent{0}"].format(y+1) = OptionMenu(root, variable, *inputvalues)#creating the dropdown menus
            ent["ent{0}"].format(y+1).config(width=3)
            ent["ent{0}"].format(y+1).grid(row=(y+1), column=x)
</code>```

Body:
At the moment each option menu box replaces the previous one so if write ent1.get() i dont get the value within any box, how can i distinguish betweeen each optionmenu and therefor retrieve each value distinctly? Ideally calling them all by a different name decided by their position in the grid.

  for x in range (xval):#creating the matrix
        for y in range (yval):
            variable = StringVar(root)
            ent1 = OptionMenu(root, variable, *inputvalues)#creating the dropdown menus
            ent1.config(width=3)
            ent1.grid(row=(y+1), column=x)

Body:
Not sure if I understand correctly but if you are trying to create different StringVar's in a single loop, you could use the variable.format() method to make sure each StringVar is saved as a unique variable.

Thus the following loop will create StringVar's that are saved into variables ent1, ent2, ent3, etc. This will allow you to call them separately later on..

for x in range (xval):#creating the matrix
        for y in range (yval):
            variable = StringVar(root)
            ent["ent{0}"].format(y+1) = OptionMenu(root, variable, *inputvalues)#creating the dropdown menus
            ent["ent{0}"].format(y+1).config(width=3)
            ent["ent{0}"].format(y+1).grid(row=(y+1), column=x)


问:
How to know which version of Microsoft Office a particular Add-in project targets?
If I have a VSTO project open in Visual Studio, how do I know which version of MS Office it targets?

Is it possible to change or broaden the scope of versions of MS Office that the project targets?

I am using Visual Studio 2013 Professional.

答: There's no place in the project that explicitly says something like "Office 2010", I think you just have to look at the references. 14 means 2010, 15 is 2013, and 16 is 2016 iirc. You can swap out references to change the target version, by picking them from a different directory.</p>


问:
Delete from one table unless row is referenced in another table
We have two tables, that look something like this:

```<code>CREATE TABLE devices(
    "id" serial NOT NULL PRIMARY KEY,
    "name" varchar(255) NOT NULL,
    "last_log_id" integer NULL
);

CREATE TABLE log(
    "id" serial NOT NULL PRIMARY KEY,
    "created_at" timestamp with time zone NOT NULL,
    "msg" varchar(255) NOT NULL,
);

ALTER TABLE "devices" ADD CONSTRAINT
   "device_last_log_id" FOREIGN KEY ("last_log_id")
   REFERENCES "log" ("id") DEFERRABLE INITIALLY DEFERRED;
</code>```

What is an efficient query to delete all "log" rows older than a certain "created_at" date, unless they are referenced by the "devices" table "last_log_id" column?

答:
```<code>delete from log l
where l.created_at < 'somedate'
and not exists (select 1
     from devices d
     where d.last_log_id = l.id
    );
</code>```

Body:
We have two tables, that look something like this:

CREATE TABLE devices(
    "id" serial NOT NULL PRIMARY KEY,
    "name" varchar(255) NOT NULL,
    "last_log_id" integer NULL
);

CREATE TABLE log(
    "id" serial NOT NULL PRIMARY KEY,
    "created_at" timestamp with time zone NOT NULL,
    "msg" varchar(255) NOT NULL,
);

ALTER TABLE "devices" ADD CONSTRAINT
   "device_last_log_id" FOREIGN KEY ("last_log_id")
   REFERENCES "log" ("id") DEFERRABLE INITIALLY DEFERRED;

What is an efficient query to delete all "log" rows older than a certain "created_at" date, unless they are referenced by the "devices" table "last_log_id" column?


问:
Retrieve values from two separate sheets in Excel
I send an email to a list of people. The email is generated by copying a range from one Excel sheet into the body of the email. This works fine.

All the code is below. The sheet that the body of the mail is selected from is called 'UKX Trade". I want to retrieve the email address data from a separate sheet called "Mailinfo". How can I adjust the code for this to work?

```<code>Sub ZC_Collar()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Don't forget to copy the function RangetoHTML in the module.
'Working in Excel 2000-2016
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim cell As Range
Dim StrBody As String

Set rng = Nothing
On Error Resume Next
'Only the visible cells in the selection
Set rng = Selection.SpecialCells(xlCellTypeVisible)
'You can also use a fixed range if you want
Set rng = Range("ZCCollar").SpecialCells(xlCellTypeVisible)

On Error GoTo 0

If rng Is Nothing Then
    MsgBox "The selection is not a range or the sheet is protected" & _
           vbNewLine & "please correct and try again.", vbOKOnly
    Exit Sub
End If

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

 StrBody = Sheets("UKX Trade").Range("body_line1").Value & "<br><br>" & _
          Sheets("UKX Trade").Range("body_line2").Value & "<br>" & _
          Sheets("UKX Trade").Range("body_line3").Value

Set OutApp = CreateObject("Outlook.Application")

On Error Resume Next
For Each cell In Columns("P").Cells.SpecialCells(xlCellTypeConstants)
    If cell.Value Like "?*@?*.?*" And _
        LCase(Cells(cell.Row, "Q").Value) = "yes" Then

        Set OutMail = OutApp.CreateItem(0)
        On Error Resume Next
        With OutMail
            .To = cell.Value
            .Subject = "Index Option RFQ"
            .CC = Range("cc_email").Value

            .HTMLBody = StrBody & RangetoHTML(rng) & "<br>" & "Thanks"

            'You can add files also like this
            '.Attachments.Add ("C:\test.txt")
            .Display  'Or use Send
        End With
        On Error GoTo 0
        Set OutMail = Nothing
    End If
Next cell

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub

Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook

TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
    .Cells(1).PasteSpecial Paste:=8
    .Cells(1).PasteSpecial xlPasteValues, , False, False
    .Cells(1).PasteSpecial xlPasteFormats, , False, False
    .Cells(1).Select
    Application.CutCopyMode = False
    On Error Resume Next
    .DrawingObjects.Visible = True
    .DrawingObjects.Delete
    On Error GoTo 0
End With

'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
     SourceType:=xlSourceRange, _
     Filename:=TempFile, _
     Sheet:=TempWB.Sheets(1).Name, _
     Source:=TempWB.Sheets(1).UsedRange.Address, _
     HtmlType:=xlHtmlStatic)
    .Publish (True)
End With

'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                      "align=left x:publishsource=")

'Close TempWB
TempWB.Close savechanges:=False

'Delete the htm file we used in this function
Kill TempFile

Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
</code>```

答:
You just need to specify where cell is in this line:

```<code>For Each cell In Columns("P").Cells.SpecialCells(xlCellTypeConstants)
' ... add contacts code
Next cell
</code>```

Do this by:

```<code>For Each cell In ThisWorkbook.Sheets("Mailinfo").Columns("P").Cells.SpecialCells(xlCellTypeConstants)
' ... add contacts code
Next cell
</code>```

This is called fully qualifying an object in VBA.

Edit

So here is your sub, but with things fully qualified. You'll notice that the code you got from Ron de Bruin (RangetoHTML) was already fully qualified. Put this in a module not a sheet.

```<code>Sub ZC_Collar()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim cell As Range
Dim StrBody As String

Set rng = Nothing
On Error Resume Next
' Remove this next line, it doesn't do anything because you set rng again anyway
' Set rng = Selection.SpecialCells(xlCellTypeVisible)
' only visible cells in ZCCollar range, specifying the sheet (put the correct sheet in)
Set rng = ThisWorkbook.Sheets("UKX Trade").Range("ZCCollar").SpecialCells(xlCellTypeVisible)
On Error GoTo 0

If rng Is Nothing Then
    MsgBox "The selection is not a range or the sheet is protected" & vbNewLine & "please correct and try again.", vbOKOnly
    Exit Sub
End If

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

With ThisWorkbook.Sheets("UKX Trade")
    StrBody = .Range("body_line1").Value & "<br><br>" & _
              .Range("body_line2").Value & "<br>" & _
              .Range("body_line3").Value
End With

Set OutApp = CreateObject("Outlook.Application")

On Error Resume Next
For Each cell In ThisWorkbook.Sheets("Mailinfo").Columns("P").Cells.SpecialCells(xlCellTypeConstants)
    If cell.Value Like "?*@?*.?*" And LCase(ThisWorkbook.Sheets("Mailinfo").Cells(cell.Row, "Q").Value) = "yes" Then

        Set OutMail = OutApp.CreateItem(0)
        On Error Resume Next
        With OutMail
            .To = cell.Value
            .Subject = "Index Option RFQ"
            .CC = ThisWorkbook.Sheets("Mailinfo").Range("cc_email").Value
            .HTMLBody = StrBody & RangetoHTML(rng) & "<br>" & "Thanks"
            .Display  'Or use Send to send each email without displaying it first
        End With
        Set OutMail = Nothing
    End If
Next cell
On Error GoTo 0

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub
</code>```

Body:
I send an email to a list of people. The email is generated by copying a range from one Excel sheet into the body of the email. This works fine.

All the code is below. The sheet that the body of the mail is selected from is called 'UKX Trade". I want to retrieve the email address data from a separate sheet called "Mailinfo". How can I adjust the code for this to work?

Sub ZC_Collar()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Don't forget to copy the function RangetoHTML in the module.
'Working in Excel 2000-2016
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim cell As Range
Dim StrBody As String

Set rng = Nothing
On Error Resume Next
'Only the visible cells in the selection
Set rng = Selection.SpecialCells(xlCellTypeVisible)
'You can also use a fixed range if you want
Set rng = Range("ZCCollar").SpecialCells(xlCellTypeVisible)

On Error GoTo 0

If rng Is Nothing Then
    MsgBox "The selection is not a range or the sheet is protected" & _
           vbNewLine & "please correct and try again.", vbOKOnly
    Exit Sub
End If

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

 StrBody = Sheets("UKX Trade").Range("body_line1").Value & "

" & _
          Sheets("UKX Trade").Range("body_line2").Value & "
" & _
          Sheets("UKX Trade").Range("body_line3").Value

Set OutApp = CreateObject("Outlook.Application")

On Error Resume Next
For Each cell In Columns("P").Cells.SpecialCells(xlCellTypeConstants)
    If cell.Value Like "?*@?*.?*" And _
        LCase(Cells(cell.Row, "Q").Value) = "yes" Then

        Set OutMail = OutApp.CreateItem(0)
        On Error Resume Next
        With OutMail
            .To = cell.Value
            .Subject = "Index Option RFQ"
            .CC = Range("cc_email").Value

            .HTMLBody = StrBody & RangetoHTML(rng) & "
" & "Thanks"

            'You can add files also like this
            '.Attachments.Add ("C:\test.txt")
            .Display  'Or use Send
        End With
        On Error GoTo 0
        Set OutMail = Nothing
    End If
Next cell

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub

Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook

TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
    .Cells(1).PasteSpecial Paste:=8
    .Cells(1).PasteSpecial xlPasteValues, , False, False
    .Cells(1).PasteSpecial xlPasteFormats, , False, False
    .Cells(1).Select
    Application.CutCopyMode = False
    On Error Resume Next
    .DrawingObjects.Visible = True
    .DrawingObjects.Delete
    On Error GoTo 0
End With

'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
     SourceType:=xlSourceRange, _
     Filename:=TempFile, _
     Sheet:=TempWB.Sheets(1).Name, _
     Source:=TempWB.Sheets(1).UsedRange.Address, _
     HtmlType:=xlHtmlStatic)
    .Publish (True)
End With

'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                      "align=left x:publishsource=")

'Close TempWB
TempWB.Close savechanges:=False

'Delete the htm file we used in this function
Kill TempFile

Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function

Body:
You just need to specify where cell is in this line:

For Each cell In Columns("P").Cells.SpecialCells(xlCellTypeConstants)
' ... add contacts code
Next cell

Do this by:

For Each cell In ThisWorkbook.Sheets("Mailinfo").Columns("P").Cells.SpecialCells(xlCellTypeConstants)
' ... add contacts code
Next cell

This is called fully qualifying an object in VBA.

Edit

So here is your sub, but with things fully qualified. You'll notice that the code you got from Ron de Bruin (RangetoHTML) was already fully qualified. Put this in a module not a sheet.

Sub ZC_Collar()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim cell As Range
Dim StrBody As String

Set rng = Nothing
On Error Resume Next
' Remove this next line, it doesn't do anything because you set rng again anyway
' Set rng = Selection.SpecialCells(xlCellTypeVisible)
' only visible cells in ZCCollar range, specifying the sheet (put the correct sheet in)
Set rng = ThisWorkbook.Sheets("UKX Trade").Range("ZCCollar").SpecialCells(xlCellTypeVisible)
On Error GoTo 0

If rng Is Nothing Then
    MsgBox "The selection is not a range or the sheet is protected" & vbNewLine & "please correct and try again.", vbOKOnly
    Exit Sub
End If

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

With ThisWorkbook.Sheets("UKX Trade")
    StrBody = .Range("body_line1").Value & "<br><br>" & _
              .Range("body_line2").Value & "<br>" & _
              .Range("body_line3").Value
End With

Set OutApp = CreateObject("Outlook.Application")

On Error Resume Next
For Each cell In ThisWorkbook.Sheets("Mailinfo").Columns("P").Cells.SpecialCells(xlCellTypeConstants)
    If cell.Value Like "?*@?*.?*" And LCase(ThisWorkbook.Sheets("Mailinfo").Cells(cell.Row, "Q").Value) = "yes" Then

        Set OutMail = OutApp.CreateItem(0)
        On Error Resume Next
        With OutMail
            .To = cell.Value
            .Subject = "Index Option RFQ"
            .CC = ThisWorkbook.Sheets("Mailinfo").Range("cc_email").Value
            .HTMLBody = StrBody & RangetoHTML(rng) & "<br>" & "Thanks"
            .Display  'Or use Send to send each email without displaying it first
        End With
        Set OutMail = Nothing
    End If
Next cell
On Error GoTo 0

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub


问:
Android: Demux MP4 into video and audio?
I need to demux an MP4 file into video and audio to do some editing on the audio. I don't want to use FFMPEG, I've already attempted to use it once and it went horribly. How would I go about demuxing? From google searches, it seems like there isn't even a way to do it. Nothing ever comes up. I was thinking of converting an MP4 into an MP3, editing that and then adding that audio onto the original MP4 using MP4Parser, how can I edit the MP3? Absolutely any help is appreciated, I have no idea where to go from here.</p>

答:
I think you will still find ffmpeg the easiest and best supported way to manipulate video.

There are good well supported wrappers that should address the issues you have seen - one example is:

https://github.com/WritingMinds/ffmpeg-android-java


问:
Cannot load obfuscated assembly
I'm working for the first time with dotfuscator. My project is written in C# and .NET 3.5, it has a main program and some plugins; this is the slice of code that loads the plugins:

```<code>// Load the file
Assembly asm = Assembly.LoadFile( pluginPath );

// Instantiate the types I need
foreach( Type type in asm.GetTypes() )
{
    ...
}
</code>```

Now the problem is: if i don't obfuscate everything is fine but when i use dotfuscator asm.GetTypes() throw a ReflectionTypeLoadException which says

The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I googled for hours with no result. Thanks in advance.

EDIT: After some researches and debugging I think it's a problem in the manifest, because the reflection can't see (or loads) the types inside the assembly. I opened the obfuscated assembly with Reflector but everything seems fine.

答:
Obfuscation works, in part, by renaming some or all method names, type names, etc.

Reflection can often fail when obfuscation is used. If you're lucky, you can be selective when it comes to choosing  what to obfuscate, but this requires some attention to detail.

ContentLicense: CC BY-SA 2.5

Title: Cannot load obfuscated assembly

Body:
I'm working for the first time with dotfuscator. My project is written in C# and .NET 3.5, it has a main program and some plugins; this is the slice of code that loads the plugins:

// Load the file
Assembly asm = Assembly.LoadFile( pluginPath );

// Instantiate the types I need
foreach( Type type in asm.GetTypes() )
{
    ...
}

Now the problem is: if i don't obfuscate everything is fine but when i use dotfuscator asm.GetTypes() throw a ReflectionTypeLoadException which says

The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I googled for hours with no result. Thanks in advance.

EDIT: After some researches and debugging I think it's a problem in the manifest, because the reflection can't see (or loads) the types inside the assembly. I opened the obfuscated assembly with Reflector but everything seems fine.


问:
Converting Integer to Long
I need to get the value of a field using reflection. It so happens that I am not always sure what the datatype of the field is. For that, and to avoid some code duplication I have created the following method:

```<code>@SuppressWarnings("unchecked")
private static <T> T getValueByReflection(VarInfo var, Class<?> classUnderTest, Object runtimeInstance) throws Throwable {
  Field f = classUnderTest.getDeclaredField(processFieldName(var));
  f.setAccessible(true);
  T value = (T) f.get(runtimeInstance);

  return value;
}
</code>```

And use this method like:

```<code>Long value1 = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
</code>```

or

```<code>Double[] value2 = getValueByReflection(inv.var2(), classUnderTest, runtimeInstance);
</code>```

The problem is that I can't seem to cast Integer to Long:

```<code>java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
</code>```

Is there a better way to achieve this?

I am using Java 1.6.

答:
A parser from int variables to the long type is included in the Integer class. Here is an example:

```<code>int n=10;
long n_long=Integer.toUnsignedLong(n);
</code>```

You can easily use this in-built function to create a method that parses from int to long:

```<code>    public static long toLong(int i){
    long l;
    if (i<0){
        l=-Integer.toUnsignedLong(Math.abs(i));
    }
    else{
        l=Integer.toUnsignedLong(i);
    }
    return l;
}
</code>```

Title: Converting Integer to Long

Body:
I need to get the value of a field using reflection. It so happens that I am not always sure what the datatype of the field is. For that, and to avoid some code duplication I have created the following method:

@SuppressWarnings("unchecked")
private static <T> T getValueByReflection(VarInfo var, Class<?> classUnderTest, Object runtimeInstance) throws Throwable {
  Field f = classUnderTest.getDeclaredField(processFieldName(var));
  f.setAccessible(true);
  T value = (T) f.get(runtimeInstance);

  return value;
}

And use this method like:

Long value1 = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);

or

Double[] value2 = getValueByReflection(inv.var2(), classUnderTest, runtimeInstance);

The problem is that I can't seem to cast Integer to Long:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

Is there a better way to achieve this?

I am using Java 1.6.

Body:
A parser from int variables to the long type is included in the Integer class. Here is an example:

int n=10;
long n_long=Integer.toUnsignedLong(n);

You can easily use this in-built function to create a method that parses from int to long:

    public static long toLong(int i){
    long l;
    if (i<0){
        l=-Integer.toUnsignedLong(Math.abs(i));
    }
    else{
        l=Integer.toUnsignedLong(i);
    }
    return l;
}


问:
RxJava; How to emit observables synchronously
I want to synchronously emit two Observable objects (which are asynchronous), one after the other where it returns the first emitted Observable object. If the first one fails, it should not emit the second one.

Let's say we have one Observable that signs a user in, and another Observable that automatically selects the user's account, after signing in.

This is what I tried:

```<code>public Observable<AccessToken> signInAndSelectAccount(String username, String password)
{

    Observable<AccessToken> ob1 = ...; // Sign in.
    Observable<Account> ob2 = ...; // Select account.

    return Observable.zip(
            ob1,
            ob2,
            new Func2<AccessToken, Account, AccessToken>() {
                @Override
                public AccessToken call(AccessToken accessToken, Account account)
                {
                     return accessToken;
                }
            });
}
</code>```

This unfortunately does not work for my use case. It will emit/call both observables parallel, starting with 'ob1'.

Did someone encounter a similar use case? Or has an idea on how to make observables wait for eachother in a synchronous way, where the first emitted can be returned?

Thanks in advance.

答:
You can also use rx.observables.BlockingObservable e.g.:</p>

```<code>BlockingObservable.from(/**/).single();
</code>```

Body:
I want to synchronously emit two Observable objects (which are asynchronous), one after the other where it returns the first emitted Observable object. If the first one fails, it should not emit the second one.

Let's say we have one Observable that signs a user in, and another Observable that automatically selects the user's account, after signing in.

This is what I tried:

public Observable<AccessToken> signInAndSelectAccount(String username, String password)
{

    Observable<AccessToken> ob1 = ...; // Sign in.
    Observable<Account> ob2 = ...; // Select account.

    return Observable.zip(
            ob1,
            ob2,
            new Func2<AccessToken, Account, AccessToken>() {
                @Override
                public AccessToken call(AccessToken accessToken, Account account)
                {
                     return accessToken;
                }
            });
}

This unfortunately does not work for my use case. It will emit/call both observables parallel, starting with 'ob1'.

Did someone encounter a similar use case? Or has an idea on how to make observables wait for eachother in a synchronous way, where the first emitted can be returned?

Thanks in advance.

Body:
You can also use rx.observables.BlockingObservable e.g.:

BlockingObservable.from(/**/).single();


问:
FullCalendar Js Select Function allDay
I have a select function defined as follows:

```<code>    select: function(start,end, callback){
        var allDay = !start.hasTime();
        alert(allDay);
</code>```

When you select a date on the calendar page, the allDay parameter is set to true. However, I do not want this. Is there a way to make allDay be set to false on select?

I have defined all the parameters like so:

```<code>    $('#calendar').fullCalendar({
        selectable: true,
        selectHelper: true,
        editable: true,
        eventLimit: true,
        allDay:false, // I really thought this would work...but it doesn't
        ...
</code>```

But it still doesn't work. Any ideas?

EDIT:

I have also tried setting the allDay in the event:

```<code>                start = start.format("YYYY-MM-DD");
                end = end.format("YYYY-MM-DD");
                start = start + "T" + startTime;
                end = end + "T" + endTime;

                var event={title: name, start: start, end:end, description: description, allDayDefault: false};
</code>```

答:
You can set the default value to allDay on the event object with allDayDefault: false. By default, is undefined:

```<code>allDayDefault: false
</code>```

More info:
https://fullcalendar.io/docs/event_data/allDayDefault/

Title: FullCalendar Js Select Function allDay

Body:
I have a select function defined as follows:

    select: function(start,end, callback){
        var allDay = !start.hasTime();
        alert(allDay);

When you select a date on the calendar page, the allDay parameter is set to true. However, I do not want this. Is there a way to make allDay be set to false on select?

I have defined all the parameters like so:

    $('#calendar').fullCalendar({
        selectable: true,
        selectHelper: true,
        editable: true,
        eventLimit: true,
        allDay:false, // I really thought this would work...but it doesn't
        ...

But it still doesn't work. Any ideas?

EDIT:

I have also tried setting the allDay in the event:

                start = start.format("YYYY-MM-DD");
                end = end.format("YYYY-MM-DD");
                start = start + "T" + startTime;
                end = end + "T" + endTime;

                var event={title: name, start: start, end:end, description: description, allDayDefault: false};

Body:
You can set the default value to allDay on the event object with allDayDefault: false. By default, is undefined:

allDayDefault: false

More info:
https://fullcalendar.io/docs/event_data/allDayDefault/


问:
How can we use the dynamically upload images effectively and responsively in content management system like Drupal 7?
Need Solution for the following:

single image uploaded via cms to be used responsively without losing
clarity...and also bigger file size images being used in devices.

methods that can be done to improve faster loading of image files and overall site performance.

答: Have you tried using the picture module https://www.drupal.org/project/picture. You need to set it up using breakpoints but it should be able to take care of both of your issues. The picture module creates variation of your image for different breakpoints.</p>


问:
Create a variable to hold objects of different types C++
I have 3 different objects A, B and C. Depending on the the parameter given, I would like to choose among these different objects. In programming,

```<code>class A {
  public:
    void printHello() { cout << "HELLO A" << endl; }
};

class B {
  public:
    void printHello() { cout << "HELLO B" << endl; }
};

class C {
   public:
     void printHello() { cout << "HELLO C" << endl; }
};

int main () {
    string key = "c";
    A a;
    B b;
    C c;
    Object obj; // I don't know how to declare Object.

    if (key == "a") obj = a;
    else if (key == "b") obj = b;
    else obj = c;
    obj.printHello(); // print Hello C.
    return 0;
}
</code>```

I have thought about templates and struct objects. But none of them work so far.

```<code>template<typename T1, T2, T3>
T1 getType(string key, T1 t1, T2 t2, T3 t3) { // this is problem coz return types are different.
    if (key == "a") return t1;
    else if (key == "b") return t2;
    else return t3;
}
</code>```

It is easy to create Object o; in JAVA because every object in Java is subclass of Object class. But how do I achieve this in C++?

Edit.
I can't change class A, B and C. I was given these classes to work with and my goal is to implement main method. So, inheritance was out of the question for me. Sorry for any confusion.

Any help is appreciated.

答:
You're looking for a variant type. There's an upcoming std::variant in C++17, and C++11-compliant versions in boost and around the web. Example with boost::variant:

```<code>struct visitor
{
    void operator()(const A&){ cout << "HELLO A" << endl; }
    void operator()(const B&){ cout << "HELLO B" << endl; }
    void operator()(const C&){ cout << "HELLO C" << endl; }
};

int main()
{
    visitor v;

    // `obj` is either an `A`, a `B` or a `C` at any given moment.
    boost::variant<A, B, C> obj{B{}};
    //                         ^^^^^
    //                   Initialize with `B`.

    boost::apply_visitor(v, obj); // prints "HELLO B"

    obj = A{};
    boost::apply_visitor(v, obj); // prints "HELLO A"
}
</code>```

Body:
I have 3 different objects A, B and C. Depending on the the parameter given, I would like to choose among these different objects. In programming,

class A {
  public:
    void printHello() { cout << "HELLO A" << endl; }
};

class B {
  public:
    void printHello() { cout << "HELLO B" << endl; }
};

class C {
   public:
     void printHello() { cout << "HELLO C" << endl; }
};

int main () {
    string key = "c";
    A a;
    B b;
    C c;
    Object obj; // I don't know how to declare Object.

    if (key == "a") obj = a;
    else if (key == "b") obj = b;
    else obj = c;
    obj.printHello(); // print Hello C.
    return 0;
}

I have thought about templates and struct objects. But none of them work so far.

template<typename T1, T2, T3>
T1 getType(string key, T1 t1, T2 t2, T3 t3) { // this is problem coz return types are different.
    if (key == "a") return t1;
    else if (key == "b") return t2;
    else return t3;
}

It is easy to create Object o; in JAVA because every object in Java is subclass of Object class. But how do I achieve this in C++?

Edit.
I can't change class A, B and C. I was given these classes to work with and my goal is to implement main method. So, inheritance was out of the question for me. Sorry for any confusion.

Any help is appreciated.

Body:
You're looking for a variant type. There's an upcoming std::variant in C++17, and C++11-compliant versions in boost and around the web. Example with boost::variant:

struct visitor
{
    void operator()(const A&){ cout << "HELLO A" << endl; }
    void operator()(const B&){ cout << "HELLO B" << endl; }
    void operator()(const C&){ cout << "HELLO C" << endl; }
};

int main()
{
    visitor v;

    // `obj` is either an `A`, a `B` or a `C` at any given moment.
    boost::variant<A, B, C> obj{B{}};
    //                         ^^^^^
    //                   Initialize with `B`.

    boost::apply_visitor(v, obj); // prints "HELLO B"

    obj = A{};
    boost::apply_visitor(v, obj); // prints "HELLO A"
}


问:
hdf to ndarray in numpy - fast way
I am looking for a fast way to set my collection of hdf files into a numpy array where each row is a flattened version of an image. What I exactly mean:

My hdf files store, beside other informations, images per frames. Each file holds 51 frames with 512x424 images. Now I have 300+ hdf files and I want the image pixels to be stored as one single vector per frame, where all frames of all images are stored in one numpy ndarray. The following picture should help to understand:

What I got so far is a very slow method, and I actually have no idea how i can make it faster. The problem is that my final array is called too often, as far as I think. Since I observe that the first files are loaded into the array very fast but speed decreases fast. (observed by printing the number of the current hdf file)

My current code:

```<code>os.chdir(os.getcwd()+"\\datasets")

# predefine first row to use vstack later
numpy_data = np.ndarray((1,217088))

# search for all .hdf files
for idx, file in enumerate(glob.glob("*.hdf5")):
  f = h5py.File(file, 'r')
  # load all img data to imgs (=ndarray, but not flattened)
  imgs = f['img']['data'][:]

  # iterate over all frames (50)
  for frame in range(0, imgs.shape[0]):
    print("processing {}/{} (file/frame)".format(idx+1,frame+1))
    data = np.array(imgs[frame].flatten())
    numpy_data = np.vstack((numpy_data, data))

    # delete first row after another is one is stored
    if idx == 0 and frame == 0:
        numpy_data = np.delete(numpy_data, 0,0)

f.close()
</code>```

For further information, I need this for learning a decision tree. Since my hdf file is bigger than my RAM, I think converting into a numpy array save memory and is therefore better suited.

Thanks for every input.

答:
I don't think you need to iterate over

```<code>imgs = f['img']['data'][:]
</code>```

and reshape each 2d array.  Just reshape the whole thing.  If I understand your description right, imgs is a 3d array: (51, 512, 424)

```<code>imgs.reshape(51, 512*424)
</code>```

should be the 2d equivalent.

If you must loop, don't use vstack (or some variant to build a bigger array). One, it is slow, and two it's a pain to cleanup the initial 'dummy' entry.  Use list appends, and do the stacking once, at the end

```<code>alist = []
for frame....
   alist.append(data)
data_array = np.vstack(alist)
</code>```

vstack (and family) takes a list of arrays as input, so it can work with many at once.  List append is much faster when done iteratively.

I question whether putting things into one array will help.  I don't know exactly how the the size of a hdf5 file relates to the size of the downloaded array, but I expect they are in the same order of magnitude.  So trying to load all 300 files into memory might not work.  That's what, 3G of pixels?

For an individual file, h5py has provision for loading chunks of an array that is too large to fit in memory.  That indicates that often the problem goes the other way, the file holds more than fits.

Is it possible to load large data directly into numpy int8 array using h5py?

Title: hdf to ndarray in numpy - fast way

Body:
I am looking for a fast way to set my collection of hdf files into a numpy array where each row is a flattened version of an image. What I exactly mean:

My hdf files store, beside other informations, images per frames. Each file holds 51 frames with 512x424 images. Now I have 300+ hdf files and I want the image pixels to be stored as one single vector per frame, where all frames of all images are stored in one numpy ndarray. The following picture should help to understand:

What I got so far is a very slow method, and I actually have no idea how i can make it faster. The problem is that my final array is called too often, as far as I think. Since I observe that the first files are loaded into the array very fast but speed decreases fast. (observed by printing the number of the current hdf file)

My current code:

os.chdir(os.getcwd()+"\\datasets")

# predefine first row to use vstack later
numpy_data = np.ndarray((1,217088))

# search for all .hdf files
for idx, file in enumerate(glob.glob("*.hdf5")):
  f = h5py.File(file, 'r')
  # load all img data to imgs (=ndarray, but not flattened)
  imgs = f['img']['data'][:]

  # iterate over all frames (50)
  for frame in range(0, imgs.shape[0]):
    print("processing {}/{} (file/frame)".format(idx+1,frame+1))
    data = np.array(imgs[frame].flatten())
    numpy_data = np.vstack((numpy_data, data))

    # delete first row after another is one is stored
    if idx == 0 and frame == 0:
        numpy_data = np.delete(numpy_data, 0,0)

f.close()

For further information, I need this for learning a decision tree. Since my hdf file is bigger than my RAM, I think converting into a numpy array save memory and is therefore better suited.

Thanks for every input.

Body:
I don't think you need to iterate over

imgs = f['img']['data'][:]

and reshape each 2d array.  Just reshape the whole thing.  If I understand your description right, imgs is a 3d array: (51, 512, 424)

imgs.reshape(51, 512*424)

should be the 2d equivalent.

If you must loop, don't use vstack (or some variant to build a bigger array). One, it is slow, and two it's a pain to cleanup the initial 'dummy' entry.  Use list appends, and do the stacking once, at the end

alist = []
for frame....
   alist.append(data)
data_array = np.vstack(alist)

vstack (and family) takes a list of arrays as input, so it can work with many at once.  List append is much faster when done iteratively.

I question whether putting things into one array will help.  I don't know exactly how the the size of a hdf5 file relates to the size of the downloaded array, but I expect they are in the same order of magnitude.  So trying to load all 300 files into memory might not work.  That's what, 3G of pixels?

For an individual file, h5py has provision for loading chunks of an array that is too large to fit in memory.  That indicates that often the problem goes the other way, the file holds more than fits.

Is it possible to load large data directly into numpy int8 array using h5py?


问:
Cannot access Neo4j browser on a Windows Server
I have a Windows Server 2012 virtual machine provisioned on Azure. I installed Neo4j server on this virtual machine and I'm accessing the Neo4j browser on localhost:7474.

However I cannot access the browser outside using my virtual machine's public IP e.g <machineIP:7474>

Here's what I have done so far:

In the Azure portal, I added inbound rules for the NSG to allow http and https ports 80 and 443 (I have done the same on a Linux virtual machine also hosted in Azure and I can access the browser just fine)

I also added an inbound rule in Windows Firewall to allow Port 80 and 443 as well

What possibly blocks me from accessing the virtual machine's IP from the outside?

答:
To remotely access Neo4j installed on a Windows VM in Azure, these are the changes you'll need to make:

In the Azure portal, add TCP port 7474 to the Endpoints of your Windows VM

On your Windows VM, in the Windows Firewall Advances Security, add a new Inbound Rule for port 7474

Change the conf/neo4j.conf and uncomment this line:
org.neo4j.server.webserver.address=0.0.0.0

Note: In case you also want full access to Neo4j's browse interface including Bolt, then also add port 7687 both in the Azure Endpoints and the Windows Firewall.


问:
How to Angular Material datepicker leave/keep opened
I've tried with md-blur md-focus, each fails. I'm using Angular Material 1.1.3 and i need to keep datepicker opened after date picked action. So, how to keep it opened, after this action. Anybody can help?

答:
Due to the md-datepicker documentation you can't achieve this. ngMaterials is good but comes with a lot of limitations. You can 'fake' this by using md-calendar like in this runnable demo codepen.

View

```<code><div ng-app="MyApp" ng-controller="MyController" layout-padding>
    {{ date }}<br />
    <input type="date" ng-model="date" ng-click="openDatePicker()" ng-show="!datePickerOpened">
    <md-calendar class="fixed-calendar" ng-show="datePickerOpened" ng-model="date"></md-calendar>
</div>
</code>```

CSS

```<code>.fixed-calendar {
  width: 340px;
  height: 340px;
  display: block;
}

.fixed-calendar .md-calendar-scroll-mask {
  width: 340px !important;
}

.fixed-calendar .md-virtual-repeat-scroller {
  width: 340px !important;
  height: 308px;
}
</code>```

Application

```<code>angular
    .module('MyApp', ['ngMaterial'])
    .controller('MyController', function($scope, $timeout) {

    //Init
    $scope.datePickerOpened = false;
    $scope.date = new Date();

    //show datepicker action
    $scope.openDatePicker = function () {

        //show datepicker
        $scope.datePickerOpened = true

        //avoid date set to 1933 by async reinit date after ng-show rendering
        $timeout(function () {
             $scope.date = new Date();
        });
    }
});
</code>```

Body:
Due to the md-datepicker documentation you can't achieve this. ngMaterials is good but comes with a lot of limitations. You can 'fake' this by using md-calendar like in this runnable demo codepen.

View

<div ng-app="MyApp" ng-controller="MyController" layout-padding>
    {{ date }}<br />
    <input type="date" ng-model="date" ng-click="openDatePicker()" ng-show="!datePickerOpened">
    <md-calendar class="fixed-calendar" ng-show="datePickerOpened" ng-model="date"></md-calendar>
</div>

CSS

.fixed-calendar {
  width: 340px;
  height: 340px;
  display: block;
}

.fixed-calendar .md-calendar-scroll-mask {
  width: 340px !important;
}

.fixed-calendar .md-virtual-repeat-scroller {
  width: 340px !important;
  height: 308px;
}

Application

angular
    .module('MyApp', ['ngMaterial'])
    .controller('MyController', function($scope, $timeout) {

    //Init
    $scope.datePickerOpened = false;
    $scope.date = new Date();

    //show datepicker action
    $scope.openDatePicker = function () {

        //show datepicker
        $scope.datePickerOpened = true

        //avoid date set to 1933 by async reinit date after ng-show rendering
        $timeout(function () {
             $scope.date = new Date();
        });
    }
});


问:
Error Conversion failed when converting date and/or time from character string: varchar(8000)
I have a column of type varchar(8000). We save all kinds of data in it like number, text, date etc.

I wrote a simple select query to get all "Date" values from the table all works, I can also use CAST or Convert to get my value in this format 2014-12-16 00:00:00.000.

Now I'm trying to add a where clause to filter this year's info, but I get an error:

Conversion failed when converting date and/or time from character string.

When I use TOP 10000 in my select query the error goes away. This is really strange

```<code>; WITH TempTable AS
(
    SELECT
        ID, CAST(Value AS DateTime) [SomeDate]
    FROM
        SampleTable
    WHERE
        ColType = 'Date'
)
SELECT *
FROM FROM TempTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'
</code>```

This throws

Conversion failed when converting date and/or time from character string.

```<code>; WITH TempTable AS
(
    SELECT TOP 100000
        ID, CAST(Value AS DateTime) [SomeDate]
    FROM
        SampleTable
    WHERE
        ColType = 'Date'
)
SELECT *
FROM FROM TempTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'
</code>```

This works fine. Please note I have only 25 some rows in my result. Top 100000 is just a big number I used. This is very strange how my TOP keyword is making my query good.

Update:

Here is how I ended up resolving without using TOP keyword. I have split my query little bit as seen below. Thank you all for your time and comments.

```<code>;WITH GetAllIDs
AS (
    SELECT ID
    FROM SampleTable
    WHERE ColType = 'Date'
    )
    ,FinalTable
AS (
    SELECT ID
        ,(
            SELECT Cast([Value] AS DATETIME)
            FROM SampleTable dt
            WHERE dt.ID = tt.ID
                AND dd.ColType = 'Date'
            ) [SomeDate]
    FROM GetAllIDs tt
    )
SELECT *FROM FinalTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'
</code>```

答:
Based on SQL 2008, you would have to change your pattern.

First, why it works with the TOP command. TOP selects all records matching the WHERE clause in the query up to the limit of the TOP. Since you have a WHERE clause, the version with the TOP only passes records with the Coltype of 'Date' on to the date check. Without the top, the optimizer thinks that checking the value of the Value column against the date range will be faster than filtering the column type, since only one data element retrieval is required to check that, "speeding up" (in this case, blowing up) the query.

One option that should work would be to change the TempTable definition code to this:

```<code>; WITH TempTable AS
(
    SELECT TOP 100 PERCENT
        ID, CAST(Value AS DateTime) [SomeDate]
    FROM
        SampleTable
    WHERE
        ColType = 'Date'
)
</code>```

Your other obvious option would be to extract all of the values to an actual temp table, rather than using a CTE directly, then query that table.

ContentLicense: CC BY-SA 4.0

Body:
I have a column of type varchar(8000). We save all kinds of data in it like number, text, date etc.

I wrote a simple select query to get all "Date" values from the table all works, I can also use CAST or Convert to get my value in this format 2014-12-16 00:00:00.000.

Now I'm trying to add a where clause to filter this year's info, but I get an error:

Conversion failed when converting date and/or time from character string.

When I use TOP 10000 in my select query the error goes away. This is really strange

; WITH TempTable AS
(
    SELECT
        ID, CAST(Value AS DateTime) [SomeDate]
    FROM
        SampleTable
    WHERE
        ColType = 'Date'
)
SELECT *
FROM FROM TempTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'

This throws

Conversion failed when converting date and/or time from character string.

; WITH TempTable AS
(
    SELECT TOP 100000
        ID, CAST(Value AS DateTime) [SomeDate]
    FROM
        SampleTable
    WHERE
        ColType = 'Date'
)
SELECT *
FROM FROM TempTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'

This works fine. Please note I have only 25 some rows in my result. Top 100000 is just a big number I used. This is very strange how my TOP keyword is making my query good.

Update:

Here is how I ended up resolving without using TOP keyword. I have split my query little bit as seen below. Thank you all for your time and comments.

;WITH GetAllIDs
AS (
    SELECT ID
    FROM SampleTable
    WHERE ColType = 'Date'
    )
    ,FinalTable
AS (
    SELECT ID
        ,(
            SELECT Cast([Value] AS DATETIME)
            FROM SampleTable dt
            WHERE dt.ID = tt.ID
                AND dd.ColType = 'Date'
            ) [SomeDate]
    FROM GetAllIDs tt
    )
SELECT *FROM FinalTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'

Body:
Based on SQL 2008, you would have to change your pattern.

First, why it works with the TOP command. TOP selects all records matching the WHERE clause in the query up to the limit of the TOP. Since you have a WHERE clause, the version with the TOP only passes records with the Coltype of 'Date' on to the date check. Without the top, the optimizer thinks that checking the value of the Value column against the date range will be faster than filtering the column type, since only one data element retrieval is required to check that, "speeding up" (in this case, blowing up) the query.

One option that should work would be to change the TempTable definition code to this:

; WITH TempTable AS
(
    SELECT TOP 100 PERCENT
        ID, CAST(Value AS DateTime) [SomeDate]
    FROM
        SampleTable
    WHERE
        ColType = 'Date'
)

Your other obvious option would be to extract all of the values to an actual temp table, rather than using a CTE directly, then query that table.


问:
Chrome inspector console does not work with version 54.0.2840.99
I use node-inspector to debug JS with Chrome version 54.0.2840.99.
I enter "node-inspector" in one windows cmd console and "node --debug-brk l:\dev\debug\test.js" in another windows cmd console. Open "http://127.0.0.1:8080/?ws=127.0.0.1:8080&port=5858" in Chrome. It's able to debug as usual. But I input "1 + 2" in Chrome console, press "Enter", nothing happen. I would expect "3" is output to Chrome console. It did work with Chrome version 48.0.2564.116. I did not test with other Chrome versions.

Is it a defect of the new Chrome versions? How to resolve the problem?
I captured the pictures as below:

答:
It's caused by Chrome deprecating KeyboardEvent.keyIdentifier.

The workaround would be to add keyIdentifier back to the KeyboardEvent prototype.

I also noticed that the KeyboardEvent.key string values are different from those from KeyboardEvent.keyIdentifier so I show below how to handle those differences if needed.

```<code>Object.defineProperty(KeyboardEvent.prototype, 'keyIdentifier', {
    get: function() {
        switch (this.key) {
            case "ArrowDown":
                return "Down";
                break;
            case "ArrowLeft":
                return "Left";
                break;
            case "ArrowRight":
                return "Right";
                break;
            case "ArrowUp":
                return "Up";
                break;
            case "Tab":
                return "U+0009";
                break;
            case "Escape":
                return "U+001B";
                break;
            default:
                return this.key;
        }
    }
});
</code>```

Simply replacing isEnterKey() is not sufficient and the above code handles this fix.

Body:
It's caused by Chrome deprecating KeyboardEvent.keyIdentifier.

The workaround would be to add keyIdentifier back to the KeyboardEvent prototype.

I also noticed that the KeyboardEvent.key string values are different from those from KeyboardEvent.keyIdentifier so I show below how to handle those differences if needed.

Object.defineProperty(KeyboardEvent.prototype, 'keyIdentifier', {
    get: function() {
        switch (this.key) {
            case "ArrowDown":
                return "Down";
                break;
            case "ArrowLeft":
                return "Left";
                break;
            case "ArrowRight":
                return "Right";
                break;
            case "ArrowUp":
                return "Up";
                break;
            case "Tab":
                return "U+0009";
                break;
            case "Escape":
                return "U+001B";
                break;
            default:
                return this.key;
        }
    }
});

Simply replacing isEnterKey() is not sufficient and the above code handles this fix.


问:
Parsing a line from an ASCII HDR file python
I am having difficulty parsing a line from an hdr file I have. When I print read (data) like in the code below the command window outputs the contents of the hdr file. However, when I try to parse out a line or a column , like the script below, it outputs nothing in the command window. </p>

```<code>import numpy as np
import matplotlib.pyplot as plt

f = open('zz_ssmv11034tS__T0001TTNATS2012021505HP001.Hdr', 'r')
data = f.read()
print (data)

for line in f:
    columns = line.split()
    time = float(columns[2])
    print (time)

f.close()
</code>```

答:
Remove this two lines and execute your code again:

```<code>data = f.read()
print (data)
</code>```

Then change your loop:

```<code>for line in f.readlines():
    columns = line.split()
    time = float(columns[2])
    print (time)
</code>```

Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use readline(), readlines()

Read the post Why can't I call read() twice on an open file?

Body:
I am having difficulty parsing a line from an hdr file I have. When I print read (data) like in the code below the command window outputs the contents of the hdr file. However, when I try to parse out a line or a column , like the script below, it outputs nothing in the command window.

import numpy as np
import matplotlib.pyplot as plt

f = open('zz_ssmv11034tS__T0001TTNATS2012021505HP001.Hdr', 'r')
data = f.read()
print (data)

for line in f:
    columns = line.split()
    time = float(columns[2])
    print (time)

f.close()

Body:
Remove this two lines and execute your code again:

data = f.read()
print (data)

Then change your loop:

for line in f.readlines():
    columns = line.split()
    time = float(columns[2])
    print (time)

Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use readline(), readlines()

Read the post Why can't I call read() twice on an open file?


问:
Space in iOS app name is not showing
My bundle display name is "Standford 2015" in Xcode but it is showing on my iPhone as "Standford2015" when it's installed.

Am I doing anything wrong?

答:
In your localized InfoPlist.string DO NOT use spaces but instead use unicode character "No-break space" :

http://www.fileformat.info/info/unicode/char/00a0/index.htm

so your line in InfoPlist.string should look like :

"CFBundleDisplayName" = "My\U00A0app";

Title: Space in iOS app name is not showing


问:
Android - how to make a scrollable constraintlayout?
I want to make a layout that lets me scroll down using constraint layout, but I don't know how to go about it. Should the ScrollView be the parent of the ConstraintLayout like this?

```<code><?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

<android.support.constraint.ConstraintLayout
    android:id="@+id/Constraint"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</code>```

Or the other way around? Maybe someone can point me to a good tutorial on this or give an example, I can't seem to find one.

Also, I don't know if this is a bug or some configuration that I don't have set up but I've seen images like this one :

where there are some components outside the blueprint "blue rectangle" yet they are visible, while on my side if I place a component on the "white space" I can't see it or move it anywhere, and it appears on the component tree.

UPDATE :

I found a way to make the constraint layout scrollable in the design tool, using a horizontal guideline to push down the constraint layout border and extend it beyond the device, after that, you can use the guideline as the new bottom of the constraint layout to anchor the components.

答:
There is a bug in version 2.2 that makes it impossible to scroll the ConstraintLayout. I guess it still exists. You can use LinearLayout or RelativeLayout alternatively.

Also, check out: Is it possible to put a constraint layout inside a ScrollView.

Body:
I want to make a layout that lets me scroll down using constraint layout, but I don't know how to go about it. Should the ScrollView be the parent of the ConstraintLayout like this?

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

<android.support.constraint.ConstraintLayout
    android:id="@+id/Constraint"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Or the other way around? Maybe someone can point me to a good tutorial on this or give an example, I can't seem to find one.

Also, I don't know if this is a bug or some configuration that I don't have set up but I've seen images like this one :

where there are some components outside the blueprint "blue rectangle" yet they are visible, while on my side if I place a component on the "white space" I can't see it or move it anywhere, and it appears on the component tree.

UPDATE :

I found a way to make the constraint layout scrollable in the design tool, using a horizontal guideline to push down the constraint layout border and extend it beyond the device, after that, you can use the guideline as the new bottom of the constraint layout to anchor the components.


问:
Setting the context of a textview array
How do i apply a context to a textview array?

```<code>TextView[] textView = new TextView[3];

for (int cell = 0; cell < 3; cell++){
    textView[cell].setText("-");
}
</code>```

Apparently, this error gets thrown:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

If this was not a textview array, adding the activity context as a parameter when calling the constructor would render the object not null, solving my issue:

```<code>for (int cell = 0; cell < 3; cell++){
    TextView textView = new TextView(context);
    textView.setText("-");
}
</code>```

Where, context = getActivity().getApplicationContext()

How do i set the context parameter for the textview array? What i want is dynamic variable names for each textview so i can call the individual textviews respectively.

答:
You should create object before calling method.
Try this:</p>

```<code>TextView[] textView = new TextView[3];

for (int cell = 0; cell < 3; cell++) {
    textView[cell] = new TextView(context);
    textView[cell].setText("-");
}
</code>```

Title: Setting the context of a textview array

Body:
How do i apply a context to a textview array?

TextView[] textView = new TextView[3];

for (int cell = 0; cell < 3; cell++){
    textView[cell].setText("-");
}

Apparently, this error gets thrown:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

If this was not a textview array, adding the activity context as a parameter when calling the constructor would render the object not null, solving my issue:

for (int cell = 0; cell < 3; cell++){
    TextView textView = new TextView(context);
    textView.setText("-");
}

Where, context = getActivity().getApplicationContext()

How do i set the context parameter for the textview array? What i want is dynamic variable names for each textview so i can call the individual textviews respectively.

Body:
You should create object before calling method.
Try this:

TextView[] textView = new TextView[3];

for (int cell = 0; cell < 3; cell++) {
    textView[cell] = new TextView(context);
    textView[cell].setText("-");
}


问:
SQL syntax error
I'm trying to execute this query:

```<code>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.columns
WHERE table_name = 'MyTableName' AND column_name = 'ColumnInQuestion')
THEN ALTER TABLE MyTableName DROP COLUMN ColumnInQuestion;
</code>```

And I get the following error message:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'articles'' at line 1

I'm using MySQL 5.1.something, so I don't think information_schema not being defined is the issue. Any ideas?

Thank you for your help!

答:
You cannot do this. IF EXISTS is meaningful only for creating tables/databases

If you need to drop column if it exists - you could use

```<code>ALTER IGNORE TABLE DROP COLUMN ...
</code>```

Note on IGNORE.

Title: SQL syntax error

Body:
I'm trying to execute this query:

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.columns
WHERE table_name = 'MyTableName' AND column_name = 'ColumnInQuestion')
THEN ALTER TABLE MyTableName DROP COLUMN ColumnInQuestion;

And I get the following error message:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'articles'' at line 1

I'm using MySQL 5.1.something, so I don't think information_schema not being defined is the issue. Any ideas?

Thank you for your help!

Body:
You cannot do this. IF EXISTS is meaningful only for creating tables/databases

If you need to drop column if it exists - you could use

ALTER IGNORE TABLE DROP COLUMN ...

Note on IGNORE.


问:
Play JSON serialize/deserialize case class with one argument by skipping it
I have the following objects:

```<code>case class Foo(value: UUID)
case class Bar(foo: Foo)
</code>```

And I would like to have them serialized like this in JSON:

```<code>{foo: "e88ad5ea-13cf-4666-addb-c231c12cd3a3"}
</code>```

Meaning I want to omit the "value" argument added by the automatic formatter if I simply write this:

```<code>implicit val fooFormat = Json.format[Foo]
implicit val barFormat = Json.format[Bar]
</code>```

I tried writing my custom writers/readers but I do not really know how to skip a JPath.

答:
What about: </p>

```<code>implicit val format: Format[Bar] = new Format[Bar] {
   override def writes(o: Bar): JsValue = Json.obj("foo" -> o.foo.value)

override def reads(json: JsValue): JsResult[Bar] =
  (json \ "foo").validate[String].map(s => Bar(Foo(UUID.fromString(s))))
}
</code>```

Body:
I have the following objects:

case class Foo(value: UUID)
case class Bar(foo: Foo)

And I would like to have them serialized like this in JSON:

{foo: "e88ad5ea-13cf-4666-addb-c231c12cd3a3"}

Meaning I want to omit the "value" argument added by the automatic formatter if I simply write this:

implicit val fooFormat = Json.format[Foo]
implicit val barFormat = Json.format[Bar]

I tried writing my custom writers/readers but I do not really know how to skip a JPath.

Body:
What about:

implicit val format: Format[Bar] = new Format[Bar] {
   override def writes(o: Bar): JsValue = Json.obj("foo" -> o.foo.value)

override def reads(json: JsValue): JsResult[Bar] =
  (json \ "foo").validate[String].map(s => Bar(Foo(UUID.fromString(s))))
}


问:
Unix tr command to convert lower case to upper AND upper to lower case
So I was searching around and using the command tr you can convert from lower case to upper case and vice versa. But is there a way to do this both at once?

So:

```<code>$ tr '[:upper:]' '[:lower:]' or  $ tr A-Z a-z
</code>```

Will turn "Hello World ABC" to "hello world abc", but what I want is "hELLO wORLD abc".

答:
You can use \L& and \U& to convert to lower and upper case respectively:

$echo "SUJIT dhamale " | sed 's/.*/\L&/g'

Result: sujit dhamale

$ echo "SUJIT dhamale " | sed 's/.*/\U&/g'

Result: SUJIT DHAMALE

Body:
So I was searching around and using the command tr you can convert from lower case to upper case and vice versa. But is there a way to do this both at once?

So:

$ tr '[:upper:]' '[:lower:]' or  $ tr A-Z a-z

Will turn "Hello World ABC" to "hello world abc", but what I want is "hELLO wORLD abc".


问:
rails 4 routing on root site
I'm under rails 4 and I've a question about routes.
I'd like to have this situation:

```<code>/brand-name -> bind to brands#show
/serie-name -> bind to series#show
</code>```

I added this on my routes

```<code>get '/:id', to: 'brands#show', as: :fe_brand
get '/:id', to: 'series#show', as: :fe_serie
</code>```

but I'm always prompt to brands#show action, I know that it is correct, but I'd like to know if there is a work around for it.

Thank you

答:
I think you'd want to use separate namespaces for brands and series. Try:

get '/brands/:id', to: 'brands#show', as: :fe_brand

get '/series/:id', to: 'series#show', as: :fe_serie

The way the routes file works is that when a new request comes in the format gets pattern-matched and the first matching route it finds is used. Both of your routes are the same, hence you always get taken to brands show. To test this, if you rearrange those two lines in your routes file you should be taken to series#show instead.

Edit:

Since you list brands and series as plural, wouldn't their pages be more like an index than a show? So you could have your desired /brands and /series direct to their respective index pages and then use id's to like to each individual brand or series.

```<code>get '/brands',     to: 'brands#index', as: :fe_brands
get '/brands/:id', to: 'brands#show',  as: :show_fe_brand
get '/series',     to: 'series#index', as: :fe_serie
get '/series/:id', to: 'series#show',  as: :show_fe_serie
</code>```

Title: rails 4 routing on root site

Body:
I'm under rails 4 and I've a question about routes.
I'd like to have this situation:

/brand-name -> bind to brands#show
/serie-name -> bind to series#show

I added this on my routes

get '/:id', to: 'brands#show', as: :fe_brand
get '/:id', to: 'series#show', as: :fe_serie

but I'm always prompt to brands#show action, I know that it is correct, but I'd like to know if there is a work around for it.

Thank you

Body:
I think you'd want to use separate namespaces for brands and series. Try:

get '/brands/:id', to: 'brands#show', as: :fe_brand

get '/series/:id', to: 'series#show', as: :fe_serie

The way the routes file works is that when a new request comes in the format gets pattern-matched and the first matching route it finds is used. Both of your routes are the same, hence you always get taken to brands show. To test this, if you rearrange those two lines in your routes file you should be taken to series#show instead.

Edit:

Since you list brands and series as plural, wouldn't their pages be more like an index than a show? So you could have your desired /brands and /series direct to their respective index pages and then use id's to like to each individual brand or series.

get '/brands',     to: 'brands#index', as: :fe_brands
get '/brands/:id', to: 'brands#show',  as: :show_fe_brand
get '/series',     to: 'series#index', as: :fe_serie
get '/series/:id', to: 'series#show',  as: :show_fe_serie


问:
How to store variables values in a class i.e "settings"?
OK. After spending literally a few hours trying to get things working I give up.

Basically I am creating a program in which user inputs some values, then after hitting button a new scene is created and depending on the values it was given, different things take place.
My problem - I created "Settings.class" with a few variables with getters and setters. My assumption was to store the values input in there and whenever needed I have easy access to them using getters.
For some reason it doesn't work.

Keep in mind I simplified it as much as I can because It'd look very messy and would be very long if I pasted my original code. I made sure that the core of the problem is the same.

Settings class:

```<code>public class Settings {
private boolean diamonds;

public boolean getDiamonds() {
    return diamonds;
}
public void setDiamonds(boolean diamonds) {
    this.diamonds = diamonds;
}
}
</code>```

Controller class:

```<code>public class Controller implements Initializable {
private Settings settings = new Settings();
private ProblematicOne prob = new ProblematicOne();

public void handleGoAction() throws IOException {

settings.setDiamonds(true);

prob.editText("This shall be set");

/* ..creating new stage and scene here no reason to paste it here, no probs with that.. */

@Override
public void initialize(URL location, ResourceBundle resources) {
}
}
}
</code>```

And crème de la crème, problematic class:

```<code>public class ProblematicOne{

private Setting settings = new Settings();
String toBeEdited = "";  //

public void editText(String text){

if(settings.getDiamonds){      // for some reason it doesn't work; The getter returns false.
    toBeEdited = text;
}else if(!settings.getDiamonds){
    toBeEdited = "getDiamonds is false";
}
}
}
</code>```

答:
Your issue is that ProblematicClass creates a new instance of settings, so the value is not accessible. You need to pass the same instance into the other class, or make your variables in settings class static, so you can access them without instance:

```<code>public class Settings {
    private static boolean diamonds;

    public static boolean getDiamonds() {
        return diamonds;
    }
    public static void setDiamonds(boolean diamonds) {
        this.diamonds = diamonds;
    }
}
</code>```

And use it without instance:

```<code>Settings.setDiamonds(true);
Settings.getDiamonds();
</code>```

Body:
OK. After spending literally a few hours trying to get things working I give up.

Basically I am creating a program in which user inputs some values, then after hitting button a new scene is created and depending on the values it was given, different things take place.
My problem - I created "Settings.class" with a few variables with getters and setters. My assumption was to store the values input in there and whenever needed I have easy access to them using getters.
For some reason it doesn't work.

Keep in mind I simplified it as much as I can because It'd look very messy and would be very long if I pasted my original code. I made sure that the core of the problem is the same.

Settings class:

public class Settings {
private boolean diamonds;

public boolean getDiamonds() {
    return diamonds;
}
public void setDiamonds(boolean diamonds) {
    this.diamonds = diamonds;
}
}

Controller class:

public class Controller implements Initializable {
private Settings settings = new Settings();
private ProblematicOne prob = new ProblematicOne();

public void handleGoAction() throws IOException {

settings.setDiamonds(true);

prob.editText("This shall be set");

/* ..creating new stage and scene here no reason to paste it here, no probs with that.. */

@Override
public void initialize(URL location, ResourceBundle resources) {
}
}
}

And crème de la crème, problematic class:

public class ProblematicOne{

private Setting settings = new Settings();
String toBeEdited = "";  //

public void editText(String text){

if(settings.getDiamonds){      // for some reason it doesn't work; The getter returns false.
    toBeEdited = text;
}else if(!settings.getDiamonds){
    toBeEdited = "getDiamonds is false";
}
}
}

Body:
Your issue is that ProblematicClass creates a new instance of settings, so the value is not accessible. You need to pass the same instance into the other class, or make your variables in settings class static, so you can access them without instance:

public class Settings {
    private static boolean diamonds;

    public static boolean getDiamonds() {
        return diamonds;
    }
    public static void setDiamonds(boolean diamonds) {
        this.diamonds = diamonds;
    }
}

And use it without instance:

Settings.setDiamonds(true);
Settings.getDiamonds();