问:
platform-specific std::chrono::high_resolution_clock::period::num
I've noticed that std::chrono::high_resolution_clock::period::num = 1 for every system I've tested. Does there exist any system (embedded, desktop, mobile, or otherwise) where it happens to be some other number? (On such a system, 1 second would not be representable in ticks.)

答:
There are three implementations of std::chrono::high_resolution_clock that I am aware of:  Visual Studio, gcc and clang (when used with libc++).

All three of these have nanosecond-precision (std::chrono::high_resolution_clock::period::num = 1).  For VS and libc++, high_resolution_clock is type-aliased to steady_clock.  On gcc it is type-aliased to system_clock.

There is nothing in the spec that prevents std::chrono::high_resolution_clock::period::num != 1, and you are correct that on such a system 1 second would not be representable in "ticks".  This further translates to:

seconds would not be implicitly convertible to high_resolution_clock::duration.

To find the coarsest duration to which both seconds and high_resolution_clock::duration are convertible to, you can portably use:

```<code>using CT = common_type_t<seconds, high_resolution_clock::duration>;
</code>```

For all of the implementations I'm aware of, CT is a type-alias for nanoseconds.

Body:
There are three implementations of std::chrono::high_resolution_clock that I am aware of:  Visual Studio, gcc and clang (when used with libc++).

All three of these have nanosecond-precision (std::chrono::high_resolution_clock::period::num = 1).  For VS and libc++, high_resolution_clock is type-aliased to steady_clock.  On gcc it is type-aliased to system_clock.

There is nothing in the spec that prevents std::chrono::high_resolution_clock::period::num != 1, and you are correct that on such a system 1 second would not be representable in "ticks".  This further translates to:

seconds would not be implicitly convertible to high_resolution_clock::duration.

To find the coarsest duration to which both seconds and high_resolution_clock::duration are convertible to, you can portably use:

using CT = common_type_t<seconds, high_resolution_clock::duration>;

For all of the implementations I'm aware of, CT is a type-alias for nanoseconds.


来源: stackexchange

问:
Google Cloud Datalab - how to create a VM for training using by multiple users
I am new with Datalab, our team of data scientist asked us to have 5 individual VM for each of them, and another VM for Training which should be accessed by any of them. I have searched a lot and in documents of google it is written:

“Cloud Datalab instances are single-user environments, therefore each member of your team needs their own instance.”

So, my question is, what is the best practice for having a training Datalab machine and how I can give access to it to multiple users?

答:
I have found a work around:

1) create a G Suite Group in your organization, each group has an email address which can be used to give access in Google Cloud

2) add users to the group

3) add group's email address to IAM and give the following access: compute.instanceAdmin.v1 and iam.serviceAccountActor

4) create datalab VM and for the option --for-user put the email address of the group

5) Users now can conncet to the VM from their cloud shell using the following command:

```<code>datalab connect <VM_NAME> --no-user-checking
</code>```

So,each user has its own VM to develop and push the codes on repository, and for training, they can connect to this VM but not in the same time.

ContentLicense: CC BY-SA 3.0

Body:
I have found a work around:

1) create a G Suite Group in your organization, each group has an email address which can be used to give access in Google Cloud

2) add users to the group

3) add group's email address to IAM and give the following access: compute.instanceAdmin.v1 and iam.serviceAccountActor

4) create datalab VM and for the option --for-user put the email address of the group

5) Users now can conncet to the VM from their cloud shell using the following command:

datalab connect <VM_NAME> --no-user-checking

So,each user has its own VM to develop and push the codes on repository, and for training, they can connect to this VM but not in the same time.


问:
Android how to retrieve data from a Service using an Intent
I have a location service running on a separate java:

```<code>public class GPSService extends Service implements LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    Intent intent;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    String lat, lon;
    public static String str_receiver = "servicetutorial.service.receiver";
</code>```

I want to retrieve mLastLocation from it using an intent from another class, to pass that Location as input of the func MyFunc

If I use

```<code>startService(new Intent(this, GPSService.class));
GPSService obj = new GPSService ();
MyFunc(obj.mLastLocation);
</code>```

It compiles, but the Location object passed is null

Do I need to use put and get Extras? How to use it in case of Location variable? I do need to use put as well?

Note: Service is working no problem and updating as designed.
Thanks.

答: You can pass latitude and longitude as two different double values and retrieve using getDoubleExtra

Body:
I have a location service running on a separate java:

public class GPSService extends Service implements LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    Intent intent;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    String lat, lon;
    public static String str_receiver = "servicetutorial.service.receiver";

I want to retrieve mLastLocation from it using an intent from another class, to pass that Location as input of the func MyFunc

If I use

startService(new Intent(this, GPSService.class));
GPSService obj = new GPSService ();
MyFunc(obj.mLastLocation);

It compiles, but the Location object passed is null

Do I need to use put and get Extras? How to use it in case of Location variable? I do need to use put as well?

Note: Service is working no problem and updating as designed.
Thanks.


问:
Call function in jQuery
I have created a function inside a .click

```<code>$('#BeforeFunction').click(function(){

//something is entered here then the function below is called
Hello();

});

$('#HitMe').click(function(){
//something here.....
function Hello(){
alert ('Hit button is pressed');
}

});
</code>```

But the function when called causes an error, the message being Hello is not defined.

What is wrong exactly?

答:
ECMA-/Javascript has a function scope (also called, lexical scope). That means, everything you define within a function is only visible within the scope/context of this function. Hence, Hello is only known within the context of the event-handler function from HitMe.

Probably the best way to create such a function, is NOT to clobber the global namespace (putting it into the window object), but to define your own namespace / scope.

```<code>(function($) {
    function hello() {
        alert ('Hit button is pressed');
    }

    $('#BeforeFunction').click(function(){
         //something is entered here then the function below is called
         Hello();
    });

    $('#HitMe').click(function(){
         Hello();
    });

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

Title: Call function in jQuery

Body:
I have created a function inside a .click

$('#BeforeFunction').click(function(){

//something is entered here then the function below is called
Hello();

});

$('#HitMe').click(function(){
//something here.....
function Hello(){
alert ('Hit button is pressed');
}

});

But the function when called causes an error, the message being Hello is not defined.

What is wrong exactly?

Body:
ECMA-/Javascript has a function scope (also called, lexical scope). That means, everything you define within a function is only visible within the scope/context of this function. Hence, Hello is only known within the context of the event-handler function from HitMe.

Probably the best way to create such a function, is NOT to clobber the global namespace (putting it into the window object), but to define your own namespace / scope.

(function($) {
    function hello() {
        alert ('Hit button is pressed');
    }

    $('#BeforeFunction').click(function(){
         //something is entered here then the function below is called
         Hello();
    });

    $('#HitMe').click(function(){
         Hello();
    });

}(jQuery));

ContentLicense: CC BY-SA 2.5


问:
How to make Rails acceptable value out of JavaScript's array?

I'm trying to generate the value for a hidden field in a Rails form with JavaScript.

```<code>pickedImages = document.getElementsByClassName("picked_images");
imagesIds = []

for (var i = 0; i < pickedImages.length; i++) {
  imagesIds.push(pickedImages[i].id)
}

document.getElementById('user_post_materials').value = imagesIds;
</code>```

I need it like: value="150 152 146"

But when I try to make it out of JS array I get: value="150,152,146" which causes saving as a string in the database and further bugs.
I tried

```<code>imagesArray = imagesIds.join(' ')
document.getElementById('user_post_materials').value = imagesArray;
</code>```

But it still gives a wrong value: value="150, 152, 146" (Commas still present)

答:
Thanks to Bergi' and Roby Rodrigues' ideas I made it through.
So I did the following:

```<code>imagesArray = imagesIds.join(' ').replace(',', '');
</code>```

I let this question unaccepted for anyone who comes up with something better.

Body:
I'm trying to generate the value for a hidden field in a Rails form with JavaScript.

pickedImages = document.getElementsByClassName("picked_images");
imagesIds = []

for (var i = 0; i < pickedImages.length; i++) {
  imagesIds.push(pickedImages[i].id)
}

document.getElementById('user_post_materials').value = imagesIds;

I need it like: value="150 152 146"

But when I try to make it out of JS array I get: value="150,152,146" which causes saving as a string in the database and further bugs.
I tried

imagesArray = imagesIds.join(' ')
document.getElementById('user_post_materials').value = imagesArray;

But it still gives a wrong value: value="150, 152, 146" (Commas still present)

Body:
Thanks to Bergi' and Roby Rodrigues' ideas I made it through.
So I did the following:

imagesArray = imagesIds.join(' ').replace(',', '');

I let this question unaccepted for anyone who comes up with something better.


问:
Clicking on an element and getting the ID of child element
I'm working within a wordpress site. I have an image map that can run scripts when I click sections of the image.

Previously I would click a button and it would show a modal popup but it adds additional scripts etc. The button itself gives no clue to what function it is running, so I was thinking I could run a script that takes the ID of the polygon (image map) and finds the button that has an attribute that matches.

I was thinking something like

```<code>function popout(popup){

    $('.imp-shape').click(function() {
        var id = $(this).attr('id');
        alert(id);
    });
}
</code>```

to get my ID but I think it's not able to get down to the polygon element as it is clicking on the div container, below is the HTML

```<code><div class="imp-shape-container">
   <svg>
      <polygon class="imp-shape" id="elementID"></polygon>
   </svg>
