text:
Q: What is the efficient way to compare a ArrayList of String in android I want to compare each item of an arraylist to the item of another arrayList It seems to slow.
How to speed up this code.
I want char by char comparision of each string.
Please  suggest me if any loop is unnecessary here.
public static void FinalGroups(ArrayList<ArrayList<QuineMCCluskyModel>> Prime_Implicants,
                                   ArrayList<ArrayList<QuineMCCluskyModel>> FinalGRoupImplicants)
    {
        Integer count = 0;

        for (Integer i = 0; i < Prime_Implicants.size(); i++)
        {
            for (Integer j = 0; j < Prime_Implicants.get(i).size(); j++)
            {

                if (i + 1 < Prime_Implicants.size())

                    for (Integer L = 0; L < Prime_Implicants.get(i+1).size(); L++)
                    {
                        count = 0;
                        if (Prime_Implicants.get(i).size() > 0 && Prime_Implicants.get(i+1).size() > 0)
                        {
                            for (Integer k = 0; k < Prime_Implicants.get(i).get(j).Number.length()  ; k++)
                            {

                                if (Prime_Implicants.get(i).get(j).Number.charAt(k)
                                        != Prime_Implicants.get(i+1).get(L).Number.charAt(k))
                                {

                                    count++;
                                }

                            }
                            if (count == 1)
                            {
                                while (i + 1 > FinalGRoupImplicants.size())
                                    FinalGRoupImplicants.add(new ArrayList<QuineMCCluskyModel>());
                                QuineMCCluskyModel temp_model = new QuineMCCluskyModel();
                                temp_model.Number = "";
                                temp_model.HasUsed = false;
                                for (Integer k = 0; k < Prime_Implicants.get(i).get(j).Number.length()
                                     ; k++)
                                {

                                    if (Prime_Implicants.get(i).get(j).Number.charAt(k)
                                            == Prime_Implicants.get(i+1).get(L).Number.charAt(k))
                                    {
                                        temp_model.Number += Prime_Implicants.get(i).get(j).Number.charAt(k);
                                    }
                                    else
                                    {
                                        temp_model.Number += 'b';
                                    }

                                }

                                Prime_Implicants.get(i).get(j).HasUsed = true;
                                Prime_Implicants.get(i+1).get(L).HasUsed = true;
                            }

                        }
                    }
            }
        }

A: Try using int types rather than Integer. You should see some performance increase from avoiding Autoboxing


text:
Q: autocomplete() not recognized by LimeSurvey I have installed LimeSurvey 3.4 and tried to add this code to my question:
<script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
        $('#question{QID} input[type="text"]').autocomplete({
            minLength: 2,
            source: ["Test1","Test2","Test3"]
        });
    });
</script>

but autocomplete is not working and I have this error in Console:
TypeError: $('input.text', thisQuestion).autocomplete is not a function. (In '$('input.text', thisQuestion).autocomplete({
        minLength: 2,
        source: ["Test1","Test2","Test3"]
    })', '$('input.text', thisQuestion).autocomplete' is undefined)

In the workarounds it says that "Note that the Autocomplete widget is already included in LimeSurvey, as part of jQuery UI." so I was expecting autocomplete to work by default.
Should I need to add anything to my installation?
Another possibility is that LS 3.5 has changed the way to refer to the question, and that is what causes the JS error... any hint more than welcome!
NOTE:
I have posted this question on the LimeSurvey forum but got no reply so far.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Оптимизиация копирования ячеек массива в случае если де факто копируется в саму себя На примере тривиального алгоритма удаления определённого числа из массива:
public int RemoveElement(int[] nums, int target)
{
    int i = 0;
    for (int j = 0; j < nums.Length; j++)
    {
        if (nums[j] != target)
        {
            nums[i] = nums[j];
            i++;
        }
    }
    return i;
}

var nums = new[] {1,2,3,4,5};
var target = 3;
var newsize = RemoveElement(nums, target);
for (int i = 0; i < newsize; i++)
{
    Console.WriteLine(nums[i]);
}

Меня интересует поведение в случае если массив не содержит искомое число: в этом случае i = j и по факту происходит копирование ячейки массива в саму себя. (Аналогично в примере это происходит до момента нахождения тройки)
Есть ли какие-либо оптимизации на уровне ниже C# - т.е. будет ли процессор переписывать ячейку саму в себя или есть какие-либо оптимизиации?
Иначе, если подобных оптимизаций нет, то есть ли смысл делать предварительную проверку на равенство i и j чтобы не выполнять лишний раз перезапись ячеек массива? (Неявно здесь ещё один вопрос: какая операция более дорогая - сравнение i и j или операция записи ячеек? Подозреваю, что вторая, на уровне C и ассемблера по крайней мере, в стековых машинах непонятно, но по идее должно быть так же)


text:
Q: Estimating uniform distribution with RJAGS - beginners question I am trying to estimate the parameters of a uniform distribution, which, by a visual inspection, is between -5 and 25.
I am getting the following error:
"Error in jags.model(filepath, data = list(x = x, N = N), n.chains = 2) :

   Error in node x[1]

Node inconsistent with parents"

I think the problem is with the .bug file:
model {
for (i in 1:N) {
    x[i] ~ dunif(a, b)
}

a ~ dnorm(-5, .0001)
b ~ dnorm(15,.0001)

}

This code is suppose to estimate "a" and "b", where "x" is uniformly distributed between them.
Any idea why I am getting the error? (Am I even in the right direction?)