</div>
</code>```

Any thoughts?

答:
You have added the click event onto the polygon should it should only fire when you click on this but it will propogate up the tree. Also, you may need to me more specific than using (this).

Try

```<code>function popout(popup){

$('.imp-shape').click(function(event) {

    var id = event.target.id;
    alert(id);
});
</code>```

}

Body:
I'm working within a wordpress site. I have an image map that can run scripts when I click sections of the image.

Previously I would click a button and it would show a modal popup but it adds additional scripts etc. The button itself gives no clue to what function it is running, so I was thinking I could run a script that takes the ID of the polygon (image map) and finds the button that has an attribute that matches.

I was thinking something like

function popout(popup){

    $('.imp-shape').click(function() {
        var id = $(this).attr('id');
        alert(id);
    });
}

to get my ID but I think it's not able to get down to the polygon element as it is clicking on the div container, below is the HTML

   <svg>
      <polygon class="imp-shape" id="elementID"></polygon>
   </svg>

Any thoughts?

Body:
You have added the click event onto the polygon should it should only fire when you click on this but it will propogate up the tree. Also, you may need to me more specific than using (this).

Try

function popout(popup){

$('.imp-shape').click(function(event) {

    var id = event.target.id;
    alert(id);
});

}


问:
event.preventDefault() and redirect asp mvc/jQuery
What am trying to do is to post on form submit to a action and catch response and that works fine.Problem is when RedirectToAction gets called, it just stays on that same view(it doesn't redirect),or in case model is not valid, it doesn't show model validation. So i guess the problem is with url, but how can I correct it?

jQuery

```<code>$("form").on("submit", function (e) {
  e.preventDefault();
  var form = $(this);

  var formURL = form.attr("action");
  $.ajax({
    type: "POST",
    url: formURL,
    data: $(this).serialize(),
    success: function (response) {
      if (response !== null && response.success == false) {
        alert(response.responseText);
      }
    }
  });
});
</code>```

c# asp mvc

```<code>public ActionResult Add(SomeModel model) {
  if (ModelState.IsValid) {
    if (true) {
      return Json(new { success = false, responseText = "Some error" }, JsonRequestBehavior.AllowGet);
    }
    return RedirectToAction("Details", new { id = id });
  }
  //gets called but it doesn't show validation.
  return View(model);
}

public ActionResult Details(int id) {
  //gets called but it doesn't show the view.
  return view(model);
}
</code>```

答:
Because you're posting your form with an Ajax POST and your in your success function you have alert(response.responseText), you are NOT going to receive a View.

What you need to do is in success function, take the response from Details action and place it inside an HTML element on the page. Like below:

```<code>        success: function (response) {
            $("#div").html(response);
        }
</code>```

On another note, since you're not using a standard FORM and your posting with JavaScript, you wont get built in validation the models provide.

Body:
What am trying to do is to post on form submit to a action and catch response and that works fine.Problem is when RedirectToAction gets called, it just stays on that same view(it doesn't redirect),or in case model is not valid, it doesn't show model validation. So i guess the problem is with url, but how can I correct it?

jQuery

$("form").on("submit", function (e) {
  e.preventDefault();
  var form = $(this);

  var formURL = form.attr("action");
  $.ajax({
    type: "POST",
    url: formURL,
    data: $(this).serialize(),
    success: function (response) {
      if (response !== null && response.success == false) {
        alert(response.responseText);
      }
    }
  });
});

c# asp mvc

public ActionResult Add(SomeModel model) {
  if (ModelState.IsValid) {
    if (true) {
      return Json(new { success = false, responseText = "Some error" }, JsonRequestBehavior.AllowGet);
    }
    return RedirectToAction("Details", new { id = id });
  }
  //gets called but it doesn't show validation.
  return View(model);
}

public ActionResult Details(int id) {
  //gets called but it doesn't show the view.
  return view(model);
}

Body:
Because you're posting your form with an Ajax POST and your in your success function you have alert(response.responseText), you are NOT going to receive a View.

What you need to do is in success function, take the response from Details action and place it inside an HTML element on the page. Like below:

        success: function (response) {
            $("#div").html(response);
        }

On another note, since you're not using a standard FORM and your posting with JavaScript, you wont get built in validation the models provide.


问:
what is the main differences between web service and wcf?
i know that web service can be host only in IIS but wcf can be host in IIS and both in win service too. but where is the actual main power lies in wcf for which developer choose wcf rather web service. please explain in detail. thanks</p>

答:
Windows Communication Foundation (WCF) has an ASP.NET compatibility mode option to enable WCF applications to be programmed and configured like ASP.NET Web services, and mimic their behavior.

Better performance, web-services uses XmlSerializer and WCF uses DataContractSerializer which is better in Performance as Compared to XmlSerializer.

In other words you can host plain old web-services using WCF. And you have more possibilities like using communication over Named Pipes/TCP/MSMQ etc.


问:
How to put multiple submit buttons in codeigniter
i have designed this form for login modal:

```<code><tr>
        <td></td>
        <td><?php echo form_submit('submit', ' Log In', 'class="btn btn-primary btn-lg btn-block"'); ?>
            <?php echo form_submit('forget', ' Forget Password ', 'class="btn btn-warning btn-lg btn-block"'); ?>
        </td>
 </tr>
</code>```

both of these buttons are doing same works how can I isolate which one has pressed?

thanks for everyon

答:
You can obtain this by using this HTML:

```<code><tr>
    <td></td>
    <td>
        <button type="submit" name="action" value="submit" class="btn btn-primary btn-lg btn-block"> Log In </button>
        <button type="submit" name="action" value="forget" class="btn btn-warning btn-lg btn-block"> Forget Password </button>
    </td>
</tr>
</code>```

Then use the POST data like this:

```<code>$action = $this->input->post('action');
if($action == 'submit') {
    // execute code to log in
}
if($action == 'forget') {
    // execute code to forget the password
}
</code>```

Body:
i have designed this form for login modal:

        <?php echo form_submit('submit', ' Log In', 'class="btn btn-primary btn-lg btn-block"'); ?>
            <?php echo form_submit('forget', ' Forget Password ', 'class="btn btn-warning btn-lg btn-block"'); ?>

both of these buttons are doing same works how can I isolate which one has pressed?

thanks for everyon

Body:
You can obtain this by using this HTML:

<tr>
    <td></td>
    <td>
        <button type="submit" name="action" value="submit" class="btn btn-primary btn-lg btn-block"> Log In </button>
        <button type="submit" name="action" value="forget" class="btn btn-warning btn-lg btn-block"> Forget Password </button>
    </td>
</tr>

Then use the POST data like this:

$action = $this->input->post('action');
if($action == 'submit') {
    // execute code to log in
}
if($action == 'forget') {
    // execute code to forget the password
}


问:
open xml excel Insert actual value in the placeholder
I have a cell that contains the placeholder "$$value" in the Excel sheet, the thing is that I need to replace the placeholder's actual value using Open XML and save it as separate workbook.

Here is the code that I tried...it is not replacing the actual value and also I'm unable to save the workbook.  I need to sort out this issue.

```<code>WorksheetPart worksheetPart = (WorksheetPart)myWorkbook.WorkbookPart.GetPartById(sheet.Id);

DocumentFormat.OpenXml.Spreadsheet.Worksheet worksheet = worksheetPart.Worksheet;

string _txt1 = "$$value";

if (_txt1.Contains("$$"))

{

     worksheet.InnerText.Replace(_txt1, "test");

}
</code>```

答:
Solution:

```<code> private static void ProcessTemplate(Stream template, Dictionary<string,string> toReplace)
        {
            using (var workbook = SpreadsheetDocument.Open(template, true, new OpenSettings { AutoSave = true }))
            {

                workbook.WorkbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;
                workbook.WorkbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;

                //Replace  SheetNames
                foreach (Sheet sheet in workbook.WorkbookPart.Workbook.Sheets)
                    foreach (var key in toReplace.Keys)
                        sheet.Name.Value = sheet.Name.Value.Replace(key, toReplace[key]);

                foreach (WorksheetPart wsheetpart in workbook.WorkbookPart.WorksheetParts)
                    foreach (SheetData sheetd in wsheetpart.Worksheet.Descendants<x.SheetData>())
                        foreach (Row r in wsheetpart.Worksheet.Descendants<x.Row>())
                            foreach (Cell c in r.Descendants<x.Cell>())
                                if (c.CellFormula != null)
                                {
                                    foreach (var key in toReplace.Keys)
                                        c.CellFormula.Text = c.CellFormula.Text.Replace(key, toReplace[key]);
                                }

                                // Replace shared strings
                                SharedStringTablePart sharedStringsPart = workbook.WorkbookPart.SharedStringTablePart;

                IEnumerable<x.Text> sharedStringTextElements = sharedStringsPart.SharedStringTable.Descendants<x.Text>();
                for(int i =0;i<toReplace.Keys.Count; i++)
                    DoReplace(sharedStringTextElements, toReplace);

                IEnumerable<x.Formula> sharedStringTextElementsF = sharedStringsPart.SharedStringTable.Descendants<x.Formula>();
                for (int i = 0; i < toReplace.Keys.Count; i++)
                    DoReplaceFormula(sharedStringTextElementsF, toReplace);

                // Replace inline strings
                IEnumerable<WorksheetPart> worksheetParts = workbook.GetPartsOfType<WorksheetPart>();
                foreach (var worksheet in worksheetParts)
                {

                    var allTextElements = worksheet.Worksheet.Descendants<x.Text>();
                    DoReplace(allTextElements, toReplace);

                    var allTextElements2 = worksheet.Worksheet.Descendants<x.Formula>();
                    DoReplaceFormula(allTextElements2, toReplace);

                }

            } // AutoSave enabled
        }
</code>```

Body:
I have a cell that contains the placeholder "$$value" in the Excel sheet, the thing is that I need to replace the placeholder's actual value using Open XML and save it as separate workbook.

Here is the code that I tried...it is not replacing the actual value and also I'm unable to save the workbook.  I need to sort out this issue.

WorksheetPart worksheetPart = (WorksheetPart)myWorkbook.WorkbookPart.GetPartById(sheet.Id);

DocumentFormat.OpenXml.Spreadsheet.Worksheet worksheet = worksheetPart.Worksheet;

string _txt1 = "$$value";

if (_txt1.Contains("$$"))

{

     worksheet.InnerText.Replace(_txt1, "test");

}

Body:
Solution:

 private static void ProcessTemplate(Stream template, Dictionary<string,string> toReplace)
        {
            using (var workbook = SpreadsheetDocument.Open(template, true, new OpenSettings { AutoSave = true }))
            {

                workbook.WorkbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;
                workbook.WorkbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;

                //Replace  SheetNames
                foreach (Sheet sheet in workbook.WorkbookPart.Workbook.Sheets)
                    foreach (var key in toReplace.Keys)
                        sheet.Name.Value = sheet.Name.Value.Replace(key, toReplace[key]);

                foreach (WorksheetPart wsheetpart in workbook.WorkbookPart.WorksheetParts)
                    foreach (SheetData sheetd in wsheetpart.Worksheet.Descendants<x.SheetData>())
                        foreach (Row r in wsheetpart.Worksheet.Descendants<x.Row>())
                            foreach (Cell c in r.Descendants<x.Cell>())
                                if (c.CellFormula != null)
                                {
                                    foreach (var key in toReplace.Keys)
                                        c.CellFormula.Text = c.CellFormula.Text.Replace(key, toReplace[key]);
                                }

                                // Replace shared strings
                                SharedStringTablePart sharedStringsPart = workbook.WorkbookPart.SharedStringTablePart;

                IEnumerable<x.Text> sharedStringTextElements = sharedStringsPart.SharedStringTable.Descendants<x.Text>();
                for(int i =0;i<toReplace.Keys.Count; i++)
                    DoReplace(sharedStringTextElements, toReplace);

                IEnumerable<x.Formula> sharedStringTextElementsF = sharedStringsPart.SharedStringTable.Descendants<x.Formula>();
                for (int i = 0; i < toReplace.Keys.Count; i++)
                    DoReplaceFormula(sharedStringTextElementsF, toReplace);

                // Replace inline strings
                IEnumerable<WorksheetPart> worksheetParts = workbook.GetPartsOfType<WorksheetPart>();
                foreach (var worksheet in worksheetParts)
                {

                    var allTextElements = worksheet.Worksheet.Descendants<x.Text>();
                    DoReplace(allTextElements, toReplace);

                    var allTextElements2 = worksheet.Worksheet.Descendants<x.Formula>();
                    DoReplaceFormula(allTextElements2, toReplace);

                }

            } // AutoSave enabled
        }


问:
Create a video or folder which will be available for particular time only
We want to develop one video or folder containing videos/images/content to be played on TV (not smart TV) in offline mode. But it should be played for some particular time only lets say a year. After that user need to contact admin or subscribe to view the same again. Is it possible to do the same and if yes what are the ways to achieve that?</p>

答:
Most DRM systems, such as Widevine, PlayReady and FPS support what you are asking for - offline playback with a limit on the duration.

When the client requests the license, the response it receives includes the decryption key and some metadata about the entitlements. This metadata allows the client be granted entitlements such as offline playback and allows a time limit be set for that capability.

As an example, look at the PlayReady license template information here and at the linked 'Compliance Rules for PlayReady Products' document which is publicly available online:

https://learn.microsoft.com/en-us/azure/media-services/media-services-playready-license-template-overview

ContentLicense: CC BY-SA 4.0


问:
How do I intersect two data.frames in R?

I have two tables that are in the data.frame structure. Table 1 contains a column of 200 gene IDs (letters and numbers) and Table 2 contains a list of 4,000 gene IDs (in rows) as well as 20 additional columns. I want to intersect these two tables and generate a new Table 3 that contains the 200 gene IDs as well as the associated information in the 20 columns.

table3 <- table1%n%table2

答:
You want something like

```<code>table3 <- merge(table1, table2, by.x="id", by.y="id", all.x=T, all.y=F)
</code>```

You might also be able to do subsetting with something like this:

```<code>table3 <- table2[table2$id %in% table1$id,]
</code>```

A reprex would have made this post more likely to get a good response, but you should have been able to find something to help you with a little searching. If these don't work because you have a unique problem no one has asked before, give is a reprex and we can try to give you alternative solutions.

edit: for a little more context, here's a similar question I replied to last week and here's a great post on understanding merges.

Body:
You want something like

table3 <- merge(table1, table2, by.x="id", by.y="id", all.x=T, all.y=F)

You might also be able to do subsetting with something like this:

table3 <- table2[table2$id %in% table1$id,]

A reprex would have made this post more likely to get a good response, but you should have been able to find something to help you with a little searching. If these don't work because you have a unique problem no one has asked before, give is a reprex and we can try to give you alternative solutions.

edit: for a little more context, here's a similar question I replied to last week and here's a great post on understanding merges.


问:
Random Forest classifier class_weight
I have an unbalanced dataset of 200000 descriptions being class 0, and something like 10000 being class 1. However, in my training dataset I have equal number of 'positive' and 'negative' samples, about 8000 each. So now I am confused about how I should properly use the "class_weight" option of the classifier. It seems that it works only if the number of the 'positive' and 'negative' samples in the training data is the same as in the whole dataset. In this case it would be 8000 'positive' and 160000 of 'negative' ones, which is not really feasible. And reducing the number of the 'positive' samples doesn't seem to be a good idea either. Or am I wrong?</p>

答:
Strictly speaking, from the point of view of your training set, you don't face a class imbalance issue, so you could very well leave class_weight to its default None value.

The real issue here and in imbalanced datasets in general (about which you don't provide any info) is if the cost of misclassification is the same for both classes. And this is a "businesss" decision (i.e. not a statistics/algorithmic one).

Usually, imbalanced datasets go hand-in-hand with problems with different misclassification costs; medical diagnosis is a textbook example here, since:

The datasets are almost by default imbalanced, since healthy people vastly outnumber infected ones

We would prefer a false alarm (misclassifying someone as having the disease, while he/she doesn't) rather than a missed detection (misclassifying an infected person as healthy, hence risking his/her life)

So, this is the actual problem you should be thinking about (i.e. even before building your training set).

If, for the business problem you are trying to address, there is not any difference between misclassifying a "0" for "1" and a "1" for "0", and given that your training set is balanced, you can proceed without worrying about assigning different class weights...

Title: Random Forest classifier class_weight


答:
I recommend the dplyr package. It works more intuitively than merge in my opinion.

you can just type:

```<code>table3 <- left_join(table1, table2, by = "unique_id")
</code>```

Title: How do I intersect two data.frames in R?

Body:
I have two tables that are in the data.frame structure. Table 1 contains a column of 200 gene IDs (letters and numbers) and Table 2 contains a list of 4,000 gene IDs (in rows) as well as 20 additional columns. I want to intersect these two tables and generate a new Table 3 that contains the 200 gene IDs as well as the associated information in the 20 columns.

table3 <- table1%n%table2

Body:
I recommend the dplyr package. It works more intuitively than merge in my opinion.

you can just type:

table3 <- left_join(table1, table2, by = "unique_id")


问:
What happened to WINVER and _WIN32_WINNT guards in windows.h?
In Using the Windows Headers, Microsoft claim that _WIN32_WINNT and NTDDI_VERSION can be used to prevent defining API functions for newer versions of Windows.  However, this does not seem to be universally true.

For example, CancelSynchronousIo requires Vista or later, but it is not guarded at all in the two versions of the windows SDK that I have (v6.0 and v7.1).

```<code>WINBASEAPI
BOOL
WINAPI
CancelIoEx(
    __in HANDLE hFile,
    __in_opt LPOVERLAPPED lpOverlapped
    );
</code>```

Meanwhile, GetVolumeInformationByHandleW, which also requires Vista, is guarded as you might expect:

```<code>#if(_WIN32_WINNT >= 0x0600)
WINBASEAPI
BOOL
WINAPI
GetVolumeInformationByHandleW(
    __in      HANDLE hFile,
    __out_ecount_opt(nVolumeNameSize) LPWSTR lpVolumeNameBuffer,
    __in      DWORD nVolumeNameSize,
    __out_opt LPDWORD lpVolumeSerialNumber,
    __out_opt LPDWORD lpMaximumComponentLength,
    __out_opt LPDWORD lpFileSystemFlags,
    __out_ecount_opt(nFileSystemNameSize) LPWSTR lpFileSystemNameBuffer,
    __in      DWORD nFileSystemNameSize
    );
#endif /* _WIN32_WINNT >=  0x0600 */
</code>```

Is this sort of thing just a bug?  Are _WIN32_WINT guards useless?  Can anyone recommend a reliable way to determine which version of Windows introduced which API functions?

Edited to add:

Here is a test.  foo.h contains:

```<code>#include <windows.h>
</code>```

Then run:

```<code>cl /E /D_WIN32_WINNT=0x0501 /DNTDDI_VERSION=0x05010000 foo.h | grep CancelSynchronousIo
</code>```

My expectation is that I'd get no output, but instead CancelSynchronousIo is defined.

答: It's a bug.  Reference examples are here and here.  Some secondary evidence that the Longhorn project was indeed a very troubled one.  The Windows team doesn't take feedback like DevDiv does, hard to get bugs fixed.  You can leave an annotation at the bottom of the MSDN Library page.</p>

Body:
In Using the Windows Headers, Microsoft claim that _WIN32_WINNT and NTDDI_VERSION can be used to prevent defining API functions for newer versions of Windows.  However, this does not seem to be universally true.

For example, CancelSynchronousIo requires Vista or later, but it is not guarded at all in the two versions of the windows SDK that I have (v6.0 and v7.1).

WINBASEAPI
BOOL
WINAPI
CancelIoEx(
    __in HANDLE hFile,
    __in_opt LPOVERLAPPED lpOverlapped
    );

Meanwhile, GetVolumeInformationByHandleW, which also requires Vista, is guarded as you might expect:

#if(_WIN32_WINNT >= 0x0600)
WINBASEAPI
BOOL
WINAPI
GetVolumeInformationByHandleW(
    __in      HANDLE hFile,
    __out_ecount_opt(nVolumeNameSize) LPWSTR lpVolumeNameBuffer,
    __in      DWORD nVolumeNameSize,
    __out_opt LPDWORD lpVolumeSerialNumber,
    __out_opt LPDWORD lpMaximumComponentLength,
    __out_opt LPDWORD lpFileSystemFlags,
    __out_ecount_opt(nFileSystemNameSize) LPWSTR lpFileSystemNameBuffer,
    __in      DWORD nFileSystemNameSize
    );
#endif /* _WIN32_WINNT >=  0x0600 */

Is this sort of thing just a bug?  Are _WIN32_WINT guards useless?  Can anyone recommend a reliable way to determine which version of Windows introduced which API functions?

Edited to add:

Here is a test.  foo.h contains:

#include <windows.h>

Then run:

cl /E /D_WIN32_WINNT=0x0501 /DNTDDI_VERSION=0x05010000 foo.h | grep CancelSynchronousIo

My expectation is that I'd get no output, but instead CancelSynchronousIo is defined.


问:
Spark job just hangs with large data
I am trying to query from s3 (15 days of data). I tried querying them separately (each day) it works fine. It works fine for 14 days as well. But when I query 15 days the job keeps running forever (hangs) and the task # is not updating.

My settings :

I am using 51 node cluster r3.4x large with dynamic allocation and maximum resource turned on.

All I am doing is =

```<code>val startTime="2017-11-21T08:00:00Z"
val endTime="2017-12-05T08:00:00Z"

val start = DateUtils.getLocalTimeStamp( startTime )
val end = DateUtils.getLocalTimeStamp( endTime )

val days: Int = Days.daysBetween( start, end ).getDays

val files: Seq[String] = (0 to days)
      .map( start.plusDays )
      .map( d => s"$input_path${DateTimeFormat.forPattern( "yyyy/MM/dd" ).print( d )}/*/*" )

sqlSession.sparkContext.textFile( files.mkString( "," ) ).count
</code>```

When I run the same with 14 days, I got 197337380 (count) and I ran the 15th day separately and got 27676788. But when I query 15 days total the job hangs

Update :

The job works fine with :

```<code>  var df = sqlSession.createDataFrame(sc.emptyRDD[Row], schema)

    for(n <- files ){
      val tempDF = sqlSession.read.schema( schema ).json(n)
      df = df(tempDF)
    }

df.count
</code>```

But can some one explain why it works now but not before ?

UPDATE : After setting mapreduce.input.fileinputformat.split.minsize to 256 GB it works fine now.

答:
You should be increasing the executor memory and # executors, If the data is huge try increasing the Driver memory.

My suggestion is to not use the dynamic resource allocation and let it run and see if it still hangs or not (Please note that spark job can consume entire cluster resources and make other applications starve for resources try this approach when no jobs are running). if it doesn't hang that means you should play with the resource allocation, then start hardcoding the resources and keep increasing resources so that you can find the best resource allocation you can possibly use.

Below links can help you understand the resource allocation and optimization of resources.

http://site.clairvoyantsoft.com/understanding-resource-allocation-configurations-spark-application/

https://community.hortonworks.com/articles/42803/spark-on-yarn-executor-resource-allocation-optimiz.html

Title: Spark job just hangs with large data

Body:
I am trying to query from s3 (15 days of data). I tried querying them separately (each day) it works fine. It works fine for 14 days as well. But when I query 15 days the job keeps running forever (hangs) and the task # is not updating.

My settings :

I am using 51 node cluster r3.4x large with dynamic allocation and maximum resource turned on.

All I am doing is =

val startTime="2017-11-21T08:00:00Z"
val endTime="2017-12-05T08:00:00Z"

val start = DateUtils.getLocalTimeStamp( startTime )
val end = DateUtils.getLocalTimeStamp( endTime )

val days: Int = Days.daysBetween( start, end ).getDays

val files: Seq[String] = (0 to days)
      .map( start.plusDays )
      .map( d => s"$input_path${DateTimeFormat.forPattern( "yyyy/MM/dd" ).print( d )}/*/*" )

sqlSession.sparkContext.textFile( files.mkString( "," ) ).count

When I run the same with 14 days, I got 197337380 (count) and I ran the 15th day separately and got 27676788. But when I query 15 days total the job hangs

Update :

The job works fine with :

  var df = sqlSession.createDataFrame(sc.emptyRDD[Row], schema)

    for(n <- files ){
      val tempDF = sqlSession.read.schema( schema ).json(n)
      df = df(tempDF)
    }

df.count

But can some one explain why it works now but not before ?

UPDATE : After setting mapreduce.input.fileinputformat.split.minsize to 256 GB it works fine now.


问:
Spark transformation that withdraws objects from a ListBuffer in a RDD[ListBuffer] and creates new entries in the RDD
So I have an RDD which is RDD[ListBuffer[(Array[String], Long)]]. For simplicity we can just call it RDD[X], where X is a list of some variables. X is a list of obj objects, X[obj].

The idea is that I want a function which takes RDD[X] as input and outputs a new RDD[X], a transformation. This transformation will create new X lists by taking out obj from one X and creating a new one, and like "appending" it to the RDD.

I haven't found anything in Spark that supports this directly. Right now the only solution I can think of is by performing collect() and managing most of this at the driver but this is obviously not good. Any ideas?

Basically something like this:

```<code>val data = RDD[ListBuffer[(Array[String], Long)]]
// some transformation that calls some function
// what will happen is some (Array[String], Long) will be moved into an entirely new ListBuffer in outData while some may be completely removed
val outData = RDD[ListBuffer[(Array[String], Long)]]
</code>```

Lets say if we have a starting RDD that contains one ListBuffer of 7 elements:

Element1 (in ListBuffer1)

Element2 (in ListBuffer1)

Element3 (in ListBuffer1)

Element4 (in ListBuffer1)

Element5 (in ListBuffer1)

Element6 (in ListBuffer1)

Element7 (in ListBuffer1)

And after the transformation the RDD will have the following contents:

Element1 (in ListBuffer1)

Element2 (in ListBuffer1)

Element4 (in ListBuffer2)

Element5 (in ListBuffer2)

Element6 (in ListBuffer2)

Some elements have been moved to a new ListBuffer in the RDD while two elements were completely removed.

I am using Spark 1.6.0.

答:
You can do transformation on each ListBuffer to collection of ListBuffer let say List of ListBuffer then do flatMap on RDD.

Below is the dummy POC.

```<code>val rdd = spark.sparkContext.parallelize(Seq(List(1,2,3,4), List(11,22,76,44)))
val flattenRdd = rdd.map(s => List(s.filter(_%2 == 1), s.filter(_%2 == 0)))
    .flatMap(s => s)
flattenRdd.collect().foreach(s => println(s.mkString(",")))

1,3
2,4
11
22,76,44
</code>```

Body:
So I have an RDD which is RDD[ListBuffer[(Array[String], Long)]]. For simplicity we can just call it RDD[X], where X is a list of some variables. X is a list of obj objects, X[obj].

The idea is that I want a function which takes RDD[X] as input and outputs a new RDD[X], a transformation. This transformation will create new X lists by taking out obj from one X and creating a new one, and like "appending" it to the RDD.

I haven't found anything in Spark that supports this directly. Right now the only solution I can think of is by performing collect() and managing most of this at the driver but this is obviously not good. Any ideas?

Basically something like this:

val data = RDD[ListBuffer[(Array[String], Long)]]
// some transformation that calls some function
// what will happen is some (Array[String], Long) will be moved into an entirely new ListBuffer in outData while some may be completely removed
val outData = RDD[ListBuffer[(Array[String], Long)]]

Lets say if we have a starting RDD that contains one ListBuffer of 7 elements:

Element1 (in ListBuffer1)

Element2 (in ListBuffer1)

Element3 (in ListBuffer1)

Element4 (in ListBuffer1)

Element5 (in ListBuffer1)

Element6 (in ListBuffer1)

Element7 (in ListBuffer1)

And after the transformation the RDD will have the following contents:

Element1 (in ListBuffer1)

Element2 (in ListBuffer1)

Element4 (in ListBuffer2)

Element5 (in ListBuffer2)

Element6 (in ListBuffer2)

Some elements have been moved to a new ListBuffer in the RDD while two elements were completely removed.

I am using Spark 1.6.0.

Body:
You can do transformation on each ListBuffer to collection of ListBuffer let say List of ListBuffer then do flatMap on RDD.

Below is the dummy POC.

val rdd = spark.sparkContext.parallelize(Seq(List(1,2,3,4), List(11,22,76,44)))
val flattenRdd = rdd.map(s => List(s.filter(_%2 == 1), s.filter(_%2 == 0)))
    .flatMap(s => s)
flattenRdd.collect().foreach(s => println(s.mkString(",")))

1,3
2,4
11
22,76,44


问:
How to evenly distribute TextView on discrete seekbar ticks in Android?
How to evenly distribute texts above each tick mark in Discrete Seekbar?

This is how I am doing:

```<code> <SeekBar
            android:id="@+id/sb_task_detail_status"
            style="@style/Widget.AppCompat.SeekBar.Discrete"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:max="4"
            android:progress="0" />

        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:stretchColumns="*"
            android:layout_above="@+id/sb_task_detail_status"
            android:layout_alignStart="@+id/sb_task_detail_status">

            <TableRow
                android:id="@+id/statusRow"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <TextView
                    android:id="@+id/tv_task_status_newly_developed"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_column="1"
                    android:textColor="@android:color/white"
                    android:textSize="10sp"
                    android:text="Newly Developed"/>
                <TextView
                    android:id="@+id/tv_task_status_developed"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_column="2"
                    android:textSize="10sp"
                    android:textColor="@android:color/white"
                    android:text="Developed"/>
                <TextView
                    android:id="@+id/tv_task_status_in_progress"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_column="3"
                    android:textSize="10sp"
                    android:textColor="@android:color/white"
                    android:text="In Progress"/>
                <TextView
                    android:id="@+id/tv_task_status_completed"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_column="4"
                    android:textSize="10sp"
                    android:textColor="@android:color/white"
                    android:text="Completed"/>
                <TextView
                    android:id="@+id/tv_task_status_submitted"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_column="5"
                    android:textSize="10sp"
                    android:textColor="@android:color/white"
                    android:text="Submitted"/>
            </TableRow>

        </TableLayout>
</code>```

And this is the result I got:

Note that only one TextView will be visible at a time depending on a progress.

答:
Have you tried using layout_width="0dp" and assign similar weights? Like this:

```<code>android:layout_width="0dp"
android:layout_weight="1"
</code>```

for each TextView

EDIT
I used this xml and it splits the space evenly

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<SeekBar
    android:id="@+id/sb_task_detail_status"
    style="@style/Widget.AppCompat.SeekBar.Discrete"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:max="4"
    android:progress="0" />

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="*"
    android:layout_above="@+id/sb_task_detail_status"
    android:layout_alignStart="@+id/sb_task_detail_status">

    <TableRow
        android:id="@+id/statusRow"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/tv_task_status_newly_developed"
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_column="0"
            android:textColor="@android:color/white"
            android:textSize="10sp"
            android:text="Newly Developed"/>
        <TextView
            android:id="@+id/tv_task_status_developed"
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_column="1"
            android:textSize="10sp"
            android:textColor="@android:color/white"
            android:text="Developed"/>
        <TextView
            android:id="@+id/tv_task_status_in_progress"
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_column="2"
            android:textSize="10sp"
            android:textColor="@android:color/white"
            android:text="In Progress"/>
        <TextView
            android:id="@+id/tv_task_status_completed"
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_column="3"
            android:textSize="10sp"
            android:textColor="@android:color/white"
            android:text="Completed"/>
        <TextView
            android:id="@+id/tv_task_status_submitted"
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_column="4"
            android:textSize="10sp"
            android:textColor="@android:color/white"
            android:text="Submitted"/>
    </TableRow>

</TableLayout>
</code>```

EDIT 2
For anyone who wants to distribute evenly Texviews on discrete seekbar, here's a nice tutorial that explains all the steps to achieve it.

Body:
How to evenly distribute texts above each tick mark in Discrete Seekbar?

This is how I am doing:

 <SeekBar
            android:id="@+id/sb_task_detail_status"
            style="@style/Widget.AppCompat.SeekBar.Discrete"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:max="4"
            android:progress="0" />

        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:stretchColumns="*"
            android:layout_above="@+id/sb_task_detail_status"
            android:layout_alignStart="@+id/sb_task_detail_status">

            <TableRow
                android:id="@+id/statusRow"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <TextView
                    android:id="@+id/tv_task_status_newly_developed"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_column="1"
                    android:textColor="@android:color/white"
                    android:textSize="10sp"
                    android:text="Newly Developed"/>
                <TextView
                    android:id="@+id/tv_task_status_developed"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_column="2"
                    android:textSize="10sp"
                    android:textColor="@android:color/white"
                    android:text="Developed"/>
                <TextView
                    android:id="@+id/tv_task_status_in_progress"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_column="3"
                    android:textSize="10sp"
                    android:textColor="@android:color/white"
                    android:text="In Progress"/>
                <TextView
                    android:id="@+id/tv_task_status_completed"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_column="4"
                    android:textSize="10sp"
                    android:textColor="@android:color/white"
                    android:text="Completed"/>
                <TextView
                    android:id="@+id/tv_task_status_submitted"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_column="5"
                    android:textSize="10sp"
                    android:textColor="@android:color/white"
                    android:text="Submitted"/>
            </TableRow>

        </TableLayout>

And this is the result I got:

Note that only one TextView will be visible at a time depending on a progress.

Body:
Have you tried using layout_width="0dp" and assign similar weights? Like this:

android:layout_width="0dp"
android:layout_weight="1"

for each TextView

EDIT
I used this xml and it splits the space evenly

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<SeekBar
    android:id="@+id/sb_task_detail_status"
    style="@style/Widget.AppCompat.SeekBar.Discrete"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:max="4"
    android:progress="0" />

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="*"
    android:layout_above="@+id/sb_task_detail_status"
    android:layout_alignStart="@+id/sb_task_detail_status">

    <TableRow
        android:id="@+id/statusRow"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/tv_task_status_newly_developed"
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_column="0"
            android:textColor="@android:color/white"
            android:textSize="10sp"
            android:text="Newly Developed"/>
        <TextView
            android:id="@+id/tv_task_status_developed"
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_column="1"
            android:textSize="10sp"
            android:textColor="@android:color/white"
            android:text="Developed"/>
        <TextView
            android:id="@+id/tv_task_status_in_progress"
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_column="2"
            android:textSize="10sp"
            android:textColor="@android:color/white"
            android:text="In Progress"/>
        <TextView
            android:id="@+id/tv_task_status_completed"
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_column="3"
            android:textSize="10sp"
            android:textColor="@android:color/white"
            android:text="Completed"/>
        <TextView
            android:id="@+id/tv_task_status_submitted"
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_column="4"
            android:textSize="10sp"
            android:textColor="@android:color/white"
            android:text="Submitted"/>
    </TableRow>

</TableLayout>

EDIT 2
For anyone who wants to distribute evenly Texviews on discrete seekbar, here's a nice tutorial that explains all the steps to achieve it.


问:
Disabled TextArea Resize stops working when there is Overflow-Y
If a textarea is disabled and has overflow-y it no longer lets you resize.
If you add overflow-y to hidden and keep it disabled it does let you resize.

Any way to have a disabled textarea with scrollable overflow-y and still have it resizable?

Fiddle with just textarea:
https://jsfiddle.net/bs5sakus/ (not resizable)

```<code><textarea disabled> TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST </textarea>
</code>```

Fiddle with overflow-y hidden: https://jsfiddle.net/30o3tmap/ (resizable)

答:
Possible solution is to use readonly instead of disabled and style it to look disabled. This also allows users to highlight and copy the text in the textarea but not modify it

https://jsfiddle.net/xynLfqag/1/

```<code><textarea readonly> TEST </textarea>
</code>```

jQuery UI resizable will work but using the SE grabber and scrollbars cause overlapping

https://jqueryui.com/resizable/

Body:
If a textarea is disabled and has overflow-y it no longer lets you resize.
If you add overflow-y to hidden and keep it disabled it does let you resize.

Any way to have a disabled textarea with scrollable overflow-y and still have it resizable?

Fiddle with just textarea:
https://jsfiddle.net/bs5sakus/ (not resizable)

<textarea disabled> TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST </textarea>

Fiddle with overflow-y hidden: https://jsfiddle.net/30o3tmap/ (resizable)

Body:
Possible solution is to use readonly instead of disabled and style it to look disabled. This also allows users to highlight and copy the text in the textarea but not modify it

https://jsfiddle.net/xynLfqag/1/

<textarea readonly> TEST </textarea>

jQuery UI resizable will work but using the SE grabber and scrollbars cause overlapping

https://jqueryui.com/resizable/


问:
MYSQL Table design help
I have  a table called teams (id, name, ...)   I have a table called divisions (id, name, ......)   I want the diviosn to hold the teams.id  for each team in a divsion  and Teams can be in more than one divsion.  How do I set this up?</p>

答: This is the standard approach for a many-to-many relationship: Make a separate table teams_divisons (or divisions_teams) that contains two columns team_id and division_id.</p>

Title: MYSQL Table design help


问:
Two Ajax calls only meet one condition at a time
I have the following script that sends a POST of my select option to a url called requestaccess.  This works great when using only one of the two, but when I change the other field the result of the POST is None for the first and correct for the second and vice-versa.

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title ="accesslevelid" class="form-control" id="accesslevelid" onclick="accesslevelid">
            <option value=""> Please select your access level  </option>
            <option value="7"> Facility  </option>
            <option value="5"> Division  </option>
            <option value = "3"> Corporate  </option>
            <option value = "6"> Market  </option>
            <option value = "4"> Group  </option>
</select>
<script>
$(document).ready(function () {
    $('#accesslevelid').on('click', function () {
        var accesslevelid = $(this).val();
        $.ajax({ url: "{% url 'requestaccess' %}",
                headers: { 'X-CSRFToken': '{{ csrf_token }}' },
                data: {
                  accesslevelid: accesslevelid,
                },
                type: 'POST',
                success: function (result) {
                  ;
                },
              });
      });
  });
</script>
        </div>
        <div class="col">

          <label for="phi"><h3>PHI</h3></label>

          <select class="form-control" id="phi" title = "phi" onclick="phi">
            <option value = ""> Please select if you need access to PHI data </option>
            <option value = "0"> No  </option>
            <option value = "1"> Yes  </option>

          </select>
          <script>
          $(document).ready(function () {
              $('#phi').on('click', function () {
                  var phi = $(this).val();
                  $.ajax({ url: "{% url 'requestaccess' %}",
                          headers: { 'X-CSRFToken': '{{ csrf_token }}' },
                          data: {
                            phi: phi,
                          },
                          type: 'POST',
                          success: function (result) {
                            ;
                          },
                        });
                });
            });
          </script>
</code>```

My view gets the POST value with the following:

```<code>selectedaccesslevel = request.POST.get('accesslevelid')
print(selectedaccesslevel)
selectedphi = request.POST.get('phi')
print(selectedphi)
</code>```

However, my print either displays as:

```<code>None
1 or 2

or

7, 5, 3, 6, 4
None.
</code>```

My desired results are for it to display as :

```<code>7, 5, 3, 6, or 4
1 or 2
</code>```

答:
Maybe just write a single click function for both selects, ie each time you click on either of the selects you fetch both the select values and pass it to the view, something like this:

```<code> $(document).ready(function () {
          $('.my_select').on('click', function () {
              var phi = $('#phi').val();
              var accesslevelid = $('#accesslevelid ').val();
              $.ajax({ url: "{% url 'requestaccess' %}",
                      headers: { 'X-CSRFToken': '{{ csrf_token }}' },
                      data: {
                        phi: phi,
                        accesslevelid: accesslevelid
                      },
                      type: 'POST',
                      success: function (result) {
                        ;
                      },
                    });
            });
        });
</code>```

do not forget to add  class name 'my_select' to both your selects.

```<code><select class="form-control my_select" id="phi" title = "phi" >
<select title ="accesslevelid" class="form-control my_select" id="accesslevelid">
</code>```

Body:
I have the following script that sends a POST of my select option to a url called requestaccess.  This works great when using only one of the two, but when I change the other field the result of the POST is None for the first and correct for the second and vice-versa.

<select title ="accesslevelid" class="form-control" id="accesslevelid" onclick="accesslevelid">
            <option value=""> Please select your access level  </option>
            <option value="7"> Facility  </option>
            <option value="5"> Division  </option>
            <option value = "3"> Corporate  </option>
            <option value = "6"> Market  </option>
            <option value = "4"> Group  </option>
</select>

PHI

          <select class="form-control" id="phi" title = "phi" onclick="phi">
            <option value = ""> Please select if you need access to PHI data </option>
            <option value = "0"> No  </option>
            <option value = "1"> Yes  </option>

          </select>

My view gets the POST value with the following:

selectedaccesslevel = request.POST.get('accesslevelid')
print(selectedaccesslevel)
selectedphi = request.POST.get('phi')
print(selectedphi)

However, my print either displays as:

None
1 or 2

or

7, 5, 3, 6, 4
None.

My desired results are for it to display as :

7, 5, 3, 6, or 4
1 or 2

Body:
Maybe just write a single click function for both selects, ie each time you click on either of the selects you fetch both the select values and pass it to the view, something like this:

 $(document).ready(function () {
          $('.my_select').on('click', function () {
              var phi = $('#phi').val();
              var accesslevelid = $('#accesslevelid ').val();
              $.ajax({ url: "{% url 'requestaccess' %}",
                      headers: { 'X-CSRFToken': '{{ csrf_token }}' },
                      data: {
                        phi: phi,
                        accesslevelid: accesslevelid
                      },
                      type: 'POST',
                      success: function (result) {
                        ;
                      },
                    });
            });
        });

do not forget to add  class name 'my_select' to both your selects.

<select class="form-control my_select" id="phi" title = "phi" >
<select title ="accesslevelid" class="form-control my_select" id="accesslevelid">


问:
Add additional individual IAM policy to serverless yaml to extend managed policy
I have a managed policy that allows or read access to a kinesis stream (AWSLambdaKinesisExecutionRole), I am trying to add additional permissions to also allow write access to PutRecord and PutRecords on to the kinesis stream.

My serverless.yml currently looks like -

```<code>resources:
  Resources:
    kinesisFullAccessRole:
      Type: AWS::IAM::Role
      Properties:
        RoleName: kinesis-full-access-role
        AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Principal:
                Service:
                  - lambda.amazonaws.com
              Action: sts:AssumeRole
        ManagedPolicyArns:
          - arn:aws:iam::aws:policy/service-role/AWSLambdaKinesisExecutionRole
        Policies:
          - PolicyName: kinesis-write-access
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: Allow
                  Action:
                    - kinesis:PutRecord
                    - kinesis:PutRecords
                  Resource:
                    - "arn:<some_arn>:stream/inbound-message-stream-dev"
</code>```

I am still getting a is not authorized to perform: kinesis:PutRecord on resource error. What am I doing wrong?

答:
If your serverless is creating the IAM role by it self you should had that to the iamRoleStatements like shown here

but it could be easier to create an IAM role in aws console and manage that yourself, and use it like here

Body:
I have a managed policy that allows or read access to a kinesis stream (AWSLambdaKinesisExecutionRole), I am trying to add additional permissions to also allow write access to PutRecord and PutRecords on to the kinesis stream.

My serverless.yml currently looks like -

resources:
  Resources:
    kinesisFullAccessRole:
      Type: AWS::IAM::Role
      Properties:
        RoleName: kinesis-full-access-role
        AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Principal:
                Service:
                  - lambda.amazonaws.com
              Action: sts:AssumeRole
        ManagedPolicyArns:
          - arn:aws:iam::aws:policy/service-role/AWSLambdaKinesisExecutionRole
        Policies:
          - PolicyName: kinesis-write-access
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: Allow
                  Action:
                    - kinesis:PutRecord
                    - kinesis:PutRecords
                  Resource:
                    - "arn:<some_arn>:stream/inbound-message-stream-dev"

I am still getting a is not authorized to perform: kinesis:PutRecord on resource error. What am I doing wrong?


问:
C# Selenium, how to execute javascript on web driver while page is still loading
So I have one page which takes a really long time to load due to some background stuff it loads. I want to be able to interact with it as soon as the DOM is loaded and readyState is 'interactive'. Basically I just want to click on a link to take me away from this page as I don't need for the whole thing to load before I move on. However, it seems like I can't run Javascript on the driver until the page is loaded; what happens is that the ExecuteJavascript function times out on me as well.

```<code>try
{
    element.Click(); //BrowserCommandTimeout was set to 10 seconds
}
catch (Timeout e)
{
     string state = driver.ExecuteJs("return document.readyState").ToString(); //Also times out after 10 seconds

     while ((state != "complete") && state != "interactive")
     {
          Utilities.Sleep(2000);
     }
}
</code>```

Anybody have any idea how to approach fixing this problem?

答:
Just this </p>

```<code>var waitForElement = new WebDriverWait(_driver, TimeSpan.FromSeconds(5));
waitForElement.Until(driver =>_driver.ExecuteJavaScript<string>("return document.readyState").ToString() == "complete");
</code>```

Body:
So I have one page which takes a really long time to load due to some background stuff it loads. I want to be able to interact with it as soon as the DOM is loaded and readyState is 'interactive'. Basically I just want to click on a link to take me away from this page as I don't need for the whole thing to load before I move on. However, it seems like I can't run Javascript on the driver until the page is loaded; what happens is that the ExecuteJavascript function times out on me as well.

try
{
    element.Click(); //BrowserCommandTimeout was set to 10 seconds
}
catch (Timeout e)
{
     string state = driver.ExecuteJs("return document.readyState").ToString(); //Also times out after 10 seconds

     while ((state != "complete") && state != "interactive")
     {
          Utilities.Sleep(2000);
     }
}

Anybody have any idea how to approach fixing this problem?

Body:
Just this

var waitForElement = new WebDriverWait(_driver, TimeSpan.FromSeconds(5));
waitForElement.Until(driver =>_driver.ExecuteJavaScript<string>("return document.readyState").ToString() == "complete");


问:
How to create a random decimal between 0 and 1 vb.net
I need a random decimal between 0 and 1 in VB.NET

```<code>Dim value As Decimal = CInt(Int((1 * Rnd()) + 0))
</code>```

I'm trying this but it's just saving as 0. It's definitely something I'm doing wrong but I'm not sure yet.

It should be between 0 and 1, but it's just returning 0.

答:
CInt will convert your Decimal value to an Integer value. Besides, Rnd is so 15 years ago, use Random.NextDouble instead:

```<code>Dim r As New Random() 'Should be declared at the topmost level
Dim value As Double = r.NextDouble()
</code>```

Fiddle: Live Demo

Body:
I need a random decimal between 0 and 1 in VB.NET

Dim value As Decimal = CInt(Int((1 * Rnd()) + 0))

I'm trying this but it's just saving as 0. It's definitely something I'm doing wrong but I'm not sure yet.

It should be between 0 and 1, but it's just returning 0.

Body:
CInt will convert your Decimal value to an Integer value. Besides, Rnd is so 15 years ago, use Random.NextDouble instead:

Dim r As New Random() 'Should be declared at the topmost level
Dim value As Double = r.NextDouble()

Fiddle: Live Demo


问:
Correctly inserting and/or updating many datasets to MongoDB (using mongoose)?
So from time to time I get new exports of a cities database of POIs and info about them and I want to have all that data in my MongoDB with a Loopback-API on it. Therefore I reduce the data to my desired structure and try to import it.

For the first time I receive such an export, I can simply insert the data with insertMany().

When I get a new export, it means that it includes updated POIs which I actually want my existing POIs to be replaced with that new data. So I thought I'd use updateMany() but I could'nt figure out how I'd do that in my case.

Here's what I have so far:

```<code>const fs = require('fs');
const mongoose = require('mongoose');

const data = JSON.parse(fs.readFileSync('data.json', 'utf8'));

// Connect to database
mongoose.connect('mongodb://localhost/test', {
  useMongoClient: true
}, (err) => {
  if (err) console.log('Error', err);
});

// Define schema
let poiSchema = new mongoose.Schema({
  _id:          Number,
  name:         String,
  geo:          String,
  street:       String,
  housenumber:  String,
  phone:        String,
  website:      String,
  email:        String,
  category:     String
});

// Set model
let poi = mongoose.model('poi', poiSchema);

// Generate specified data from given export
let reducedData = data['ogr:FeatureCollection']['gml:featureMember'].reduce((endData, iteratedItem) => {
  endData = endData.length > 0 ? endData : [];

  endData.push({
    _id:          iteratedItem['service']['fieldX'],
    name:         iteratedItem['service']['fieldX'],
    geo:          iteratedItem['service']['fieldX']['fieldY']['fieldZ'],
    street:       iteratedItem['service']['fieldX'],
    housenumber:  iteratedItem['service']['fieldX'],
    phone:        iteratedItem['service']['fieldX'],
    website:      iteratedItem['service']['fieldX'],
    email:        iteratedItem['service']['fieldX'],
    category:     iteratedItem['service']['fieldX']
  });

  return endData;
}, []);

//
// HERE: ?!?!? Insert/update reduced data in MongoDB collection ?!?!?
//

mongoose.disconnect();
</code>```

So I just want to update everything that has changed.

Of course if I leave it to insertMany() it fails due to dup key.

答:
For the second time, use mongo's update command with upsert set to true.

```<code>db.collection.update(query, update, options)
</code>```

In the query pass the _id ,in update pass the object and in option set upsert to true. This will update the document if it exists creates a new document if that doesn't exist.

Body:
So from time to time I get new exports of a cities database of POIs and info about them and I want to have all that data in my MongoDB with a Loopback-API on it. Therefore I reduce the data to my desired structure and try to import it.

For the first time I receive such an export, I can simply insert the data with insertMany().

When I get a new export, it means that it includes updated POIs which I actually want my existing POIs to be replaced with that new data. So I thought I'd use updateMany() but I could'nt figure out how I'd do that in my case.

Here's what I have so far:

const fs = require('fs');
const mongoose = require('mongoose');

const data = JSON.parse(fs.readFileSync('data.json', 'utf8'));

// Connect to database
mongoose.connect('mongodb://localhost/test', {
  useMongoClient: true
}, (err) => {
  if (err) console.log('Error', err);
});

// Define schema
let poiSchema = new mongoose.Schema({
  _id:          Number,
  name:         String,
  geo:          String,
  street:       String,
  housenumber:  String,
  phone:        String,
  website:      String,
  email:        String,
  category:     String
});

// Set model
let poi = mongoose.model('poi', poiSchema);

// Generate specified data from given export
let reducedData = data['ogr:FeatureCollection']['gml:featureMember'].reduce((endData, iteratedItem) => {
  endData = endData.length > 0 ? endData : [];

  endData.push({
    _id:          iteratedItem['service']['fieldX'],
    name:         iteratedItem['service']['fieldX'],
    geo:          iteratedItem['service']['fieldX']['fieldY']['fieldZ'],
    street:       iteratedItem['service']['fieldX'],
    housenumber:  iteratedItem['service']['fieldX'],
    phone:        iteratedItem['service']['fieldX'],
    website:      iteratedItem['service']['fieldX'],
    email:        iteratedItem['service']['fieldX'],
    category:     iteratedItem['service']['fieldX']
  });

  return endData;
}, []);

//
// HERE: ?!?!? Insert/update reduced data in MongoDB collection ?!?!?
//

mongoose.disconnect();

So I just want to update everything that has changed.

Of course if I leave it to insertMany() it fails due to dup key.

Body:
For the second time, use mongo's update command with upsert set to true.

db.collection.update(query, update, options)

In the query pass the _id ,in update pass the object and in option set upsert to true. This will update the document if it exists creates a new document if that doesn't exist.


问:
ViewModel cannot be instantiated in an Activity
I am trying to instantiate one ViewModel to use across all of my Activity(s).

```<code>public class LaunchActivity extends Activity {
    private Controller control;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_launch);
         control = ViewModelProviders.of(this).get(Controller.class);
    }
}
</code>```

but I got an error at control = ViewModelProviders.of(this) <-- stating that it cannot resolve of(this), but based on the example here by Android Developer on Implementing ViewModel; a class that extends ViewModel should be able to be instantiated on Activity, am I right?

If what I am doing is wrong, how should I instantiate a ViewModel object for my Activity(s)? Do I have to create n number of Activity(s) with Fragment(s) since ViewModelProviders.of() only works with Fragment?

答: You are extending Activity. ViewModelProviders works with FragmentActivity and things that inherit from that, such as AppCompatActivity. It also works with the backport of Fragment (android.support.v4.app.Fragment). There is no official support for the native Activity or Fragment class.

Body:
I am trying to instantiate one ViewModel to use across all of my Activity(s).

public class LaunchActivity extends Activity {
    private Controller control;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_launch);
         control = ViewModelProviders.of(this).get(Controller.class);
    }
}

but I got an error at control = ViewModelProviders.of(this) <-- stating that it cannot resolve of(this), but based on the example here by Android Developer on Implementing ViewModel; a class that extends ViewModel should be able to be instantiated on Activity, am I right?

If what I am doing is wrong, how should I instantiate a ViewModel object for my Activity(s)? Do I have to create n number of Activity(s) with Fragment(s) since ViewModelProviders.of() only works with Fragment?


问:
perl user input into a data structure

I am trying to take user input such as 4 2 1 4 and store that into an array. Then loop through the array looking for duplicates to store into a hash table.

```<code>#!/usr/bin/perl -w
print "Enter numbers into hash table :";

my @num = <STDIN>;
my %hash;

foreach $x (@num){
    my $count =1;
    foreach $y(@num){

        if($x == $y){
        my $count++;
        $hash{'$x'} = $count;
        }
    }

}

map{print "$_\t$hash{$_}\n"}keys %hash;
</code>```

I expect the result to be:
1 1
2 1
4 2

The actual result, I just continue to enter digits, after I hit enter the program continues to ask for more input. I hit CTRL D and nothing happens.

答:
Probably it is possible to do more nicely, but i would do this as:</p>

```<code>use strict;
use warnings;
use Data::Dumper;

my $numbers;

print "Enter numbers and finish with CTRL-D\n";
while(my $line = <STDIN>) {
        $numbers->{$_}++ for ( $line =~ m/(\b\d+\b)/g );
}

print Dumper $numbers;
</code>```

Title: perl user input into a data structure

Body:
I am trying to take user input such as 4 2 1 4 and store that into an array. Then loop through the array looking for duplicates to store into a hash table.

#!/usr/bin/perl -w
print "Enter numbers into hash table :";

my @num = <STDIN>;
my %hash;

foreach $x (@num){
    my $count =1;
    foreach $y(@num){

        if($x == $y){
        my $count++;
        $hash{'$x'} = $count;
        }
    }

}

map{print "$_\t$hash{$_}\n"}keys %hash;

I expect the result to be:
1 1
2 1
4 2

The actual result, I just continue to enter digits, after I hit enter the program continues to ask for more input. I hit CTRL D and nothing happens.

Body:
Probably it is possible to do more nicely, but i would do this as:

use strict;
use warnings;
use Data::Dumper;

my $numbers;

print "Enter numbers and finish with CTRL-D\n";
while(my $line = <STDIN>) {
        $numbers->{$_}++ for ( $line =~ m/(\b\d+\b)/g );
}

print Dumper $numbers;


问:
L2 regularization in tensorflow with high level API
I know there are some similar questions out there regarding l2 regularization with the layer API from tensorflow but it is still not quite clear to me.

So first I set the kernel_regularizer in my conv2d layers repeatedly like this:

regularizer = tf.contrib.layers.l2_regularizer(scale=0.1)
tf.layers.conv2d(kernel_regularizer=)
```