A: You don't have a reproducible example but I'm pretty sure I know what is going on.  If any of your observations are outside a, b then the likelihood is undefined and you get the error (which must be happening for x[1], it is either less than -5 or greater than 15.
It's really odd to estimate the uniform distribution this way.  Just take a and b to be the min(x) and max(x).  I don't see the uniform distribution used as likelihood, more often as a prior.


text:
Q: MongoDB 2.4 MapReduce Refactor I recently upgraded to MongoDB 2.4 and as referenced in the release notes, am having an issue with a map function that makes use of db.  The release notes recommend refactoring, but I am unclear as to what route I need to take.
The now non-working piece of the function is as follows:
function map() {
  var student = db.student.findOne(this.student_id);
  var school = db.school.findOne(this.school_id);
  ...
  emit({
    bcg_id: student.bcg_id,
  ...

I am unclear on how to pass the document from the 'student' collection to the 'student' variable now that db is deprecated.
Any recommendations?

A: You can no longer run a query inside a javascript function anymore.
See: http://docs.mongodb.org/manual/release-notes/2.4/#additional-limitations-for-map-reduce-and-where-operations
You can pass data into the scope eg:
res = t.mapReduce( mapper , reducer , { scope : { xx : 1 } } );

But as to how bigger a refactor - it depends on what the original map reduce function did.
You may want to collate all the data needed into a new collection and then run the map reduce over that instead.


text:
Q: htaccess redirect not exist file and show link like exist This is my htaccess
RewriteEngine On
RewriteCond %{SERVER_PORT} !=443
RewriteRule ^https://example.com%{REQUEST_URI} [NS,R,L]
RewriteRule ^((?:[a-zA-Z0-9_-]|%20)+)/?$ member.php?id=$1

With this htaccess, i can remove .php and i can show my "example.com/member.php?id=1" page as "example.com/3".
Now i want to show "example.com/product.php?id=1" as "example.com/product/1" but the interesting part, there is not exist "product" file. Is it possible to show as "example.com/product/1"?
Thanks

A: Have it like this:
RewriteEngine On

RewriteCond %{SERVER_PORT} !=443
RewriteRule ^ https://example.com%{REQUEST_URI} [NE,R=301,L]

# skip all files and directories from rewrite rules below
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# product rewrite
RewriteRule ^product/([^/]+)/?$ product.php?id=$1 [L,QSA,NC]

# member rewrite
RewriteRule ^([^/]+)/?$ member.php?id=$1 [L,QSA]


text:
Q: Get System brightness level I have a WPF app running on windows 10 devices in which I am setting system's brightness based on value set in a progress bar and its vice versa. I am querying WmiMonitorBrightness to get the brightness levels. Here is the link that I am using to do so.
This was working fine until we started to have power plans set in devices.Now, if I am in battery saver mode and I go to display settings, I can move brightness to max (which is still slightly low so as to support battery saver power plan). So System is aligning its brightness levels' values to power plan but my wmi query is returning me the values supported by the hardware. These values are now higher than values in system's display settings.
This is causing the brightness control to move to a different value than value set by user.
How can I get the brightness levels that are seen in system's display settings? Is there any api which can be used?


text:
Q: Undo click(function() {return false;}) I have a question/problem. At some point I need that every element are non-clickable except one div and I have:
$('#MainDiv *:not(#Div)').click(function() {return false;});

In the MainDiv i have several other elements (a, img,...) and I need those elements retun to be clickable. It is possible to undo that function or do I need to set every a.href and img.click of those elements again?

A: Try using $('#MainDiv *:not(#Div)').unbind("click");
Then when you need to reasign the the click functions, just make sure what each click does is wrapped in its on function so you can simply do something like $(".someEle").click(function(e){ yourCustomeFuncForThisItem(var1, var2); });

A: This is a job for event delegation. #MainDiv probably has dozens or hundreds of elements? Just attach one click event handler there, let the event bubble to #MainDiv and see if the thing that was clicked is #Div.
$("#MainDiv").click(function(event){
    if ( event.target.id === "Div" ) {
      // do the thing with Div
    }
    else {
      return false;
    }
});

A: You can try this:
$('#MainDiv *:not(#Div)').bind('click', false);

$('#MainDiv *:not(#Div)').unbind('click', false);

$('#MainDiv *:not(#Div)').bind('click', false); should be equivalent to $('#MainDiv *:not(#Div)').click(function() { return false; });


text:
Q: Does Apple Pay in an iOS app require a payment's handler like Stripe? If I accept payments via Apple Pay within my app for goods sold on my app do I need to also set up a Stripe account or will Apple handle the payments directly?

A: Yes, We must need any merchant like Stripe, Braintree, mastercard etc. to perform actual payment.


text:
Q: AM335x FPGA Memory Integration I'm currently designing a digital mixing console. We have a somewhat large number of ADCs and DACs (more than the multi channel audio serial port on the processor can handle). We decided the solution for this was to use an FPGA to interface with the data converters and let the processor access the data through the RAM in the FPGA. We have not yet picked out a FPGA.
From what I have read we can configure the FPGA RAM as being a NOR non-multiplexed 16-bit device through the GPMC. Is this correct?
And my other question is it would probably be too slow to keep the data in RAM of the FPGA so would it be possible to set up a DMA transfer from the FPGA RAM to other memory in the processor that is easier and faster to access? Or would we need to use a PRU to copy the data?

A: I will make some assumptions: since this is mixing audio, you will want to sequentially read all of the ADCs at some fixed synchronous rate (like 96kHz), and sequentially write all of the DACs at the same rate. I think the PRU will be the easiest way to implement a fast data-pipe to/from an FPGA.
There are two PRU processors in a AM335x Sitara processor, and each has 32 input pins and 32 output pins. Since you would probably need some control signals and are likely using 24-bit codecs, that should work out nicely. You could dedicate one PRU to receive data and the other to send data. With tight C code, I estimate that you could get at least 10 samples per microsecond in each direction (30 megabytes/second), and more with assembly language.
I have put multiple I2S audio interfaces into an FPGA, and it's not that hard. As you said, the codecs could move data to/from FPGA sram, and after each codec cycle (every 10.417 microseconds at 96kHz) the PRUs could read/write the data as a contiguous block. A simple sequencer in the FPGA could respond to strobes from the PRU to walk through the block of data. In the Sitara, a Linux process can allocate a block of memory to share with the PRU. I've put C structures and arrays into shared ARM/PRU memory to allow the Linux process and the PRU to share data as C variables.
Hope that helps.


text:
Q: How to handle delete message on Thunderbird I have a Thunderbird add-on and should to fix some bugs.
I need to handle deleting messages and do some actions, but I don't get any information about onDeleteEvent.
I only found this page and tried to use
document.addEventListener("onMessagesRemoved", function() {
  Application.console.log('deleted');
});

But nothing happens.
How I can handle delete messages event?

A: The notification is fired on listeners of nsIMsgFolders. So you need folder.addEventListener, not document.addEventListener. You have to provide a listener for each specific folder that you want to watch deletion for.
(reference: http://mxr.mozilla.org/comm-central/source/mailnews/base/public/nsIMsgFolder.idl#652)


text:
Q: Web API [FromBody] parameter is null when sending an array of objects I seem to have run into an interesting problem with Web API - using this controller action, with a breakpoint on the opening brace to inspect thing:
[HttpPut]
public void Test([FromBody]object thing)
{
}

If I submit the following request (as CURL), I get the expected value which is a JObject containing the data from the body:
curl -X PUT -H "Content-Type: application/json" -d '{
    "Name": "Joe",
    "Key": { "Key": "Value" }
}' "http://localhost/api/TestController/Test"

That is, an anonymous object where Name is Joe and Key is another object containing Key = Value.
However, if I change this ever-so-slightly to instead submit an array of Keys, I get null.  No error, just null.
curl -X PUT -H "Content-Type: application/json" -d '{
    "Name": "Joe",
    "Keys": [{ "Key": "Value" }]
}' "http://localhost/api/TestController/Test"

Why is this happening?  The HTTP verb doesn't seem to matter (I've tried POST and PUT), and using dynamic instead of object is the same thing.
Here's some screenshots:

A: Your code is working fine when testing in Postman.

A: Turns out I had the global JSON setting for MaxDepth set to 2 elsewhere in my code, which was running before the controller action.  Why this returns null and not an empty object is still beyond me, but changing this to 3 corrects the issue and functions as expected.
Sorry for the confusion everyone, thanks for the answers!

A: i think it all depends on how you wish to work with it, if you want to get a strongly typed model you can always create one like user3658685 said.
another thing you can do is bind the data to JObject and then serialize using Newton-soft Serializer:
public void Post([FromBody] JObject value)
{
    //instead of object you can use any type you wish to cast
    object obj = value.ToObject<object>();
}

A: WebApi uses model mapping class to try to map json object with the argument og your WebApi method. You can resolve this by creating a class with all attributes matching your json object.
public class Contract {
   public string Name { get; set; }
   public dynamic[] Keys { get; set; }
}

And changing the signature of your WebApi method with
public void Post([FromBody] Contract value)
{
}


text:
Q: How to remove all table row below particular table row in jQuery This is my table :

            1

            2

            remove all below tr

            remove 1

            remove  2

            remove 3

            remove 4

I want to remove all the table rows below the following table row
 remove all below tr

what is the best way to do this
I can remove one tr like the following :
$('.removeFromHere').parent().remove();

But it will only remove the following :
 remove all below tr

How can I remove all the tr below the particular tr.

A: You can use nextAll() for that result.

*

*You first need to get the
 element in which there is the element with class removeFromHere

*Then you can use nextAll() to remove all the
 elements those are next to it.

$('.removeFromHere').closest('tr').nextAll('tr').remove();

      1

      2

      remove all below tr

      remove 1

      remove 2

      remove 3

      remove 4

A: You could use index's with the help of greater than selector :gt() to achieve that like :

//Get the index of the target tr with class `removeFromHere`
var target_index = $('tr').index($('.removeFromHere').parent());

//Get all the tr's with index greater than 'target_index' then remove them
$('table').find("tr:gt(" + target_index + ")").remove();

      1

      2

      remove all below tr

      remove 1

      remove 2

      remove 3

      remove 4

A: using
$('.removeFromHere').parent().remove();

won't help, because td's parent is just one particular tr.
I don't use jQuery so I don't really know the syntax, but try using
while($('.removeFromHere')parent().next()) {
   $('.removeFromHere')parent().next().remove()
}

A: $('.removeFromHere').parent().nextAll().remove();

This will remove all rows after the selected row...

A: Give your table an id then try removing the last table row until you reach your particular table row.
$('#table tr:last').remove();

Then you remove the particular tr.

A: Simply, you can use nextAll() selector. You can refer document at https://api.jquery.com/nextAll/
Below are the example,

$(document).ready(function() {
  $('.removeFromHere').parent().nextAll("tr").remove();
});

      1

      2

      remove all below tr

      remove 1

      remove 2

      remove 3

      remove 4


text:
Q: C# FileUpload with client feedback and keep files I have a project in C# that needs to upload files in a page with a lot of others information.
Problems:
1 - File upload doesn't give any feedback for the user, so they can't know how long will takes (doesn't work with UploadProgress and UpdatePanel).
2 - Some validations I can't do with javascript (relationships for example), so if I get any error on the server side, FileUpload loses the file and the user needs to upload the whole file AGAIN.
3 - End user have a really poor link, so for 10mb will takes a long time (10mb is the maximum allowed).
Solutions (none of them works great):
1 - I can use a client side file upload with javascript (like uploadify) and get the percentage, but works as async method so I need to block the screen to don't allow the user to do another things. My worry is more about when I receive the file and save it, because I need to link this file with the other entity if not I will lose the bridge between the file and the entity. (Same happens with the AsyncFileUpload Control). This doesn't solve the problem number 2.
2 - Just do everything synchronous as FileUpload, when all the files arrive to the server, save the file and put all the informations that I need in HiddenFields, so if I get any error on the server side I can recover the file. The problem is that I can't give any feedback for the user while he uploads the file. This doesn't solve the problem number 1.
3 - Split all the files from the others entities (this will mess a lot the project) and upload file individually. The problem is that if I do that I need some mechanism to create the link between the file and the entity AND I can't allow to use the file more than once, so probably this will request a lot of resources to check it. This solves the problems listed but I think create another, complex for the user and a lot of new verifications for the system.
4 - Create 2 buttons, one button VALIDATE for validations on the server side (with no file uploads) and after this check, allow the user to click on the SAVE button. This doesn't solve the problem number 1.
Well, as you can see I'm thinking a lot about the problem but I can't find a really good solution. One that fits all my needs. Anyone have a idea?
PS: I have FileUploads inside repeaters as well, so the IDs are automatics.


text:
Q: Hibernate Mapping same Column twice and insert I want to insert a row that contain two filed name organization_id and account_id that is refereed from same table (organization table).
EntityModel.java
@ManyToOne
@JoinColumn(name = "organization_id")
private OrganizationModel organization;

@ManyToOne
@JoinColumn(name = "account_id")
private OrganizationModel account;

OrganizationModel.java
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "organization_id", unique = true, nullable = false)
private int organizationId;

@OneToMany(mappedBy = "organization")
private Set<EntityModel> organization;

But iam getting following error.
Repeated column in mapping for entity: com.party.OrganizationModel column: organization_id (should be mapped with insert="false" update="false")

And when i add insert="false" update="false" for account, error gone.But i need to insert both account and organization at the same time.

A: Add a primary key for EntityModel.
Here is the code that worked for me:
@Entity
@Table(name = "EntityModel")
public class EntityModel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "entity_model_id", unique = true, nullable = false)
    private int entityModelId;

    @ManyToOne
    @JoinColumn(name = "organization_id")
    private OrganizationModel organization;

    @ManyToOne
    @JoinColumn(name = "account_id")
    private OrganizationModel account;

}

@Entity
@Table(name = "OrganizationModel")
public class OrganizationModel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "organization_id", unique = true, nullable = false)
    private int organizationId;

    @OneToMany(mappedBy = "organization")
    private Set<EntityModel> organization;

}


text:
Q: Python Code Error 3.3.2 I have recently been practicing my skills at figuring out my own problems but this one problem is persistent. This is the problematic code:
with open('login_names.txt', 'r') as f:
        login_name = [line.rstrip('\n') for line in f]
        k = input("name: ")
        if k in login_name :
            print("No errors")
        else:
            print("You have an error")
else:
    print('fail')
#var = login_name.index[random]
check = login_pass[login_name.index[random]]

with open('login_passw.txt', 'r') as p:
    login_pass = [line.rstrip('\n') for line in p]
    s = input("pass: ")
    if s == check :
        print("Works")
    else:
        print("Doesn't work")

f.close()
p.close()

Basically when I run the code it says:
Traceback (most recent call last):
  File "C:/Python33/Test.py", line 29, in <module>
    check = login_pass[login_name.index[random]]
TypeError: 'builtin_function_or_method' object is not subscriptable

I have tried lots of different suggestions on different questions but none of them have worked for me...

A: If we assume that login_pass, login_name and random are defined in the namespace that line is in, the only problem you have is that you should write
check = login_pass[login_name.index(random)]

str.index is a function that returns the first index of the argument given in str, so you use () instead of [], which you would use for lists, tuples and dictionaries.


text:
Q: Set username as default value in Access table I have an access table with a column username. I have multiple users that will use the database at different times and they will add rows to the table. But everytime a user add a new row, his/her username must appear in the username column of the table, without them having to type it in by themselves. I tried putting in UCase(Environ("USERNAME")) as the default value, but Environ is an unknown function. I use  this UCase(Environ("USERNAME")) in VBA to get the user name when i export tables.
Is there any way i can set the deafult value of a column to a user's username?

A: Create a public function as described here:
Public Function GetUserName() As String
    ' GetUserName = Environ("USERNAME")
    ' Environ("USERNAME") is easily spoofed, see comment by HansUp
    GetUserName = CreateObject("WScript.Network").UserName
End Function

and use =GetUserName() as default value for the control.


text:
Q: Request.QueryString usage to read Passed array I'm not able to read the array passed from the other page with Request.Querystring
//Label1.Text += FID[l]; //Checked the array and it is printing properly.

Response.Redirect("show.aspx?id=" + ID + "&name=" + NAME + "&fileid="
                  +FID+"&length="+j);

string fid=string.Empty;
if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["fileid"].ToString())))
{
    fid = Request.QueryString["fileid"].ToString();

}

for (int l = 0; l < length; l++)
{

    Label1.Text += fid[l]; //Printing wrong array
}

Can anybody help me with this.
How can I use Global.aspx file to do this instead of parameter passing.