<p>Then I can collect all the regularization losses with following:</p>

<pre class="lang-py prettyprint-override"><code>regularization_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
</code>```

And last but not least I have to incorporate the regularization term into the final loss. However, here I am not quite sure what to do, which one of the following is correct?

1) loss = loss + factor * tf.reduce_sum(regularization_losses)

2) loss = loss + tf.contrib.layers.apply_regularization(regularizer, weights_list=regularization_losses)
```

<p>Or are both of them wrong? The second option seems weird to mean since I have to pass the regularizer as parameter once again, even tho each layer already has a regularizer as argument.</p>

<p><em>EDIT</em></p>

<pre class="lang-py prettyprint-override"><code>loss_1 = tf.losses.mean_squared_error(labels=y, predictions=logits, weights=1000)

regularization_loss = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)

loss = tf.add_n([loss_1] + regularization_loss, name='loss')
</code>```

答:
The first method is correct. One more way of doing this is via tf.add_n function:

```<code>reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
loss = tf.add_n([base_loss] + reg_losses, name="loss")
</code>```

The second method also works, but you'll have to define a single regularizer. So it works in your case, but may be inconvenient if you use different regularizers in different layers.

Body:
I know there are some similar questions out there regarding l2 regularization with the layer API from tensorflow but it is still not quite clear to me.

So first I set the kernel_regularizer in my conv2d layers repeatedly like this:

regularizer = tf.contrib.layers.l2_regularizer(scale=0.1)
tf.layers.conv2d(kernel_regularizer=)

Then I can collect all the regularization losses with following:

regularization_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)

And last but not least I have to incorporate the regularization term into the final loss. However, here I am not quite sure what to do, which one of the following is correct?

1) loss = loss + factor * tf.reduce_sum(regularization_losses)

2) loss = loss + tf.contrib.layers.apply_regularization(regularizer, weights_list=regularization_losses)

Or are both of them wrong? The second option seems weird to mean since I have to pass the regularizer as parameter once again, even tho each layer already has a regularizer as argument.

EDIT

loss_1 = tf.losses.mean_squared_error(labels=y, predictions=logits, weights=1000)

regularization_loss = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)

loss = tf.add_n([loss_1] + regularization_loss, name='loss')

Body:
The first method is correct. One more way of doing this is via tf.add_n function:

reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
loss = tf.add_n([base_loss] + reg_losses, name="loss")

The second method also works, but you'll have to define a single regularizer. So it works in your case, but may be inconvenient if you use different regularizers in different layers.


问:
How to create a database from existing Database without any data?
I want to create a database from existing one without taking any data from it (only schema). I know, I can create a script for this purpose using SQL Server Management Studio, but I need some transact SQL script doing this dynamically</p>

答:
Try this DBCC command: DBCC CLONEDATABASE
https://support.microsoft.com/en-us/help/3177838/how-to-use-dbcc-clonedatabase-to-generate-a-schema-and-statistics-only</p>


问:
What is the normal memory-ram size?(xamarin)
I'm using an application with many activities inside. also listview with images and so on. Here is an image from apk.
      Here is an image

First question what kind of memory is this with red circle? Is it Ram? Or heap memory?
Second question what is the normal size for each apk.Is it safe bigger than a number of memory?
Third question my application if this memory is above 380mb. In some cases it crashes my apk.with error message apk doesnt respond. Is something which i can do for this?
Most common activity uses a listview with items inside:Here is part of my code:
I'm using very much sqlite in my apk.

```<code>var table = db.Query<InventoryPreviewClass>(
    "select * from InventoryPreviewClass where CategoryID =" +
    Connection.CategoryID + " and InventoryItemName like '%" +
    etSearchAlwaysOn.Text.ToUpper() + "%'");