A: Your code makes no sense, first of all If that code is all in the same method then nothing after the Response.Redirect will run.
Second assuming the Response.Redirect is not in the same method as the other code then
if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["fileid"].ToString())))

On the above line you are calling ToString() on something that is already a string and then converting it to a string. If Request.QueryString["fileid"] is null then this will throw a null reference exception. You should do:
if (!string.IsNullOrEmpty(Request.QueryString["fileid"]))

Third fid is a string, Label1.Text is a string.  Why are you looping through the string char by char and then adding them onto the end Label1.Text.
Finally fid will contain whatever is passed as the query string param "fileid", it can't contain anything else.  If it has the "wrong" value then the "wrong" value is getting passed in the query string.


text:
Q: How to check if stripe.js has finished executing? Trying to improve my score on Lighthouse and the general performance of a site. The official docs about including stripe.js mention (emphasis mine):

To best leverage Stripe's advanced fraud functionality, include this script on every page, not just the checkout page. This allows Stripe to detect suspicious behavior that may be indicative of fraud as customers browse your website.

Which is understandable but means that, without async/defer, the script slows down the page slightly (by ~190 ms in my tests) on a majority of pages that barely use it.
And:

You can also load Stripe.js using the async or defer attribute on the script tag. Note, however, that with asynchronous loading any API calls will have to be made only after the script execution has finished.

This leaves me with the following questions:

*

*How can I check whether stripe.js has finished executing?

*async or defer? i.e. is stripe.js completely independent (async), or does it depend on the DOM being fully built (defer)?

*Rather than check if stripe.js has finished  executing, maybe I should just move my own, inline, Stripe code (for a checkout page) into its own dedicated JS file, loaded as defer. This way things would load in a non-blocking way, and would still execute in their relative order.

A: If using an npm module isn't your case for asynchronous loading, you can check for the Stripe function before initializing Stripe.js. Something like this:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title></title>
  <script defer src="https://js.stripe.com/v3/"></script>
</head>

<body>
  <script type="text/javascript">
    try {
      console.log("The first attempt to access Stripe: " + Stripe.version);
    } catch (e) {
      console.log("Stripe is not ready.");
    }
    stripeScriptElement = document.querySelector("script[src^='https://js.stripe.com/v3']");
    if (stripeScriptElement) {
      stripeScriptElement.addEventListener("load", () => {
        if (Stripe) {
          console.log("Stripe v." + Stripe.version + " is ready. ");

        } else {
          console.error("Failed loading Stripe.js");
        }
      });
    }
  </script>
</body>

</html>

A: In a React environment I initialize as below:
import { loadStripe } from "@stripe/stripe-js";

export let stripe = null;
export let stripe_started = false;
export let stripe_running = false;

(async () => {
  try {
    stripe = await loadStripe("pk_test_****");
    stripe_running = true;
  } catch (err) {
    stripe_running = false;
  } finally {
    stripe_started = true;
  }
})();

any module that imports this one has access to the flags; the closure allows the function to run async at top level.

A:
How can I check whether stripe.js has finished executing?

Checking loadStripe() as the other answer.

async or defer? i.e. is stripe.js completely independent (async), or does it depend on the DOM being fully built (defer)?

Defer, since sometimes stripe.js and your own js will look for an element to your DOM to mount, and it will safer to be run after the full DOM is loaded

Rather than check if stripe.js has finished executing, maybe I should
just move my own, inline, Stripe code (for a checkout page) into its
own dedicated JS file, loaded as defer. This way things would load in
a non-blocking way, and would still execute in their relative order.

Make sure to mark both stripe.js and your own dedicated JS 'defer', and put stripe.js before your JS. When there are multiple defer scripts, their execution order will be decided by the including order
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer


text:
Q: Convert Table Creation from MSSQL to PostgreSQL CREATE TABLE [dbo].[Addresses](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [UserId] [int] NULL,
    [City] [nvarchar](50) NULL,
    [State] [nvarchar](50) NULL,
    [CountryCode] [nvarchar](50) NULL,
    [PostalCode] [nvarchar](50) NULL,
    [Street1] [nvarchar](50) NULL,
    [Street2] [nvarchar](50) NULL,
PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

What would the equivalent PostgreSQL table creation script look like, based off of the previous MSSQL create script? Looking for an approach/resource that can guide me on converting MSSQL schema to PostgreSQL ...

A: Here you go:
CREATE TABLE Addresses(
    Id SERIAL NOT NULL PRIMARY KEY,
    UserId int NULL,
    City varchar(50) NULL,
    State varchar(50) NULL,
    CountryCode varchar(50) NULL,
    PostalCode varchar(50) NULL,
    Street1 varchar(50) NULL,
    Street2 varchar(50) NULL
);

SQL Fiddle: http://sqlfiddle.com/#!15/b76b6

A: Phil's answer is correct. As you also asked for "for an approach", here is a very short description to convert Microsoft T-SQL:

*

*always end your statements with a ; (in general: replace GO with ;) - and no, the ; does not go in front of the with keyword for a common table expression

*remove the non-standard square bracket "quoting" [..] (I highly recommend to never use quoted identifiers). Details about the identifier syntax are in the manual

*identity columns map to serial or bigserial in Postgres. That implies the data type integer or bigint so you only need the keyword serial. For details see the manual

*there is no nvarchar in Postgres. All character columns use the same character set.

*other data types to convert (incomplete!):
SQL Server         Postgres
---------------------------
image              bytea
binary             bytea
varbinary(max)     bytea
varchar(max)       text
nvarchar(max)      text
text               text
ntext              text
bit                boolean
datetime           timestamp
smalldatetime      timestamp
timestamp          no equivalent
uniqueidentifier   uuid
xml                xml

*there are not clustered indexes so remove the clustered attribute

*the whole with part defines physical properties of the table that are not relevant in Postgres

*the dbo schema "maps" to the public schema in Postgres. It is somewhat uncommon prefix tables with public though unless you changed your schema search path (there is also no need to use the schema prefix for your own functions as it is required in SQL Server)

Some things to watch out for:

*

*string comparison is case sensitive in Postgres. where name = 'Arthur' will return something different than where name = 'arthur'. Search this site, there are plenty of questions regarding this.

*the "poor man's regex" syntax of SQL Server's LIKE (e.g. like '[0-9]') does not work in Postgres. You need to use the regex operator.

*date handling is a bit different

*Postgres is much more picky about correct data types and value literals. where varchar_column = 2 fails in Postgres even if there are only numbers in that column

*In Postgres you can insert multiple null values into a unique index on a nullable column. The following fails in SQL Server but works in Postgres
create table foo (col1 integer, col2 integer);
create unique index idx_foo on foo (col1, col2);
insert into foo (col1, col2) values (1, null);
insert into foo (col1, col2) values (1, null);

This list is by no means complete! There is a lot more to look out when converting from one DBMS to another.


text:
Q: Font Weight not applying to Typekit Font I'm having trouble with a font-weight declaration for a typekit font. I have the font installed correctly, and it uses the correct font throughout the site. However, for the bold version of the font, I'm wanting to use the 900 weight of proxima nova. In the kit editor on typekit, I have only included the 900 version and the 300 version. For body copy, the 300 seems to be showing correctly...the 900 version doesn't display on any computer that doesn't have the 900 weight installed directly.
I can see it displaying, because I have the font installed on my machine, but no one else can. They just see a bold font, which I'm assuming is defaulting to a 700 weight.
It should be visible on all headline text (h1, h2, etc.) and as the default bold strong tag. Any ideas on what could be going on?
The site is here: southernkentuckyeye.com/wp/ (It is in development, so don't judge me.)

A: I figured this out a while back...It turned out to be a really silly error, but for grins, I thought I'd post it here. (Especially if anyone else is having trouble.)
The way I was declaring the font in the CSS...
{ font-family:"Proxima Nova", sans-serif; }
Would show the font on my computer, because I had the font installed on my computer. I knew this, and figured this was the case anyway. What I couldn't figure out was why Typekit wouldn't display the font anyway. Turns out, it's because I wasn't declaring the font correctly in the CSS. Here's the correct way...
{ font-family:"proxima-nova", sans-serif; }
Again, silly I know, but it's working now. Make sure you pay close attention to how you declare typekit fonts in CSS.

A: You haven't included how you've linked the fonts, but if you want to be able to use 'bold' or 'oblique' the best way is to include them like this:
@font-face {
    font-family: "Your font";
    src: url("fonts/your-font.ttf");
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/your-font.ttf");
    font-weight: bold;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/your-font.ttf");
    font-style: italic, oblique;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/your-font.ttf");
    font-weight: bold;
    font-style: italic, oblique;
}

Otherwise, instead of using font-weight: bold, you can use font-weight: 900


text:
Q: How to run Xdebug 3 on Vagrant / Homestead with VSCode (on Big Sur Mac) Suddenly, with a new installation of Vagrant/Homestead running a freshly installed Big Sur (macOS), my (old) Xdebug configuration for some reason didn't want to work with my VSCode.
I spent a good few hours trying to figure it out, trying many different setups but with no luck. Xdebug didn't want to work.
So how to set it up correctly to make it work?

A: The main reason that it didn't work correctly anymore is that suddenly with the newest version of Homestead we have a Xdebug in version 3 which changes many options of Xdebug 2. It mostly simplifies the thing but also breaks previous setups. You can read more about the changes done to configuration variables in Xdebug 3 on their page.
For Xdebug to work on Homestead / Vagrant / macOS (Big Sur) these are the steps needed.

*

*You have to find xdebug.ini location which is easily done displaying phpinfo() and checking the path, which in my case is: /etc/php/7.3/fpm/conf.d/20-xdebug.ini

*Open it and edit: sudo vi /etc/php/7.3/fpm/conf.d/20-xdebug.ini:
My configuration looks like:
zend_extension=xdebug.so
xdebug.client_port = 9003
xdebug.max_nesting_level = 512

xdebug.mode=debug
xdebug.start_upon_error = true
xdebug.idekey = VSCODE

; The MacOS way
xdebug.discover_client_host = false
xdebug.client_host = 10.254.254.254

Things that has changed:

*

*the port - now it is 9003,

*for debugging setup - many options are now set using this one simple option: xdebug.mode=debug

*You have to save the file and restart php-fpm by: sudo service php7.3-fpm reload

*For macOS (on my Windows machine this wasn't needed) you have to:

Ensure you have created an Host address alias on MacOS and
10.254.254.254 is aliased to your localhost.

By doing: sudo ifconfig lo0 alias 10.254.254.254.
Which is in more detail also explained here.

*Install VSCode PHP Debug (vscode-php-debug) extension.

*Configure VSCode by clicking the debug icon from the left menu and then edit JSON file containing debugger configuration.
Paste this:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "My XDebug on Homestead",
            "type": "php",
            "request": "launch",
            "pathMappings": {
                "/home/vagrant/code/myproject": "${workspaceFolder}"
            },
            "port": 9003
        }
    ]
}

*Finally install Chrome Xdebug Helper extension and turn on the (green bug) debug mode when you want to do the debugging.

*One extra thing. If you want to enable/disable Xdebug, lets say for performance reasons there is a very easy and fast way to do this.
enable:
sudo phpenmod xdebug
sudo service php7.3-fpm reload

disable:
sudo phpdismod xdebug
sudo service php7.3-fpm reload

As you can see a lot of different things in different places must be set correctly to make it work. It takes a lot of googling and patience so I thought it would be useful to put it here for you and for my future installations. :)

A: First of all, make sure about which version of PHP-FPM your site is running (change laravel.test to the name of your configured site). Remember that you can choose the PHP version to use for each site in the Homested.yaml file.
$ cat /etc/nginx/sites-available/laravel.test | grep fastcgi_pass
        fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;

This will tell you which configuration file to edit in the Homestead virtual machine (NB: change 8.0 to your version of PHP, if different).
$ sudo nano /etc/php/8.0/fpm/conf.d/20-xdebug.ini

Here, you can remove all lines starting with xdebug.* and instead add these lines:
xdebug.mode=debug
xdebug.client_host=192.168.10.1
xdebug.client_port=9003
xdebug.max_nesting_level = 512

NB: 192.168.10.1 is by default the IP address of the host machine in VirtualBox, it is supposed to be different than your actual IP address in your LAN. Note that max_nesting_level is not necessary, it's a default by Homestead so I left it there.
Now in Visual Studio Code on your host machine you can set your launch.json file to the following:
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for Xdebug",
            "type": "php",
            "request": "launch",
            // "stopOnEntry": true,
            "pathMappings": {
                "/home/vagrant/laravel.test": "${workspaceFolder}"
            },
            "port": 9003
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 9003
        }
    ]
}

PS. I keep "stopOnEntry": true commented so that I can simply uncomment it when needed, otherwise I simply use breakpoints in vscode.

A: for Xdebug Version 3.0.3

*

*set IDE to use a debugging port - 9003

*modify the /etc/php/7.x/fpm/conf.d/20-xdebug.ini
zend_extension = xdebug.so
xdebug.remote_port = 9003
xdebug.max_nesting_level = 512
xdebug.mode = debug
xdebug.client_host = 192.168.10.1

If Homestead.yaml contains a different subnet for the IP address, this IP address may be different...
BTW, after editing 20-xdebug.ini, restart you FPM like so
$ sudo service php7.4-fpm restart

and restart your browser and IDE
PS
Tested on NetBeans and Vagrant (Laravel homestead) with php 7.4, host - WIN-10


text:
Q: How to compile sets of .ts files ito a single .js I want to compile a subset of my .ts files into a single .js file.  There is a question that addresses how to compile everything into a single .js file, but I just need a subset.
I've looked around tsconfig.json, but didn't see anything obvious.  Is there a way to do, preferably from the IDE (Visual Studio).

A: There is the outFile argument which is mentioned by the question you referenced but, as you state, it will compile everything into one file.  You could create a second tsconfig.json file (named tsconfig.subset.json or something) which uses the includes/excludes options to specify only the files you want but if any of the included files references any of the excluded files you will get an exception (e.g. the specific files must be self contained).
If you have a single file which you can use as an entry point that references only the subset of files you want bundled up you could use rollup or webpack.
Otherwise, if you just want to specify some specific collection of files that aren't really self contained I do not know any tools that do that.


text:
Q: Can !Ref and !Sub be used interchangeably on any use case in aws cloudformation Can !Ref and !Sub be used interchangeably in any use case? I need to substitute Parameter1 in environment variable LOCATION_UPDATE_SNS_TOPIC, So that this variable can be used programatically using python code inside the ec2. The Userdata property below for an ec2 instance is below.
UserData:
   Fn::Base64:
     !Sub |
     #!/bin/bash
     export LOCATION_UPDATE_SNS_TOPIC=!Sub Parameter1

or
UserData:
   Fn::Base64:
     !Sub |
     #!/bin/bash
     export LOCATION_UPDATE_SNS_TOPIC=!Ref Parameter1

A: In this case you neither use !Sub nor !Ref. You already declared with the first !Sub | that the following contains parameter. The correct solution would be:
UserData:
   Fn::Base64:
     !Sub |
     #!/bin/bash
     export LOCATION_UPDATE_SNS_TOPIC=${Parameter1}

You can find some examples here.


text:
Q: Response.Flush With Ajax is not working? I am following the following sample to create a very simple Comet in ASP.NET 4.5. What is the best way of showing progress on an Ajax call?
I have also downloaded the sample from http://www.aaronlerch.com/blog/2007/07/08/creating-comet-applications-with-aspnet/. I am not getting any response from Server.
Is Response.Flush is changed in ASp.NEt 4.5?
Update: Just remove the Thread.Sleep, everything works now.

A: I think dose not have radical change just add Asynchronously flushing a response
Asynchronously flushing a response

Sending responses to an HTTP client can take considerable time when
  the client is far away or has a low-bandwidth connection. Normally
  ASP.NET buffers the response bytes as they are created by an
  application. ASP.NET then performs a single send operation of the
  accrued buffers at the very end of request processing.

If the buffered response is large (for example, streaming a large file
    to a client), you must periodically call HttpResponse.Flush to send
    buffered output to the client and keep memory usage under control.
    However, because Flush is a synchronous call, iteratively calling
    Flush still consumes a thread for the duration of potentially
    long-running requests.
ASP.NET 4.5 adds support for performing flushes asynchronously using
    the BeginFlush and EndFlush methods of the HttpResponse class. Using
    these methods, you can create asynchronous modules and asynchronous
    handlers that incrementally send data to a client without tying up
    operating-system threads. In between BeginFlush and EndFlush calls,
    ASP.NET releases the current thread. This substantially reduces the
    total number of active threads that are needed in order to support
    long-running HTTP downloads.


text:
Q: What does "right on the line" mean in this context?
Others are right on the line. Robo advisors Betterment LLC and Wealthfront Inc. are each sitting at $700 million, and online money transfer startup WorldRemit has a valuation of $500 million.

source: http://www.bloomberg.com/news/articles/2016-09-06/why-fintech-startups-might-not-want-to-become-unicorns

A: Here 'right on the line' means 'at a threshhold' of some kind. The exact meaning depends on the context of the article, but the phrase implies the 'others' could go one way or the other.


text:
Q: django.db.utils.IntegrityError: FOREIGN KEY constraint failed - Django First, I know there are a lot of answers regarding this error, but I can't understand why this is erroring out in my case. I am learning Django and any help would be highly appreciated.
I have a Ticket model with ForeignKey reference to Category, Type & GHDUser as below
models.py
`
# from accounts/models.py
class GHDUser(AbstractBaseUser, PermissionsMixin):
    emp_id = models.IntegerField(primary_key=True)
    email = models.EmailField(_('email address'),unique=True)
    username = models.CharField(max_length=150, unique=True)

# from ticket/models.py
class Category(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name = 'Category'
        verbose_name_plural = 'Categories'

    def __str__(self):
        return self.name

class Type(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name = 'Type'
        verbose_name_plural = 'Types'

    def __str__(self):
        return self.name

class Ticket(models.Model):

    status_options = (
        ('open', 'Open'),
        ('pending', 'Pending'),
        ('closed', 'Closed')
    )

    priority_options = (
        ('high','High'),
        ('medium','Medium'),
        ('low','Low')
    )

    ticket_no = models.CharField(max_length=10, blank=True)
    title = models.CharField(max_length=100)
    description = models.TextField(max_length=1000)
    category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1)
    type = models.ForeignKey(Type, on_delete=models.PROTECT, default=1)
    file = models.FileField(upload_to=user_directory_path, blank=True, default='files/Default_Avatar.png')
    raised_by_user = models.ForeignKey(GHDUser, on_delete=models.CASCADE, related_name='raised_ticket')

`
Now, I am able to create an instance for Ticket model from Admin Panel, but when I try to do the same via shell / using data from front end, I am getting the below error.
django.db.utils.IntegrityError: FOREIGN KEY constraint failed

Can you please help me understand what I am doing wrong ?


text:
Q: Program a unix kill in Java I am writing a unit test for a Java program, and I need to simulate a Unix kill. Is there any way that this is possible?
Thanks!

A: In short, no, there isn't.
On a unix system, the best bet is to use Runtime.exec().


text:
Q: How to select last element in whole body using css? How can I select the latest paragraph in my body if I have two more divs? I tried with the last-child, last-type but it selects Paragraph 3, Paragraph 8, and Paragraph 10.
I need to select only paragraph 10 and make it italic.

Main Heading

Paragraph 1

Google
Google Doodles
Goto Link Group

Subheading

Paragraph 2

Paragraph 3

Sub subheading

Paragraph 4

Paragraph 5

Paragraph 6

Paragraph 7

Paragraph 8

Paragraph 9

Paragraph 10

A: This does the trick.

body>p:last-of-type {
  color: red;
}

Main Heading

Paragraph 1

Google
Google Doodles
Goto Link Group

Subheading

Paragraph 2

Paragraph 3

Sub subheading

Paragraph 4

Paragraph 5

Paragraph 6

Paragraph 7

Paragraph 8

Paragraph 9

Paragraph 10

A: body direct child and last paragraph element.
so, we can use body > p:last-of-type

body > p:last-of-type{
    background: #ff0000;
}
<!DOCTYPE html>

Main Heading

Paragraph 1

    Google
    Google Doodles
    Goto Link Group

Subheading

Paragraph 2

Paragraph 3

Sub subheading

Paragraph 4

Paragraph 5

Paragraph 6

Paragraph 7

Paragraph 8

Paragraph 9

Paragraph 10


text:
Q: Android ListView scroll to top without highlighting first item I use list.setSelection(0); to scroll the ListView to top, but this also unfortunately sets the highlight color of the top list item.
I just want it to scroll to top and not set the highlight color. (Android API 10)

A: You could use smoothScrollToPositionFromTop.
try
list.smoothScrollToPositionFromTop(0, 0);

or
list.smoothScrollToPositionFromTop(list.getHeaderViewsCount(), 0);

if your ListView has header.

A: You can try
list.smoothScrollBy(0, 1000);

or
if (!ListView.isStackFromBottom()) {
    ListView.setStackFromBottom(true);
}
ListView.setStackFromBottom(false);


text:
Q: Python: Regex for multiple characters in a line? I would like to understand and know how i can combine all these regex into one line.
I want to ignore lines that have the following characters (?,+,-,insA,insC,insG,insT,insU, and any line tht has ins and some number immediately after it, for example ins34 or ins99)
The following seems to work but not pretty. Any help is really appreciated.
    f1=re.search(r'\?(.+)$',line)
    f2=re.search(r'\+(.+)$',line)
    f3=re.search(r'\-(.+)$',line)
    f4=re.search(r'\insA(.+)$',line)
    f5=re.search(r'\insC(.+)$',line)
    f6=re.search(r'\insG(.+)$',line)
    f7=re.search(r'\insT(.+)$',line)
    f8=re.search(r'\insU(.+)$',line)

A: This should work:
if not re.search("[-?+]|ins[ACGTU\d]", line):
    # Do something