mItems = new List<InventoryPreviewClass>();

foreach(var item in table)
{
    mItems.Add(new InventoryPreviewClass() {
        InventoryItemID = item.InventoryItemID,
        InventoryItemName = item.InventoryItemName,
        InventoryItemPrice = item.InventoryItemPrice
    });
}

MyListViewAdapterInventory adapter = new MyListViewAdapterInventory(this, Resource.Layout.InventoryPreview, mItems);
mlistview.Adapter = adapter;
</code>```

I tag also java cause its similar

答:
First question what kind of memory is this with red circle? Is it Ram? Or heap memory?

Working Set : refers to the total physical memory (RAM) used by the process.  For more detail information you could refer to : What is private bytes, virtual bytes, working set?

Second question what is the normal size for each apk. Is it safe bigger than a number of memory?

Android provide MemoryClass on ActiviyManager API to get the value for your device, for deatail information, you could refer to : What is the maximum amount of RAM an app can use?

Third question my application if this memory is above 380mb. In some cases it crashes my apk.

As you said, your application has ListView with images and in some cases it crashes your apk, when you app load many image at one time it will occupy lots of memory, and it usual cause OutOfMemoryError, so I think your problem is an OutOfMemoryError. You should pay more attention to the heap size in your app instead of the Working Set. As the Android document said :

To allow multiple running processes, Android sets a hard limit on the heap size alloted for each app. The exact heap size limit varies between devices based on how much RAM the device has available overall. If your app has reached the heap capacity and tries to allocate more memory, the system throws an OutOfMemoryError.

Since we don't know how did you load images to your listview, here are some suggestion :

It is recommend to implement image cache, but there is no need to reinvent the wheel, focus on the core logic of your app instead. Just use a known and solid framework for Cache & Fetching images, like Picasso or Glide. Then you can use it to load image in your listview like this:

```<code>Picasso.With(context).Load(imageUrl).Into(imageView);
</code>```

Try to implement View Holder Pattern to increases the performance ListViews. Xamrin.Android example here.

Make sure there is no memory leak in your Application.

Body:
I'm using an application with many activities inside. also listview with images and so on. Here is an image from apk.
      Here is an image

First question what kind of memory is this with red circle? Is it Ram? Or heap memory?
Second question what is the normal size for each apk.Is it safe bigger than a number of memory?
Third question my application if this memory is above 380mb. In some cases it crashes my apk.with error message apk doesnt respond. Is something which i can do for this?
Most common activity uses a listview with items inside:Here is part of my code:
I'm using very much sqlite in my apk.

var table = db.Query<InventoryPreviewClass>(
    "select * from InventoryPreviewClass where CategoryID =" +
    Connection.CategoryID + " and InventoryItemName like '%" +
    etSearchAlwaysOn.Text.ToUpper() + "%'");

mItems = new List<InventoryPreviewClass>();

foreach(var item in table)
{
    mItems.Add(new InventoryPreviewClass() {
        InventoryItemID = item.InventoryItemID,
        InventoryItemName = item.InventoryItemName,
        InventoryItemPrice = item.InventoryItemPrice
    });
}

MyListViewAdapterInventory adapter = new MyListViewAdapterInventory(this, Resource.Layout.InventoryPreview, mItems);
mlistview.Adapter = adapter;

I tag also java cause its similar

Body:
First question what kind of memory is this with red circle? Is it Ram? Or heap memory?

Working Set : refers to the total physical memory (RAM) used by the process.  For more detail information you could refer to : What is private bytes, virtual bytes, working set?

Second question what is the normal size for each apk. Is it safe bigger than a number of memory?

Android provide MemoryClass on ActiviyManager API to get the value for your device, for deatail information, you could refer to : What is the maximum amount of RAM an app can use?

Third question my application if this memory is above 380mb. In some cases it crashes my apk.

As you said, your application has ListView with images and in some cases it crashes your apk, when you app load many image at one time it will occupy lots of memory, and it usual cause OutOfMemoryError, so I think your problem is an OutOfMemoryError. You should pay more attention to the heap size in your app instead of the Working Set. As the Android document said :

To allow multiple running processes, Android sets a hard limit on the heap size alloted for each app. The exact heap size limit varies between devices based on how much RAM the device has available overall. If your app has reached the heap capacity and tries to allocate more memory, the system throws an OutOfMemoryError.

Since we don't know how did you load images to your listview, here are some suggestion :

It is recommend to implement image cache, but there is no need to reinvent the wheel, focus on the core logic of your app instead. Just use a known and solid framework for Cache & Fetching images, like Picasso or Glide. Then you can use it to load image in your listview like this:

Picasso.With(context).Load(imageUrl).Into(imageView);

Try to implement View Holder Pattern to increases the performance ListViews. Xamrin.Android example here.

Make sure there is no memory leak in your Application.


答:
You could add two columns - division_names to teams which will contain the names of teams that are in each division, and team_names to divisions which will contain the names of the divisions that team is a part of.

When you add a team or division, follow it by a ;, then you can create an array of teams or divisions based on that field by using $field = explode(";", $field);, and then list the teams or divisions using foreach().

That's assuming you're using PHP. Let me know if I misunderstood you.

Title: MYSQL Table design help

Body: I have  a table called teams (id, name, ...)   I have a table called divisions (id, name, ......)   I want the diviosn to hold the teams.id  for each team in a divsion  and Teams can be in more than one divsion.  How do I set this up?


问:
SSIS Redirect on Error - Too many rows
I have an SSIS package that imports a flat CSV file, there are approx 200,000 records in the file. I've set the table that the data imports into with a primary unique key of the account number. There shouldn't be any duplicates in the source data (application controlled - outside of my influence)

However there is 1 duplicate row in the CSV, however when i add the primary key it redirect 7k rows... these aren't duplicate rows it just appears to redirect a load for no reason?

If I manually remove the single duplicate row it works perfectly. There is nothing special about the data or the files, it should just import the data and redirect the error row.

答:
This behavior is due to OLE DB Destination and fast insert mode used.

With fast insert mode, OLE DB destination issues INSERT BULK command and does insert in batches. If one of rows within a batch violates table constraints, the whole batch is failed and got redirected to Error Output. This accounts for strange at the first glance behavior - reject more than 1 row.

What you can do with it - depends on your goal and limitations

If simply filter out consecutive duplicates - switch OLE DB Dest to regular insert mode at cost of significant performance decrease. Simplest way.

If performance drop is not an option, and you need to keep it simple - use Sort Component at Dataflow and tick discard duplicate rows flag. Caveat - you do not have a control on which row will be discarded.

If you need to implement some business rules on what data should pass - then you have to implement some scoring column and use it to filter rows. See Todd McDermid's article on this.

Title: SSIS Redirect on Error - Too many rows


问:
Core 2 MVC with JQuery Datatables
There is a good example on how to use JQuery Datatables with Core MVC at Using jQuery DataTables Grid With ASP.NET CORE MVC

I download the sample project, made some modifications and it works perfectly.

However, I'm getting an error when I try to integrate this into my project.

DataTables warning: table id=example - Requested unknown parameter 'IdStudent' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4

After I click ok on the error, the table generates with the correct number of rows, but with no data:

This is my class:

```<code>public class GridStudent
{
    [Key]
    public int IdStudent { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
}
</code>```

The HTML and JavaScript:

```<code>    <div class="container">
    <br />
    <div style="width:90%; margin:0 auto;">
        <table id="example" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
            <thead>
                <tr>
                    <th>IdStudent</th>
                    <th>Name</th>
                    <th>LastName</th>
                    <th>Edit</th>
                    <th>Delete</th>
                </tr>
            </thead>
        </table>
    </div>
</div>

<script>

    $(document).ready(function ()
    {
        $("#example").DataTable({
            "processing": true, // for show progress bar
            "serverSide": true, // for process server side
            "filter": true, // this is for disable filter (search box)
            "orderMulti": false, // for disable multiple column at once
            "ajax": {
                "url": "/StudentGrid/LoadData",
                "type": "POST",
                "datatype": "json"
            },
            "columnDefs":
            [
                {
                    "targets": [0],
                    "visible": false,
                    "searchable": false,
                }
            ],
            "columns": [
                { "data": "IdStudent", "name": "IdStudent", "autoWidth": true },
                { "data": "Name", "name": "Name", "autoWidth": true },
                { "data": "LastName", "name": "LastName", "autoWidth": true },
                {
                    "render": function (data, type, full, meta)
                    { return '<a class="btn btn-info" href="/StudentGrid/Edit/' + full.IdStudent + '">Edit</a>'; }
                }
                ,
                {
                    data: null, render: function (data, type, row)
                    {
                        return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.IdStudent + "'); >Delete</a>";
                    }
                },
            ]
        });
    });

    function DeleteData(CustomerID)
    {
        if (confirm("Are you sure you want to delete ...?"))
        {
            Delete(CustomerID);
        }
        else
        {
            return false;
        }
    }

   function Delete(CustomerID)
   {
        var url = '@Url.Content("~/")' + "StudentGrid/Delete";

        $.post(url, { ID: CustomerID }, function (data)
            {
                if (data)
                {
                    oTable = $('#example').DataTable();
                    oTable.draw();
                }
                else
                {
                    alert("Something Went Wrong!");
                }
            });
   }
</script>
</code>```

This is the line of code, from the controller, than returns the data:

```<code>return await Task.Run(() => Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }));
</code>```

As you can see from the image, the controller is returning the data correctly, but for some reason DataTables can't read it.

I cross check with the sample a thousand times and I can't see a difference on the format of the data being return.

Any suggestions?

答:
This is most likely due to the casing of the serialized JSON. Your data properties in the column definitions within your JavaScript expect Pascal casing. At present, I expect your are serializing JSON as lower camel case rather than Pascal case (e.g. idStudent instead of IdStudent).

To serialize JSON as Pascal case, make sure you have the following in the ConfigureServices method in your Startup class:

```<code>services
    .AddMvc()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.ContractResolver
            = new Newtonsoft.Json.Serialization.DefaultContractResolver();
    });