It will only run the "Do something" part if linedoesn't have a ?, a +, a -, a insA, a insC, a insG, a insT, a insU, or a ins followed by a number in it.


text:
Q: При нажатии кнопки в форме "отправить",не появляется всплывающее окно У меня есть форма обратной связи с модульным окном div на котором стоит изначально display:block. Нужно чтобы при нажатии на кнопку отправить,появлялось красивое окно об успешной отправке.Только вот заявка на почту отправляется ,а всплывающего окна нет.
вот моя форма

                            Имя

                         Телефон

                             E-mail

                         Отправить

вот модальное окно

OK

и свойства к нему
#modal{
   z-index: 999;
   width: 100%;
   height: 100%;
   position: absolute;
 display: none;
}

вот обработчик email на JS
$(document).ready(function() {

   //E-mail Ajax Send
   $("form").submit(function() { //Change
       var th = $(this);
       $.ajax({
           type: "POST",
           url: "mail.php", //Change
           data: th.serialize()
       }).done(function() {
           $("#modal").css("display", "block");
           setTimeout(function() {
               // Done Functions
               th.trigger("reset");
           }, 1000);
       });
       return false;
   });

});

и собственно PHP код
<?php

$method = $_SERVER['REQUEST_METHOD'];

//Script Foreach
$c = true;
if ( $method === 'POST' ) {

   $project_name = trim($_POST["project_name"]);
   $admin_email  = trim($_POST["admin_email"]);
   $form_subject = trim($_POST["form_subject"]);

   foreach ( $_POST as $key => $value ) {
       if ( $value != "" && $key != "project_name" && $key != "admin_email" && $key != "form_subject" ) {
           $message .= "
           " . ( ($c = !$c) ? '
':'
' ) . "
               $key
               $value

           ";
       }
   }
} else if ( $method === 'GET' ) {

   $project_name = trim($_GET["project_name"]);
   $admin_email  = trim($_GET["admin_email"]);
   $form_subject = trim($_GET["form_subject"]);

   foreach ( $_GET as $key => $value ) {
       if ( $value != "" && $key != "project_name" && $key != "admin_email" && $key != "form_subject" ) {
           $message .= "
           " . ( ($c = !$c) ? '
':'
' ) . "
               $key
               $value

           ";
       }
   }
}

$message = "
$message
";

function adopt($text) {
   return '=?UTF-8?B?'.Base64_encode($text).'?=';
}

$headers = "MIME-Version: 1.0" . PHP_EOL .
"Content-Type: text/html; charset=utf-8" . PHP_EOL .
'From: '.adopt($project_name).' <'.$admin_email.'>' . PHP_EOL .
'Reply-To: '.$admin_email.'' . PHP_EOL;

mail($admin_email, adopt($form_subject), $message, $headers );

Что я делаю не так?


text:
Q: react-apollo perfomance issue on android For me, it seems that  in react-apollo has some performance issues on Android
For example, I have a FlatList of elements, each of which has
<Query
        query={cardUniversalQuery}
        variables={{
          date: date.format(innerDateFormat)
        }}
        delay>
        {({ data }) => (
          <FlatList
            data={data && data.userDayActivities ? data.userDayActivities : []}
            renderItem={({ item }) => <ListItem {...item} />}
            keyExtractor={(item, index) => ((index).toString())} />)}
      </Query>

if remove Query - android and ios version works with roundly the same speed, while go through a list.
But if return that section back - it blocks JS thread until all queries in {windowSize} items are finished - so that UI is still response on scroll but their proper handlers can't be fired.
Ios work fine - just show empty space in place of query, and don't block JS/UI thread (perf monitor shows just reducing fps to the range of 30-50 on ios)

A: A new version of caching is coming. It helps a LOT! And make android version works as fast as IOS
link of upcoming PR: https://github.com/apollographql/apollo-client/pull/3394


text:
Q: Create a list of tuples with consecutive NaN values in all columns I'm trying to build a list of tuples with the consecutive start and end dates in which all columns have NaN values.
In the following example my result should be something like:
missing_dates = [('2018-10-10 20:00:00', '2018-10-10 22:00:00'),
('2018-10-11 02:00:00', '2018-10-11 03:00:00 ')]

If there 's a isolated NaN the value should be repeated in the tuple.
A dictionary example with a table for visualization.
   dicts = [
        {'datetime': '2018-10-10 18:00:00', 'variable1': 20, 'variable2': 30},
        {'datetime': '2018-10-10 19:00:00', 'variable1': 20, 'variable2': 30},
        {'datetime': '2018-10-10 19:00:00', 'variable1': 20, 'variable2': 30},
        {'datetime': '2018-10-10 19:00:00', 'variable1': 20, 'variable2': 30},
        {'datetime': '2018-10-10 20:00:00', 'variable1': np.nan, 'variable2': np.nan},
        {'datetime': '2018-10-10 21:00:00', 'variable1': np.nan, 'variable2': np.nan},
        {'datetime': '2018-10-10 22:00:00', 'variable1': np.nan, 'variable2': np.nan},
        {'datetime': '2018-10-10 23:00:00', 'variable1': 20, 'variable2': 30},
        {'datetime': '2018-10-10 23:00:00', 'variable1': 20, 'variable2': 30},
        {'datetime': '2018-10-11 00:00:00', 'variable1': 20, 'variable2': 30},
        {'datetime': '2018-10-11 01:00:00', 'variable1': np.nan, 'variable2': 30},
        {'datetime': '2018-10-11 02:00:00', 'variable1': np.nan, 'variable2': np.nan},
        {'datetime': '2018-10-11 03:00:00', 'variable1': np.nan, 'variable2': np.nan}]

Table representation:
----------------------+-----------+-----------+
|          datetime   | variable1 | variable2 |
+---------------------+-----------+-----------+
| 2018-10-10 18:00:00 |      20.0 |     30.0  |
| 2018-10-10 19:00:00 |      20.0 |     30.0  |
| 2018-10-10 19:00:00 |      20.0 |     30.0  |
| 2018-10-10 19:00:00 |      20.0 |     30.0  |
| 2018-10-10 20:00:00 |       NaN |     NaN   |
| 2018-10-10 21:00:00 |       NaN |     NaN   |
| 2018-10-10 22:00:00 |       NaN |     NaN   |
| 2018-10-10 23:00:00 |      20.0 |     30.0  |
| 2018-10-10 23:00:00 |      20.0 |     30.0  |
| 2018-10-11 00:00:00 |      20.0 |     30.0  |
| 2018-10-11 01:00:00 |       NaN |     30.0  |
| 2018-10-11 02:00:00 |       NaN |     NaN   |
| 2018-10-11 03:00:00 |       NaN |     NaN   |
+---------------------+-----------+-----------+

What i did:
df = pd.DataFrame(example_dict)
s = dframe.set_index('datetime').isnull().all(axis=1)
df['new_col'] = s.values
dframe.datetime = pd.to_datetime(dframe.datetime)
new_df = dframe.loc[dframe['new_col'] == True]
new_df['delta'] = (new_df['datetime'] - new_df['datetime'].shift(1))

I got a nice dataframe with a delta but i'm a little lost.

A: Use:
#create boolean mask for not NaNs rows
mask = df.drop('datetime', axis=1).notnull().any(axis=1)
#create groups for missing rows with same values
df['g'] = mask.cumsum()

#aggregate first and last, convert to nested lists and map to tuples
L = list(map(tuple, df[~mask].groupby('g')['datetime'].agg(['first','last']).values.tolist()))
print (L)
[('2018-10-10 20:00:00', '2018-10-10 22:00:00'),
 ('2018-10-11 02:00:00', '2018-10-11 03:00:00')]

Similar solution, only mask is inverted:
mask = df.drop('datetime', axis=1).isnull().all(axis=1)
df['g'] = (~mask).cumsum()

L = list(map(tuple, df[mask].groupby('g')['datetime'].agg(['first','last']).values.tolist()))
print (L)
[('2018-10-10 20:00:00', '2018-10-10 22:00:00'),
 ('2018-10-11 02:00:00', '2018-10-11 03:00:00')]


text:
Q: Silverlight 5 not printing on some printers I have a Silverlight 5 OOB application (with Elevated Permissions) that's just been deployed to a number of our users.
Some of these users are reporting that prints are coming out blank or very faint.
These printers do print Word documents correctly and I am unable to reproduce the problem on my own printers.
All users are on Windows XP SP3 32 bit, and I am developing on Win7 64 bit.
As anyone seen this issue before? Or any idea what could be causing this?
Help much appreciated.
Many Thanks,
Andrew

A: I Should Got Solution May Be useFull To You.............................
First i created a new PrintDocument, and hooked up some handlers for its PrintPage event.
mobjPrintDocument = New PrintDocument
RemoveHandler mobjPrintDocument.PrintPage, AddressOf Print_Report
AddHandler mobjPrintDocument.PrintPage, AddressOf Print_Report

Then we can call the PrintBitmap function on the PrintDocument whenever you want to print. Here I am doing it when the user clicks the Print button.
Private Sub xbtnPrint_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
    mintPageIndex = 0
    mobjPrintDocument.PrintBitmap(FileName)
  End Sub

Now comes the important part. We can hijack the content targeted by hooking into the PrintPage event (as handled above). I can set the e.PageVisual to any visual xaml element and the PrintBitmap will handle it. Here I use the GetPages function and loop through to make sure I print each page (a pdfviewer element). However, you can point it to any visual element like I said.
Private Sub Print_Report(sender As System.Object, e As PrintPageEventArgs)
    e.PageVisual = xobjReportViewer.GetPages(mintPageIndex)
    mintPageIndex += 1
    e.HasMorePages = mintPageIndex < xobjReportViewer.GetPages.Count
  End Sub

The e.HasMorePages allows you to force the firing of this event until you are finished.
Hope this is helpful to someone. With Silverlight 5 and the Post-Script printer support, alot of printers that have a PostScript emulator may not be compatible, but will also not default to bitmap printing. This workaround fixes that, making printing a little bit more stable in a LOB type application.


text:
Q: Moving on the map in navigation mode - Skobbler map Framework As soon as the app starts, I need to start free navigation mode in order to be notified about streetType changes.
However, there are cases where certain Annotations are placed on the map, and user should be able to move around on the map, away from user's current location, and browse those annotations.
It's possible to zoom in and out, while in navigation mode, but is it possible to move around the map ?

A: Check if this is possible if you enable panning after you startNavigation (see the enterPanningState code in the demo project).
Something like:
- (void)enterPanningState {
    [self showPanningUI];

    self.mapView.settings.followUserPosition = NO;
    self.mapView.settings.displayMode = SKMapDisplayMode2D;
}


text:
Q: Avoid code duplication of try/except blocks, from a class I have a class Test which is a subclass of another one (which is already a context manager, I chose nullcontext here for simplicity).
How to avoid to repeat the try/except blocks, and have this directly in the class definition?
Unlike Avoiding Multiple Try/Except blocks in Python and its answers, I'd like to do it with the class instead of creating a new function.
Example:
import contextlib