</code>```

Title: Core 2 MVC with JQuery Datatables

Body:
There is a good example on how to use JQuery Datatables with Core MVC at Using jQuery DataTables Grid With ASP.NET CORE MVC

I download the sample project, made some modifications and it works perfectly.

However, I'm getting an error when I try to integrate this into my project.

DataTables warning: table id=example - Requested unknown parameter 'IdStudent' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4

After I click ok on the error, the table generates with the correct number of rows, but with no data:

This is my class:

public class GridStudent
{
    [Key]
    public int IdStudent { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
}

The HTML and JavaScript:

                    IdStudent
                    Name
                    LastName
                    Edit
                    Delete

This is the line of code, from the controller, than returns the data:

return await Task.Run(() => Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }));

As you can see from the image, the controller is returning the data correctly, but for some reason DataTables can't read it.

I cross check with the sample a thousand times and I can't see a difference on the format of the data being return.

Any suggestions?

Body:
This is most likely due to the casing of the serialized JSON. Your data properties in the column definitions within your JavaScript expect Pascal casing. At present, I expect your are serializing JSON as lower camel case rather than Pascal case (e.g. idStudent instead of IdStudent).

To serialize JSON as Pascal case, make sure you have the following in the ConfigureServices method in your Startup class:

services
    .AddMvc()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.ContractResolver
            = new Newtonsoft.Json.Serialization.DefaultContractResolver();
    });