class Test(contextlib.nullcontext):
    pass

try:
    with Test('abc') as t1:
        do_something(t1)
        do_something_else()
except ValueError:      # these exceptions are thrown from Test's parent
    print('a')          # class/context-manager methods  (nullcontext in this example)
except KeyError:
    print('b')

try:
    with Test('def') as t2:
        do_something(t2)
        do_this(t2)
except ValueError:
    print('a')
except KeyError:
    print('b')

TL;DR: How to move the try:, except ValueError:, except KeyError: into the class Test?

A: Does putting the code in __init__ solve your problem?
import contextlib

class Test(contextlib.nullcontext):
    def __init__(self, abc, *args, **kwargs):
        super().__init__(*args, **kwargs)
        try:
            if abc == 'def':
                raise ValueError("VALUEERROR")
            elif abc == 'ghi':
                raise KeyError("KEYERROR")
            else:
                print("OK")
        except ValueError:
            print('a')
        except KeyError:
            print('b')

x1 = Test('abc')
x2 = Test('def')
x3 = Test('ghi')


text:
Q: Difference between it and so What is the difference between

I think it would be wise to do so.

and

I think it would be wise to do it.

Do 'so' and 'it' have the same grammatical category?

A: to do so is a very specific idiom meaning to act in the way mentioned, this could be a single action, but it is more likely to involve some long term plan. It is also more formal, and is therefore appropriate when giving professional advice.

Are you going to stop smoking? I think it would be wise to do so

to do it, on the other hand, refers more to a single action.

There is a parachute jump next week: do you want to do it?

In most situations, either would be appropriate.


text:
Q: What are the security concerns when passing a hashed password around? I have a Silverlight control on a web page and would like to pass the username and the hashed password to this control as part of the InitParams.
What are the security concerns with doing this?
The user has to log in to get to this page. However, I'm guessing that the browser might cache the page with the Silverlight control and this would cache the username and hashed password.
This brings me on to a more specific question: Is there a an HTML meta tag that tells a browser not to cache a page?

A: Security: Think first about potential uses a malicious user might have for the hashed password (including comparison with other stored hashes).
Caching: Yes there is a meta tag, but you shouldn't use it unless you have to; better to set the HTTP headers

HTML authors can put tags in a document's  section that describe its attributes. These meta tags are often used in the belief that they can mark a document as uncacheable, or expire it at a certain time.
Meta tags are easy to use, but aren't very effective. That's because they're only honored by a few browser caches (which actually read the HTML), not proxy caches (which almost never read the HTML in the document). While it may be tempting to put a Pragma: no-cache meta tag into a Web page, it won't necessarily cause it to be kept fresh.

*

*from the Caching Tutorial for Web Authors and Webmasters (HTML Meta Tags and HTTP Headers)

A: If an attacker can get at the hashed password, he could potentially reverse it by using a rainbow table. A rainbow table is basically a huge database of all possible passwords up to a certain size, indexed by their hash. I think of it as the ultimate speed-space trade-off. For passwords of up to 7 characters, containing only lower case letters and numbers, the rainbow table can fit in a few gigabytes. For longer passwords (or ones with less character restrictions) the required size does rise exponentially.
To defeat this attack, you need to salt the hashes. Salting means that you add a random salt value to the password before hashing it. This salt can be stored unencrypted next to the hash. Since each password is hashsed with another random salt, the rainbow lookup table becomes useless. Rainbow tables cannot consider all possible salt values because the required database size rises exponentially with the salt size.
Even then, weak passwords matching the salt+hash could still be found with brute force. This can be fixed by using some quality-control heuristics on the password (minimal length, mixes certain character types like lowercase/uppercase/digits/other, not just a 1 at the end...).
All in all, I'd say the security risks of exposing the hash are big enough that you're better of avoiding it.

A: My question would be, what can the control do with the hashed password? It doesn't seem like it could serve any useful purpose, so why is it passed to the control?
A password is hashed to make it computationally infeasible to recover the original password. So, assuming the hash was done properly, there's no risk in exposing it. But, the fact that the control thinks it needs the hashed password makes me suspicious.

A: Keep in mind that MD5 hashing has been cracked by brute force attacks, so having a hashed password in the open is not 100% secure, but for most cases it may be a non issue especially if you use some stronger hashing algorithm.


text:
Q: How to Create waterfall chart in dc.js I am trying to create a waterfall chart using dc.js it seems there are not many examples for waterfall chart. How do I achive waterfall chart similar to this one from http://bl.ocks.org/chucklam/f3c7b3e3709a0afd5d57 ?
PS: Will update the answer with a proper solution once I get a hint of the chart. I am trying to create more advanced charts which can be extended as part of dc.js examples.

A: This might be a late reply to the thread. I'm adding an answer in case anyone else (in addition to the original poster) hits the same question. The code representing my answer is on GitHub. I will give an explanation here as my git repo still lacks a proper readme file (apologies).
The trick is to create two (crossfilter) groups, one containing your real data and the other a dummy data. This dummy data is supposed to serve as support for your columns in the waterfall chart (you can also think of them as the shadow of each column of your data). The values for this dummy data follows this formulation:
Dummy value of current column = previous dummy value + previous real data value

The formula above doesn't account for the first and last columns though. They should be set manually (before and after the loop respectively) if the formula is used within a loop. The first column's dummy value should be 0 and the last one equal to the last value from your real data. Also, some decoration must be done on the chart to render the dummy columns invisible (even when selected/deselected). This feature too is available in the git code.


text:
Q: How to get all children in kendo ui treelist? How can I get all the children for selected row in kendo ui treelist :

I want to get direct children for Backframe that would be level 3 rows.

A: You need to iterate through the datasource comparing the id of the row to the parentid of each row:
   change: function(e) {
      var selectedRows = this.select();
      if (selectedRows.length > 0){
        var dataItem = this.dataItem(selectedRows[0]);
        var curID = dataItem.id;
        var ds = $(this)[0].dataSource.data();
        var children = [];
        for (var i=0; i<ds.length; i++){
          var pid =  ds[i].parentId;
          if (pid == curID){
            children.push(ds[i].Name)
          }
        }
        alert(children);
      }
     },

DEMO

A: TreeList has dataSource.childNodes method for this purpose.
change: function(e) {
    var selectedRows = this.select();
    if (selectedRows.length > 0){
        var dataItem = this.dataItem(selectedRows[0]);
        var children=this.dataSource.childNodes(dataItem);

        console.log(children);
    }
}


text:
Q: What does "have anything to do with you" mean in this quote?
People will love you, people will hate you, and none of it will have anything to do with you. —Abraham Hicks

In this sentence what is the meaning of "will have anything to do"?

A:
None of it will have anything to do with you

It means that your decisions and actions won't change anything. It doesn't matter what you do, some people will hate you and some people will love you.

A: You need to understand the phrase:

to have something to do with (something/someone)

It means "to be related to something" or "to be the cause of something", or "being involved", but without mentioning in which way the two are related.
More information can be found here or here.
So, regarding your quote:

People will love you, people will hate you, and none of it will have anything to do with you. — Abraham Hicks

Meaning: The reaction of people (here: "love", "hate") will not be related to you (neither as a person nor regarding your actions).
(As far as grammar is concerned, please remember that "some" changes to "any" for negative phrases.)

A: People will like you or people will hate you.  You won't be responsible for the way people respond to you.   We say "people take a liking to" someone, or they don't.


text:
Q: SVG image not rendering properly in IE11 / Edge unless container has fixed width Both Edge and Internet Explorer 11 seem to scale SVG images rather differently than regular raster images.
Take a look at the following example:

.container {
  display: flex;
  flex-flow: row nowrap;
}

.box {
  flex: 0 1 auto;
  background: red;
}

.fill {
  flex: 1 0 auto;
  background: green;
}

.box img {
  display: block;
  width: auto;
  height: 150px;
  background: blue;
}

fill

fill

Both images are identical, the first is a PNG, the other is an SVG. Both images reside in a .box which is set to flex-shrink but not flex-grow. Next to the box is a .fill which is set to flex-grow, but not flex-shrink.
So, the idea is really simple. We set each image's height to some fixed value, the width gets calculated automatically keeping the aspect ratio of the image, which respectfully sets the width of the .box container. .fill occupies the rest of the available space.
The example works just fine both in Chrome and Firefox, and two identical images are being displayed:

In Edge however, the image is cropped:

Where in IE it's even weirder:

You can view the source of the SVG here: http://imgh.us/logo-light_1.svg
I've also tried a couple of different values for the preserveAspectRatio attribute of the SVG all with different results, but still not the one I'm actually looking for.
Am I missing something? Is this just a matter of a proper preserveAspectRatio attribute or is it a bug?

A: As you've noted, a fixed width on the image container gets this to work on IE11.
This worked for me:
.box {
    flex: 0 1 461px;   /* changed flex-basis from auto */
    background: red;
}

If that's not an option, and you simply want PNG and SVG to match, then a positive z-index value will shift the blue background to the surface.
.box {
    flex: 0 1 auto;
    background: red;
    z-index: 1;        /* new */
}

Note that z-index does not need to be positioned when applied to flex items (reference).

Another possible solution would be placing the image in a flex container, then defining the width (as opposed to the height) of the image:
.box {
  flex: 0 1 auto;
  background: red;
  display: flex;      /* new */
}

.box img {
  /* display: block; */
  /* width: auto; */
  /* height: 150px; */
  background: blue;
  width: 332px;     /* new; value can be anything, PNG and SVG will match */
}


text:
Q: Setting\Placing a DIV(CSS Layer) with table cell as reference you may skip the following HTML code to proceed to actual question

the output of the above code will be somewhat like this

now i want i CSS Layer (a DIV) setup with the center-cell (red bordered cell) as its REFERENCE how to do it...
 #myLayer{
 position: ? ;
 left    : ? ;
 right   : ? ;
 top     : ? ;
 bottom  : ? ;
 padding : ? ;
 width   : * ;
 height  : * ;
 z-index : 2 ;
 }

and where to place the

 tag

A: Not exactly sure if this is what you're trying to do, but you could give the red-bordered td an id and place the div inside of it. Then use the following CSS:
#mainTD {
    position: relative;
}

#myLayer {
    position: absolute;
    top: 0;
    left: 0;
}

I never use tables for layout so I don't know if this will react how I think it will, but this should make #myLayer's top, left, bottom, and right coordinates relative to the coordinates of its parent, #mainTD. So in the instance above, with top and left set to 0, #myLayer's top-left corner should be at #mainTD's top-left corner.


text:
Q: android timer problem I have question. is this code timer correct;]? or i can do it more easily
package timer2.android;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Timer2Activity extends Activity {

private TextView tv;
private Timer myTimer;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tv = (TextView)findViewById(R.id.textView1);

    myTimer = new Timer();
    myTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            TimerMethod();
        }

    }, 0, 1000);
}

private void TimerMethod()
{

    //This method is called directly by the timer
    //and runs in the same thread as the timer.

    //We call the method that will work with the UI
    //through the runOnUiThread method.
    this.runOnUiThread(Timer_Tick);
}

long mStartTime = System.currentTimeMillis();

private Runnable Timer_Tick = new Runnable() {
    public void run() {
        final long start = mStartTime;
        long millis = System.currentTimeMillis() - start;
        int seconds = (int) (millis / 1000);
        int minutes = (int) (seconds / 60);
         seconds     = seconds % 60;

         if (seconds < 10)
         {
            tv.setText("" + minutes + ":0" + seconds);
         }
         else
         {
            tv.setText("" + minutes + ":" + seconds);
         }

         //a++;

    //This method runs in the same thread as the UI.

    //Do something to the UI thread here

    }
};

}

A: Can't see anything wrong here. But you should use Handler for timers as it does not create additional threads. See example here: Repeat a task with a time delay?


text:
Q: How to dynamically change Form Tab Titles in October CMS Is there an efficient method or plugin to dynamically change a Form Tab's title in the October CMS backend?
Similar to how it's done from the Builder plugin, but a bit more user-friendly:
enter image description here

A: You can listen for backend.form.extendFieldsBefore event. You can combine it with DB fetch data from DB and use here (which may be entered by the some user ..)

Write down this in your plugin's boot method.

<?php

class Plugin extends PluginBase
{
    public function boot() {

      \Event::listen('backend.form.extendFieldsBefore', function($widget) {

          if (!$widget->model instanceof \RainLab\User\Models\User) {
              // --------------------------------- ^ Check if its your modal
              return; // other wise do nothing return
          }

          // rainlab.user::lang.user.account =>
          // translated to Account by Lang Manager

          // need to change
          // "rainlab.user::lang.user.account" => 'My Account - OK'
          // if you need to change tab's title
          // you need to change it for all fields
          // which uses that same tab title

          foreach ($widget->tabs['fields'] as $key => $val) {
            if($val['tab'] === 'rainlab.user::lang.user.account') {
              $widget->tabs['fields'][$key]['tab'] = 'My Account - OK';
            }
          }

      });

    ...
}

before result

after result

if any doubt please comment


text:
Q: Get total amount of hours from 2 variables Here is my code:
$time = "20:58:05";
$time2 = "10:40:00";

$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
echo $result;

The output of the above code is - 07:38:05
i want it to display like this - 31:38:05. How can i achieve this?

A: Convert both times to seconds, add them, and then calculate the hours, minutes, and seconds yourself.
$time = "20:58:05";
$time2 = "10:40:00";

$secs = strtotime($time)-strtotime("00:00:00");
$secs2 = strtotime($time2)-strtotime("00:00:00");
$total = $secs + $secs2;
$hours = floor($total/3600);
$mins = floor(($total % 3600) / 60);
$secs = $total % 60;
echo sprintf("%d:%02d:%02d", $hours, $mins, $secs);

A: The solution of Barmar works when adding hours that are below 24:00:00, but when you add 2 variable with each variable exceeds 24:00:00 it gives a wrong output. For example:
$time = "20:58:05";
$time2 = "30:40:00";

$secs = strtotime($time)-strtotime("00:00:00");
$secs2 = strtotime($time2)-strtotime("00:00:00");
$total = $secs + $secs2;
$hours = floor($total/3600);
$mins = floor(($total % 3600) / 60);
$secs = $total % 60;
echo sprintf("%d:%02d:%02d", $hours, $mins, $secs);

output of the above code: -431348:-2:-55
Here is a code that works even if the data of the variables exceeds 24:00:00:
  function sum_the_time($time1, $time2) {
  $times = array($time1, $time2);
  $seconds = 0;
  foreach ($times as $time)
  {
    list($hour,$minute,$second) = explode(':', $time);
    $seconds += $hour*3600;
    $seconds += $minute*60;
    $seconds += $second;
  }
  $hours = floor($seconds/3600);
  $seconds -= $hours*3600;
  $minutes  = floor($seconds/60);
  $seconds -= $minutes*60;
  if($seconds < 9)
  {
  $seconds = "0".$seconds;
  }
  if($minutes < 9)
  {
  $minutes = "0".$minutes;
  }
    if($hours < 9)
  {
  $hours = "0".$hours;
  }
  return "{$hours}:{$minutes}:{$seconds}";
}

i found this code here


text:
Q: Calculating Average and median on Monthly data and convert in htmltable R I have a DF:
my_data <- read.table(text =
                      "ID     Date1                     T1     Date2     Val1
                      A-1    '2018-01-10 15:05:24'       A    2018-01-15  10
                      A-2    '2018-01-05 14:15:22'       B    2018-01-14  12
                      A-3    '2018-01-04 13:20:21'       A    2018-01-13  15
                      A-4    '2018-01-01 18:35:45'       B    2018-01-12  22
                      A-5    '2017-12-28 19:45:10'       A    2018-01-11  18
                      A-6    '2017-12-10 08:03:29'       A    2018-01-10  21
                      A-7    '2017-12-06 20:55:55'       A    2018-01-09  28
                      A-8    '2018-01-10 10:02:12'       A    2018-01-15  10
                      A-9    '2018-01-05 17:15:14'       B    2018-01-14  12
                      A-10   '2018-01-04 18:35:58'       A    2018-01-13  15
                      A-11   '2018-01-01 21:09:25'       B    2018-01-12  22
                      A-12   '2017-12-28 02:12:22'       A    2018-01-11  18
                      A-13   '2017-12-10 03:45:44'       A    2018-01-10  21
                      A-14   '2017-12-06 07:15:25'       A    2018-01-09  28
                      A-18   '2017-10-07 08:02:84        B    2017-11-05  20
                      A-21   '2017-10-01 06:04:04        A    2017-10-20  15
                      A-51   '2017-09-20 08:07:06        A    2017-09-28  10
                      A-35   '2017-09-14 08:02:45        A    2017-09-25  20
                      A-30   '2017-08-10 15:03:08        A    2017-08-30  25",
header = TRUE, stringsAsFactors = FALSE)

and running below mentioned code i get output as shown in below:
    table_2 <- merge(
  my_data %>%
    mutate(Date2 = ymd(Date2)) %>%
    arrange(Date2) %>%
    mutate(Month = paste(month(ymd_hms(Date1), label = TRUE), year(Date1), sep = "-")) %>%
    filter(T1 == "A") %>%
    group_by(Month) %>%
    summarise("# of A" = n(),
              "sum of A" = sum(Val1)) %>%
    mutate("MOM Growth # of A" = round(apply(cbind(`# of A`, lag(- `# of A`)),
                                       1, sum, na.rm = TRUE) / lag(`# of A`), 2),
           "MOM Growth sum of A" = round(apply(cbind(`sum of A`, lag(- `sum of A`)),
                                         1, sum, na.rm = TRUE) / lag(`sum of A`) * 100, 2)) %>%
    select(Month, `# of A`, `MOM Growth # of A`, `sum of A`, `MOM Growth sum of A`),
  my_data %>%
    mutate(Date2 = ymd(Date2)) %>%
    arrange(Date2) %>%
    mutate(Month = paste(month(ymd_hms(Date1), label = TRUE), year(Date1), sep = "-")) %>%
    filter(T1 == "B") %>%
    group_by(Month) %>%
    summarise("# of B" = n(),
              "sum of B" = sum(Val1)) %>%
    mutate("MOM Growth # of B" = round(apply(cbind(`# of B`, lag(- `# of B`)),
                                       1, sum, na.rm = TRUE) / lag(`# of B` * 100), 2),
           "MOM Growth sum of B" = round(apply(cbind(`sum of B`, lag(- `sum of B`)),
                                         1, sum, na.rm = TRUE) / lag(`sum of B`) * 100), 2) %>%
    select(Month, `# of B`, `MOM Growth # of B`, `sum of B`, `MOM Growth sum of B`),
  by = "Month",
  all = TRUE)

table_2[is.na(table_2)] <- ""

Output (table_2):

Now i want to add two more column Median of A , Avg Time of A under Status of A head and Median of B, Avg Time of B in Status of B head. and convert those output in htmltable format.
Just wanted to know how to tweak code in summarise to calculate these value on monthly data.
in addition, month should be in sequence order in output data & if there is any month missing between Max month and Min month than that month should come with all value 0 except MOM Growth for both Status of A and Status of B because that should be than -100%.

A: Here is an attempt using:
library(dplyr)
library(lubridate)
library(tableHTML)

I have added a median and avg time column for A and B, plus added the MOM Growth condition, and ensured that the Months are 1) in the correct order and 2) complete, even if no data is available in a particular month.
In order to get all Months, create a date sequence from the first to the last date in your data (with 1 month step in between). Then make sure both groups A and B have a date (because there is a filter later on):
date_range = expand.grid(Date1 = seq(min(ymd_hms(my_data$Date1)), max(ymd_hms(my_data$Date1)),
                                     by = "1 month"),
                         T1 = c("A", "B"),
                         stringsAsFactors = FALSE)

table_2 <- merge(
  my_data %>%
    mutate(Date2 = ymd(Date2),
           Date1 = ymd_hms(Date1)) %>%
    full_join(date_range, by = c("Date1", "T1")) %>% # join date ranges to table
    arrange(Date1) %>% # sort by date
    mutate(Month = paste(month(Date1, label = TRUE), year(Date1), sep = "-"),
           row_number = row_number(), # create row_numbers to keep up order
           Val1 = coalesce(Val1, 0L)) %>% # replace NA with 0 in Val1
    filter(T1 == "A") %>%
    group_by(Month) %>%
    summarise("# of A" = n(),
              "sum of A" = sum(Val1, na.rm = TRUE),
              "Median of A" = median(Val1, na.rm = TRUE), # compute median
              "Avg Time of A" = round(mean(difftime(Date2, Date1),
                                           na.rm = TRUE), # compute avg time
                                      2),
              row_number = min(row_number)) %>% # get min row number
    arrange(row_number) %>% # sort by row number (to sort months)
    mutate("MOM Growth # of A" = round(apply(cbind(`# of A`, lag(- `# of A`)),
                                             1, sum, na.rm = TRUE) / lag(`# of A`), 2),
           "MOM Growth sum of A" = round(apply(cbind(`sum of A`, lag(- `sum of A`)),
                                               1, sum, na.rm = TRUE) / lag(`sum of A`) * 100, 2)) %>%
    mutate("MOM Growth # of A" = if_else(is.infinite(`MOM Growth # of A`), 100, `MOM Growth # of A`), # replace Inf with 100
           "MOM Growth sum of A" = if_else(is.infinite(`MOM Growth sum of A`), 100, `MOM Growth sum of A`)) %>%
    select(Month, `# of A`, `MOM Growth # of A`,
           `sum of A`, `MOM Growth sum of A`,
           `Median of A`, `Avg Time of A`),
  my_data %>%
    mutate(Date2 = ymd(Date2),
           Date1 = ymd_hms(Date1)) %>%
    full_join(date_range, by = c("Date1", "T1")) %>%
    arrange(Date1) %>%
    mutate(Month = paste(month(Date1, label = TRUE), year(Date1), sep = "-"),
           row_number = row_number(),
           Val1 = coalesce(Val1, 0L)) %>%
    filter(T1 == "B") %>%
    group_by(Month) %>%
    summarise("# of B" = n(),
              "sum of B" = sum(Val1, na.rm = TRUE),
              "Median of B" = median(Val1, na.rm = TRUE),
              "Avg Time of B" = round(mean(difftime(Date2, Date1),
                                           na.rm = TRUE),
                                      2),
              row_number = min(row_number)) %>%
    arrange(row_number) %>%
    mutate("MOM Growth # of B" = round(apply(cbind(`# of B`, lag(- `# of B`)),
                                             1, sum, na.rm = TRUE) / lag(`# of B`), 2),
           "MOM Growth sum of B" = round(apply(cbind(`sum of B`, lag(- `sum of B`)),
                                               1, sum, na.rm = TRUE) / lag(`sum of B`) * 100, 2)) %>%
    mutate("MOM Growth # of B" = if_else(is.infinite(`MOM Growth # of B`), 100, `MOM Growth # of B`),
           "MOM Growth sum of B" = if_else(is.infinite(`MOM Growth sum of B`), 100, `MOM Growth sum of B`)) %>%
    select(Month, `# of B`, `MOM Growth # of B`,
           `sum of B`, `MOM Growth sum of B`,
           `Median of B`, `Avg Time of B`),
  by = "Month",
  all = TRUE,
  sort = FALSE) # do not sort by ID column to keep month order

'Remove' missing values:
table_2[is.na(table_2)] = ""

Create a tableHTML from that data:
table_2 %>% tableHTML(rownames = FALSE,
                      widths = rep(100, 13),
                      second_headers = list(c(1, 4, 4),
                                            c("", "Status of A", "Status of B")),
                      caption = "A & B consolidated") %>%
  add_css_caption(css = list(c("font-weight", "border"),
                             c("bold", "1px solid black")))

And this is the result:


text:
Q: Why can't my App find my plist file? This is my first question I've posted here and am new at this, so be gentle. :-)
I'm using Xcode 6.1
My project shows these folders:
ToDoList
ToDoListTests
Frameworks
Products
![enter image description here][1]
I manually created a plist file using File->New->IOS/Resource->Property List and named it ToDoListData.plist
The plist is located in the ToDoList folder with my source files.
![enter image description here][2]
I'm using this code to read the file into an NSMutableArray named toDoItems but there are 2 problems.

*

*the plist file isn't found -> in Xcode, where/what folder do I need to place plist so that it ends up in the documents folder in simulator so it can be found?

*toDoItems variable is unused - not sure why because I thought that the code was suppose to read the values from the plist into the mutable array toDoItems
Hope that I have been able to clearly convey the problem. (I've been stuck for 4 hours)
Thanks for your help.
- (void)loadInitialData
{

//    JNMToDoItem *item1 = [[JNMToDoItem alloc] init];
//    item1.itemName = @"Buy milk";
//    [self.toDoItems addObject:item1];
//
//    JNMToDoItem *item2 = [[JNMToDoItem alloc] init];
//    item2.itemName = @"Buy eggs";
//    [self.toDoItems addObject:item2];
//
//    JNMToDoItem *item3 = [[JNMToDoItem alloc] init];
//    item3.itemName = @"Read a book";
//    [self.toDoItems addObject:item3];

    [self loadData];

}

-(void)loadData
{

    NSString *plistPath = [self getFilePath];

    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:plistPath];

    NSLog(@"Does the file exist?: %@", @(fileExists));

    if(fileExists)
    {

        NSLog(@"The value of the path is: %@",plistPath);

        NSMutableArray *toDoItems = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
    }else{
        NSLog(@"File does not exist");
    }

}

-(NSString *)getFilePath
{

    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    return [[pathArray objectAtIndex:0] stringByAppendingPathComponent:@"ToDoListData.plist"];

}

A: Drag the plist file into your project in XCode. It'll then come up with a screen asking if you want to copy the items and which targets to select. Make sure you select "copy items if needed" and also tick your project under "targets".
That way, it should be found in the code.


text:
Q: Can programmers be called code authors? Can programmers be called code authors or any other term similar in meaning to a book author?

A: Yes, but it must be used judiciously and rarely to avoid sounding pretentious.

A: Doxygen, a source code documentation system that supports several languages, uses the  \author tag to document who authored the code.
Here's a C++ example:
//! \class  GargleBlaster
//! \brief  Alcoholic equivalent of a mugging
//! \author Zaphod Beeblebrox

A: Here is an example of poetry in Perl. Flexible syntax allows to write so.
https://gist.github.com/1610861
Yes, programmers can be called code authors.

A: As a programmer myself, I say "why the hell not?" — But I guess that's biased?
However, Merriam-Webster does seem to agree with me as it defines 'author' as:
"one that originates or creates" and cites software authors as an example.
So in both my opinion and the accepted definition of the word author, yes, a programmer can be considered an author.

A: In Spain and other European countries (France and Portugal at least), software cannot be patented; its commercial protection is achieved through intellectual property laws, the equivalent to the anglosaxon concept of copyright. Intellectual property laws, which explicitly include software, speak of a creator or author of the work being protected.
So I guess yes, author is a good term for someone who has created a piece of software.

A: It certainly used to be; "Author" is a reserved word in Cobol used in the Identification Division like this

Author: Ben Large.

to record the name of the programmer. I haven't come across it in any other language I've used and I've never heard people referring to themselves as Software Authors but you could claim the Cobol convention as a reason for using it if you want.


text:
Q: GTK - Python Treeview Selecting A Row Programmatically I have a GTK3 GUI (with Python 3.7). There is a treeview on the GUI and sorting, filtering is used. I need to select a row by using code. It works when sorting is not used. It selects wrong row when sorting is used by clicking on column header buttons.
What is the solution for this?
Here is the simplified code:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

builder = Gtk.Builder()
builder.add_from_file('test1.glade')
window1 = builder.get_object('window1')
treeview1 = builder.get_object('treeview1')

class Signals:
    def on_window1_destroy(self, widget):
        Gtk.main_quit()

file_data = [[True, "a", 1],
             [True, "b - select this", 2],
             [True, "c", 3],
             [True, "d", 4]]

treestore1 = Gtk.TreeStore(bool, str, int)
iter1 = treestore1.append(None, file_data[0])
iter2 = treestore1.append(None, file_data[1])
iter3 = treestore1.append(None, file_data[2])
iter4 = treestore1.append(None, file_data[3])

#treeview1.set_model(treestore1)
treemodelfilter1 = treestore1.filter_new()
treemodelfilter1.set_visible_column(0)
treemodelsort1 = Gtk.TreeModelSort.new_with_model(treemodelfilter1)
treeview1.set_model(treemodelsort1)

for i, column_title in enumerate(["Column1", "Column2"]):
    renderer = Gtk.CellRendererText()
    column = Gtk.TreeViewColumn(column_title, renderer, text=i+1)
    column.set_sort_column_id(i+1)
    treeview1.append_column(column)

treeview1.get_column(1).clicked()
treeview1.get_column(1).clicked()
#treeview1.get_selection().select_iter(iter2)
path = treestore1.get_path(iter2)
treeview1.get_selection().select_path(path)

builder.connect_signals(Signals())
window1.show_all()
Gtk.main()

Here is the Glade designer GUI file:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.22.1 -->
<interface>
  <requires lib="gtk+" version="3.20"/>
  <object class="GtkWindow" id="window1">
    <property name="can_focus">False</property>
    <property name="default_width">300</property>
    <property name="default_height">300</property>
    <child>
      <placeholder/>
    </child>
    <child>
      <object class="GtkTreeView" id="treeview1">
        <property name="visible">True</property>
        <property name="can_focus">True</property>
        <child internal-child="selection">
          <object class="GtkTreeSelection"/>
        </child>
      </object>
    </child>
  </object>
</interface>

A: For anybody else coming here, the actual problem is that it doesn't turn out well to mix iters or paths between different models of the same Treeview. If you get a path of the filtered store, don't apply it to the sorted store, etc, etc. There are ways around this, but they are very complicated. They deserve a whole article explaining the nuances. In practice, if you need operate on the path of a store, get your info from that same store.

A: I have fixed the problem by using the following code:
treeview1.get_column(1).clicked()     # Existing code in the question
treemodelsort1.set_sort_column_id(1, Gtk.SortType.ASCENDING)  # Solution
path = treestore1.get_path(iter2)     # Existing code in the question

Treestore has to be sorted first and after that path could be get correctly.
EDIT: This code works but according to @theGtknerd's answer, it is not the exact solution for the problem. Currently I have no knowledge about the exact solution and details of the @theGtknerd's answer.

A: Since you are using treemodelfilter1 to sort the treeview. To get the exact tree path to the selection after selecting, you can use treemodelfilter1  instead of treestore1. This should work.

    path = treemodelfilter1.get_path(iter2)


text:
Q: G minus the union of conjugates of a self-normalizing subgroup Let $G$ be a finite group with $H \leq G$ such that $H \cap H^g=1$ for all $g \in G-H$ .
Prove there are exactly $|G|/|H|-1$ elements of $G$ lying outside of all conjugates of $H$.
My query: Group action shows the number of conjugates of $H$ is  $|G|/|H|$, so it remains to show $H^x \cap H^y$ is trivial for each pair of distinct $x ,y \in G-H $: Assume there is  $1 \neq z \in H^x \cap H^y$, then there are $h_1, h_2 \in H-{1}$ such that $z=h_1^{x}=h_2^{y}$, this gives $h_1^{xy^-1}=h_2 \in H$ thus $xy^{-1} \in H$<--- I intended to get a contradiction from here but it seems not obvious.
Note: Once one can show every pair of conjugates of $H$ has trivial intersection then the answer is $|G|-[|G:H|(|H|-1)+1]=|G|/|H|-1$

A: You don't actually want to prove that if $x\neq y$ are both in $G-H$ then $H^x \cap H^y = \{1\}$. (It's not true, anyway: if $h\neq 1$ then setting $y=hx$ gives $H^y = H^x$, even though $y\neq x$ and $x,y\in G-H$). What you actually want to prove is that if $H^x\cap H^y\neq\{1\}$, then $H^x = H^y$. Then you'll take the sum over the distinct conjugates of $H$.
And this follows from what you have: if $z\in H^x\cap H^y$, then $xzx^{-1}\in H\cap H^{yx^{-1}}$, and since $z\neq 1$, it follows that $yx^{-1}\in H$, hence $Hy = Hx$, hence $H^x = H^y$, as above.
So the pairwise distinct conjugates of $H$ have trivial intersection, and we have exactly $|G|/|H|$ conjugates. Now you can conclude as you want: the number of elements in the union of distinct conjugates of $H$ is exactly $[G:H](|H|-1) + 1 = |G| - |G|/|H| + 1$.


text:
Q: Huge stack of credential dialogs when switching user I have reported this bug:
https://bugs.launchpad.net/ubuntu/+source/update-manager/+bug/1831332
My question is that what would be the correct package/component for this? I filed that against update-manager, but not sure if that's correct.