text:
Q: Not update visual cells in a tableviewcell I'm programming an app with a tableviewcell. When I touch a cell drives me to another view controller where I activate a switch and save this status on a plist file. Back to tableviewcell I read the information from the plist file and update the background color of the cell touched and activated. The problem is when I go back to the tableview cell though the navigation button, if the cell is visible doesn't show the background colored. Only if I scroll down or up, the color cell is updated. I have tried to reloadData method, but not success. On the IOS API says the visible cells will be updated with the reloadData method. Thanks in advance.
- (void)viewWillAppear:(BOOL)animated {
controladorRegistre = [[ControladorRegistres alloc]initRegistreAmbCategoria];
[self.tableCategories reloadData];
[super viewWillAppear:animated];

}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell       *)cell
            forRowAtIndexPath:(NSIndexPath *)indexPath
{
//Pinta la celda si esta activada
registre = [controladorRegistre getRegistreCategoria:cell.textLabel.text];
BOOL estaActivat = [[registre objectForKey:@"estaActivat"] boolValue];
if (estaActivat) {
    [cell setBackgroundColor:[UIColor redColor]];
}else{
    cell.backgroundColor = [UIColor whiteColor];
}
}

A: As willDisplayCell is not called automatically when an already loaded cell becomes visible when transitioning from another view controller, you will have to put your update code into viewWillAppear.
I usually break this out into a separate method like updateCells.
In general, you can access the relevant cells with [_tableView visibleCells] or indexPathsForVisibleCells. In your case, you could keep a reference of the selected cell that started the second view controller and use that.


text:
Q: Passing $this variable as an argument I need help in understanding the following php code.
    $this->_PageHeader = new PAGE_HEADER($this);

I want to understand the functionality of $this argument in PAGE_HEADER($this).
I knew that $this is used inside a class to refer property and methods but in this case, what values will be passed through this argument.

A: $this contains the current instance of the class you are in. So it means that you pass the current object of the class containing the code $this->_PageHeader = new PAGE_HEADER($this); to the constructor of the class PAGE_HEADER.
For instance:
class A
{
    public $value = 1;

    public function execute()
    {
        $b = new B($this);
    }
}

class B
{
    public $value = 2;

    public function __construct(A $dep)
    {
        echo $dep->value; // 3
        echo $this->value; // 2
    }
}

$a = new A();
$a->value = 3;
$a->execute(); // In this execution, $this is the object $a.

This code will output 32.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I change a template via config.xml of custom module in Magento? This content of my module's config.xml.
I want to change the onepage template file via this module.
It is works if I change code in onepage.xml, but I want to make this with my module.
Whats wrong in this code?
<config>
    <modules>
        <Mynamespace_Mymodule>
            <version>1.0</version>
        </Mynamespace_Mymodule>
    </modules>
    <frontend>
        <layout>
            <checkout_onepage_index>
                <reference name="checkout.onepage">
                    <action method="setTemplate"><template>mynamespace/mymodule/onepage.phtml</template></action>
                </reference>
            </checkout_onepage_index>
        </layout>
    </frontend>
</config>

A: You can't call a layout from config.xml
You said that: I change code in onepage.xml -> looks like what you meant is checkout.xml
This is term of definition. We may have different definition of modules.
Let's say you have module in app/code/local/[Mynamespace]/[Mymodule]
Your [Mymodule] is calling mymodule.xml
Do you say it is called from your module?
1) If yes, then you can use this code in your config.xml
<config>
    <modules>
        <Mynamespace_Mymodule>
            <version>1.0</version>
        </Mynamespace_Mymodule>
    </modules>
    <frontend>
        <layout>
            <updates>
                <mymodule>
                    <file>mymodule.xml</file>
                </mymodule>
            </updates>
        </layout>
    </frontend>
</config>

That code will call layout named mymodule.xml
Then create the layout file in app/design/frontend/[base/default]/[default/yourtheme]/layout/mymodule.xml
<?xml version="1.0"?>
<layout version="0.1.0">
    <checkout_onepage_index>
        <reference name="checkout.onepage">
            <action method="setTemplate"><template>mynamespace/mymodule/onepage.phtml</template></action>
        </reference>
    </checkout_onepage_index>
</layout>

2) If no -> your definition of module is only files under app/code/local/[Mynamespace]/[Mymodule], then you need to rewrite the Onepage's block
config.xml
<config>
    <modules>
        <Mynamespace_Mymodule>
            <version>1.0</version>
        </Mynamespace_Mymodule>
    </modules>
    <global>
        <blocks>
            <checkout>
                <rewrite>
                    <onepage>Mynamespace_Mymodule_Block_Checkout_Onepage</onepage>
                </rewrite>
            </checkout>
        </blocks>
    </global>
</config>

With that config, your Mage_Checkout_Block_Onepage will be rewritten by Mynamespace_Mymodule_Block_Checkout_Onepage (you can change the name as long as you keep the directory structure in a match).
For the example your file will be put in: app/code/local/[Mynamespace]/[Mymodule]/Block/Checkout/Onepage.php
Finally your app/code/local/[Mynamespace]/[Mymodule]/Block/Checkout/Onepage.php will be like this:
class Mynamespace_Mymodule_Block_Checkout_Onepage extends Mage_Checkout_Block_Onepage
{
    public function __construct()
    {
        parent::__construct();
        $this->setTemplate('mynamespace/mymodule/onepage.phtml');
    }
}


text:
Q: Как разбить строку по 2 символа, и если символу нет пары добавить ('_')? Помогите пожалуйста, как На каждой итерации добавь строку с текущим и следующими символами в массив результатов.

function splitString(str) {
  let resArr = [];
  let helpStr = '_';

  for (var i = 0; i < str.length; i = i + 2) {
    let currstr = str[i + 1];

    console.log(currstr)

  }
  return resArr;
}
let = resSplit = splitString('123456');
console.log(resSplit);

A: Ну если я правильно понял, что нужно. Очень просто. Разумеется, мы изначально подразумеваем, что inputString это обычная строка

const inputString = '123456';
let result = [];

for (let i = 0; i < inputString.length; i++) {
  result.push(`${inputString[i]}${ !!inputString[i+1] ? inputString[i+1] : '_' }`);

}

console.log(result);

A: Не знаю, какой вариант правильный с точки зрения поставленной задачи, привел оба решения.

const inputString = '123456';

const getArray = (str) => str.split('').map((item, index) =>
  `${item},${!!str[index+1] ? str[index+1] : '_'}`
)

console.log(getArray(inputString));

const inputString = '1234567';

const getArray = (str) => {
  let result = [];

  for (let i = 0; i < str.length; i = i + 2) {
    result.push(`${str[i]}${ !!str[i+1] ? str[i+1] : '_' }`);

  }

  return result;
}

console.log(getArray(inputString));


text:
Q: How to Add Calculation in Field table using Hook Feathers? Suppose I have a table with three fields, "id", "firstValue", and "secondValue". I use postgres as its database. I want to add some calculation first, for example, the second field "firstValue" should be  ( firstValue + secondValue ) / 10. Does anyone know how to add this calculation in hooks service? Can someone give a method example in hooks?
This is a template in hooks service
module.exports = function () {
    return async context => {

      return context;
    };
  };

I save this file as calculate.js
And this is the template in hooks.js
let calculate = require('./../../hooks/calculate');

module.exports = {
  before: {
    all: [],
    find: [calculate()], // add some calculation
    get: [calculate()], // add some calculation
    create: [],
    update: [],
    patch: [],
    remove: []
  },

  after: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  },

  error: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  }
};

Thanks

A: context.result is the object that represents the result of the service call (mentioned here: https://docs.feathersjs.com/guides/basics/hooks.html), it can be accessed within after hooks. Then your hook should be:
module.exports = function () {
    return async context => {
        context.result.computedField = ( context.result.firstValue + context.result.secondValue ) / 10

      return context;
    };
};

And the hooks file should be:
let calculate = require('./../../hooks/calculate');

module.exports = {
  before: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  },

  after: {
    all: [],
    find: [calculate()],
    get: [calculate()],
    create: [],
    update: [],
    patch: [],
    remove: []
  },

  error: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  }
};


text:
Q: Send Emails using Python Win32. Adding Image to the Body of the Email is not working I am trying to add an Image to an Email Body.
I am using Outlook 16 and Python 3.7 to do this.
The mail gets sent from Mailbox.
Here is my code function to send email and how can I add an Image at the end of the email.
def send_email(sender,recipient):
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = recipient
    mail.Subject = Subject_Req
    mail.HTMLBody = Content_Email
    mail.SentOnBehalfOfName = sender
    mail.GetInspector
    mail.Send()

The Image is present in my local network :- C:\Users\Sid\AppData\Roaming\Microsoft\Signatures\My Project\image001.png
The Image is nothing but the logo which I want to put at the last part of the HTML body.
So basically from the function it will be Content_Email + This image.
I tried some code, what it does is :- it sends an "X" mark at the end in place of the image itself to the recipient.
And when I send it to myself, It puts the "X" mark but I get an option to download pictures on right click and it gets the Image.
What I would like to do is, put the Image instead of the "X" for both the cases without the user having to have access to that Image.
How can I do this using Python. The solution in here seems to be working with VBA : https://www.experts-exchange.com/questions/26481413/Problem-inserting-HTML-images-into-the-body-of-a-messge.html

A: I managed to get this to work through attachment.PropertyAccessor.SetProperty function.
def send_email(sender,recipient):
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = recipient
    mail.Subject = Subject_Req
    attachment = mail.Attachments.Add(signatureimage)
    attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "MyId1")
    mail.HTMLBody = Content_Email + ""
    mail.SentOnBehalfOfName = sender
    mail.GetInspector
    mail.Send()

#Change the Paths here, if ran from a different location
signatureimage = "C:\\Users\\Sid\\AppData\\Roaming\\Microsoft\\Signatures\\My Project\\image001.png"

This would mean, it will embed the Image and not link the Picture to a link. Linking to a picture expects the recipients to have access to that particular picture location.
Also, for a learning this link doesn't change at all :- http://schemas.microsoft.com/mapi/proptag/0x3712001F


text:
Q: Any singular word ending in 's'? Singular word that ends in 's' seems to be rare, not counting proper nouns. So far I only know lens. Is there other example?

A: If you allow multiples of the letter s, there are a ton (class, pass, mass, etc).
If you restrict it to words that end with a single s, I suspect there are still a great many.  Dias, bias, alias, octopus, cactus, and mucus all come to mind.  Come up with common word endings that have an s and I think you can generate more.

A: In keeping with your example of "lens," add "iris."
In keeping with the puzzle nature of the question, "rebus."
Any medical condition ending in -itis, e.g., "bronchitis."
Any word ending with the suffix -osis, e.g., "hypnosis."


text:
Q: Insert Adsense Ads on bottom as a sticky ads I try to insert advertisement on bottom which is sticky it's working fine in desktop but didn't work on mobile device. Below is the code

Above code slide up ad when user scroll and i want to other user interaction like touchstart, mousemove, mousedown, etc so that it will work on all device.
HTML

Ad
      X


text:
Q: Expectation of transition in a Markov process I have the following transition matrix for a Discrete Markov process with 3 states, say states A, B and C:
\begin{bmatrix}0.985992 &  0.0134092 & 0.000599272\\
               0.0265225 &  0.949748 & 0.0237297 \\
               0.00196398 & 0.0895138 & 0.908522
\end{bmatrix}
As I was doing some calculations I noticed that if I simulated data the number of transitions from any two states is roughly the same going both ways (e.g. the number of states going from A to B, A->B, is roughly the same as from B to A, B->A), for example for 100000 iterations:

*

*A->B: 8164 and B->A: 8340

*B->C: 7602 and C->B: 7779

*A->C: 365 and C->A: 188

In an intuitive way, Why is this? I understand it if I calculate the expectations, for example:
$\mathbb{E}(A \rightarrow B)=\pi_A P(B | A)$
and this is actually very close to $\mathbb{E}(B \rightarrow A)=\pi_B P(A | B)$, where $\pi_X$ is the stationary distribution for state $X$.
I just don't quite grasp why this happens. Any insights? Any reference or leads appreciated.

A: This is a peculiar property of your transition matrix, but it doesn't have to be that way.
If your system satisfies $\pi_A P(B|A) = \pi_B P(A|B)$ for all states $A$ and $B$, your system is said to satisfy the property of detailed balance. Transition matrices that satisfy this property, are called reversible.
But there are Markov chains with stationary distributions that don't satisfy this property. E.g., you could try to find a chain that has as stationary distribution the uniform distribution but a transition matrix that is not symmetric. That means, find a transition matrix where all rows and all columns sum to one, but that is not symmetric. A simple example would be:
$$
T = \left[\begin{matrix}
              0.1 & 0.1 & 0.8 \\
              0.2 & 0.8 &   0 \\
              0.7 & 0.1 & 0.2 \\
          \end{matrix}\right].
$$
Clearly, the stationary distribution is the uniform distribution $\pi_U = (1/3, 1/3, 1/3)$, and this Markov chain is not reversible.
A good, short introduction to Markov chains can be found e.g. in

Bishop, Christopher M., and Nasser M. Nasrabadi. Pattern recognition and machine learning. Vol. 4. No. 4. New York: springer, 2006.


text:
Q: Data Type Mismatch in SQL when comparing a field against another field that has a null value I've been given a data set that contains 7 columns Reject1, Reject2,... etc. Each reject code that is in the column has a priority, 1 being highest priority and 9999 being the lowest. Unfortunately, the data is not normalized (I know shoot me in the face) and I have been tasked with finding the highest priority reject code from seven columns in one record and then returning that reject code.
What I've been able to do is left join the data to a table that has the hierarchy for the reject codes i.e. Reject code 79 = 1 Priority. So I now have 7 Reject Code columns along with 7 Priority columns to correspond.
My initial idea was to write a bunch of update queries that would update a TopPriority column after comparing two priority columns.
UPDATE tblPriority
SET tblPriority.HighestPriority = tblPriority.Priority1

So the above code works fine. The issue is with the second bit of SQL:
UPDATE tblPriority
SET tblPriority.HighestPriority = tblPriority.Priority2
WHERE tblPriority.HighestPriority > tblPriority.Priority2

The above code gives me a data type mismatch and I'm assuming it is because the Priority2 column is null? If so how does on solve this. Thanks in advance!

A: You can normalize the data pretty easily it seems
Select thingBeingRejected, Reject1 as RejectCode, 'Reject1' as SourceColumn
union all Select thingBeingRejected, Reject2 as RejectCode, 'Reject2' as SourceColumn
union all Select thingBeingRejected, Reject3 as RejectCode, 'Reject3' as SourceColumn
union all Select thingBeingRejected, Reject4 as RejectCode, 'Reject4' as SourceColumn
union all Select thingBeingRejected, Reject5 as RejectCode, 'Reject5' as SourceColumn
union all Select thingBeingRejected, Reject6 as RejectCode, 'Reject6' as SourceColumn
union all Select thingBeingRejected, Reject7 as RejectCode, 'Reject7' as SourceColumn

Then find the max like normal
Select max(p.priority), nrc.thingBeingRejected
from NormalizedRejectCodes nrc
inner join Priorities p on p.RejectCode = nrc.RejectCode
group by nrc.thingBeingRejected


text:
Q: Given some $v,k$ how many functions exist that satisfy the constraints $\int_{0}^{a} f(x) dx = v$ and $f(a) = k$? Some arbitrary constants $v$ and $k$ are given. Let a function $f(x)$ be valid if:
$\int_{0}^{a} f(x) dx  = v$ and $f(a) = k$ (for some arbitrary $a$)
I am interested to know how many such valid functions exist. One of them is obvious, where $f(x) = \frac{k^2}{2v}x$
Intuitively, it appears to me that there are more, but I am  not sure.

A: You can generalize your example. The function $f(x) = \dfrac{k^{n+1}x^n}{(n+1)^nv^n}$ is valid with $a = \dfrac{(n+1)v}{k}$ for every non-negative integer $n$.
Also, for any non-zero real number $c$, the function $f(x) = \begin{cases}c & \text{if} \ x \neq \tfrac{v}{c} \\ k & \text{if} \ x = \tfrac{v}{c}\end{cases}$ is valid with $a = \tfrac{v}{c}$.
Of course, there are even more examples than this.

A: $f(x)=e^{\alpha x}$ for $\alpha=\frac{{k-1}}{{v}}$ and $a = \frac{{v\ln (k)}}{{k - 1}}$. I think you can consider functions that their derivatives generate themselves.


text:
Q: How to add HTML/CSS using the editor on DNN? How to add markup without relying on modules? I don't have direct Host or Superuser access to DNN and the way our system is set up I wont get access to those accounts. It is a policy where i work. Is there ANY way to get your HMTL/CSS to actually work as you put it into the DNN HMTL editor?  I have tried adding things like an accordion sidebar, tabbed area, and a simple CSS image hover.  DNN takes my code and jumbles it up so that it does not work correctly.  I have taken markup straight from my text editor, into dnn (that was working fine in the browsers before i took it into DNN) and it shows up, but does not act like it should or the code gets jumbled and breaks and I spend an hour trying to fix it EVERY TIME.
Has anyone out there had the same issue, or any suggestions, tricks to get your markup to work correctly in DNN.
Thanks,

A: Yes and no, you can't add scripts in the html editor and if you are copy-pasting something that has a FORM element, it won't directly work without modification.
One possible way to keep your javascript working is to move it to the Header or Footer options in the module options of that module instead of the content.
As for if your code contains a FORM element, you can use javascript to modify the Asp.NET FORM element to suit your need, see http://dotnetnuke.bz/Articles/tabid/156/DotNetNuke/98/How-to-Include-Multiple-Forms-in-DotNetNuke.aspx for more details.


text:
Q: Page not getting redirected when sessions are not set - PHP In home.php page, if session is not set I want to redirect to index page. But it is not getting redirected. Session will be set only if I login to the project. However, currently I am not logged in, so sessions are not set.
require_once 'header.php';
if(!isset($_SESSION['uid']) && !isset($_SESSION['uname']))
{
   //echo "hai";                       // works
   header("location:index.php");
   exit;
}
echo "hello";   // does not work

In header.php page I am starting session like
if(!isset($_SESSION)){
    session_start();
}

What I am doing wrong? Can anyone help me to find the problem?
Thanks in advance.

A: The correct format to redirect is via header is :
header('Location: '.$newURL);

Uppercase L

A: Can you try like that and tell me how it is working:
require_once 'includes/header.php';
if(!isset($_SESSION['US_Id']) && !isset($_SESSION['US_UName']))
{
   header("Location: /index.php");
   exit;
}

Be sure to remove all the symbols (even the empty spaces) before the opening tag <?php and after the closing tag ?> in both your file and the header.php.
Having anything there will make impossible for the headers to be changed.

A: Your issue is that you are formatting wrong and you cannot use a relative path
Change it to:
header("Location: http://yoursite.com/index.php");


text:
Q: TMPFS for /var/cache When I use the TMPFS set for /var/cache and I reboot the computer and then once the computer has booted back into the Ubuntu 13.10 and login and goto run the Ubuntu Software Center it loads for about 2 seconds and then crashes out.
My System is a

*

*Intel I7

*16GB Memory

*1 x OCZ-SSD Drive 120GB BOOT Drive, With trim enabled in OS

*1 X WD-HDD Drive 250GB User Drive

Here is the TMPFS line that I add to the fstab file:
tmpfs  /var/cache tmpfs   defaults,noatime,mode=0755   0  0
and also tried
tmpfs  /var/cache tmpfs   defaults,noatime,mode=1777   0  0
When I remove the above line(s) the Ubuntu Software-center works fine..

A: Of course it wouldn't work fine. Lets take a peek at what /var/cache has:
ls /var/cache
apt               cracklib  dictionaries-common  git       lxc       pppconfig        sublime-text-2
apt-xapian-index  cups      fontconfig           jockey    man       samba
auto-apt          debconf   gdm                  ldconfig  pm-utils  software-center

Among others things, the cache has about the most massive amount of cache archives, from the current package lists, to virtual machines, to all sorts of important data that it is used in all moment:
sudo du -sh /var/cache/*
517M    /var/cache/apt
88M     /var/cache/apt-xapian-index
72M     /var/cache/auto-apt
448K    /var/cache/cracklib
5.8M    /var/cache/cups
5.1M    /var/cache/debconf
36K     /var/cache/dictionaries-common
660K    /var/cache/fontconfig
4.0K    /var/cache/gdm
4.0K    /var/cache/git
4.0K    /var/cache/jockey
84K     /var/cache/ldconfig
488M    /var/cache/lxc
3.6M    /var/cache/man
4.0K    /var/cache/pm-utils
4.0K    /var/cache/pppconfig
4.0K    /var/cache/samba
5.7M    /var/cache/software-center
5.5M    /var/cache/sublime-text-2

Making the /var/cache a tmpfs just because is cache is a very bad move. Instead move it to an HDD if you don't want to wear your SSD (through, truth be told, /var/cache isn't written so often as it's read (unless you use samba)) instead using tempfs.


text:
Q: Django admin add view popup dialog box How can I pass in an extra GET parameter in the add view popup box in the Django admin?
Basically I have a + sign in a foreign key, and when I click on it, it opens a popup box to add a new object of that type.
The problem is that I am using some custom Ajax code in the popup box, and I need to find a way to update only the field that is opened the dialog box (assuming there might be other foreign key fields).
The only solution I can think of is to somehow pass in a GET parameter so that I know which field should be updated.
Any ideas?  I just need a push in the right direction in order to complete this
Right now I am doing something like this to update the field. and I want to make this dynamic
if ($('#id_avatar').length) {
  $('#id_avatar', opener.document).append($('<option selected="selected"></option>').attr('value', data.obj_id).text(data.obj__unicode__));
     }

I guess I somehow reloading the select box in the original page could be an option since at this point its already saved in the database.

A: I ended up overriding the fieldsets in change_form.html. not sure if its the best approach but it seems to be working for me.
Now i can pass a source_field to know what field called the popup so i can later updated the proper field with Jquery
{% for fieldset in adminform %}
{#  {% include "admin/includes/fieldset.html" %}#}
    <fieldset class="module aligned {{ fieldset.classes }}">
        {% if fieldset.name %}
{{ fieldset.name }}
{% endif %}
        {% if fieldset.description %}

{{ fieldset.description|safe }}

        {% endif %}
        {% for line in fieldset %}

                {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %}
                {% for field in line %}

                        {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}
                        {% if field.is_checkbox %}
                            {{ field.field }}{{ field.label_tag }}
                        {% else %}
                            {{ field.label_tag }}
                            {% if field.is_readonly %}

{{ field.contents }}

                            {% else %}
                                {% if field.field.name == 'avatar' %}
                                    <select id="id_avatar" name="avatar">
                                        <option value="" selected="selected">---------</option>
                                    </select>
                                {% else %}
                                    {{ field.field }}
                                {% endif %}
                            {% endif %}
                        {% endif %}
                        {% if field.field.help_text %}

{{ field.field.help_text|safe }}

                        {% endif %}

                {% endfor %}

        {% endfor %}
    </fieldset>
{% endfor %}


text:
Q: Consistent Timezone in popup window Using FullCalendar for my Google Calendar, I would like to ignore the local timezone completely and always render the time in America/Chicago time.
I'm actually not worried about the calendar itself - it works fine.  I'm trying to make the popup window display properly.  As long as I'm logged into a Google account, the time displays "local" time. But many of my visitors will not have Google accounts and when they open the popup window, it always displays GMT time.
How do I tell the popup window to always display "America/Chicago"? Is this a FullCalendar issue or a Google issue?

A: According to the documentation of fullcalendar at:
http://fullcalendar.io/docs/timezone/timezone/
You have the method/parameter timezone which allows you to set it with the parameter 'America/Chicago'
This is taken from their example:
function renderCalendar() {
            $('#calendar').fullCalendar({
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay'
                },
                defaultDate: '2015-02-12',
                timezone: currentTimezone, //Here you can set timezone to 'America/Chicago'
                editable: true,
                eventLimit: true, // allow "more" link when too many events
                events: {
                    url: 'php/get-events.php',
                    error: function() {
                        $('#script-warning').show();
                    }
                },
                loading: function(bool) {
                    $('#loading').toggle(bool);
                },
                eventRender: function(event, el) {
                    // render the timezone offset below the event title
                    if (event.start.hasZone()) {
                        el.find('.fc-title').after(
                            $('<div class="tzo"/>').text(event.start.format('Z'))
                        );
                    }
                }
            });
        }

And accordingly the same parameter is available for the google calendar example:
http://fullcalendar.io/docs/google_calendar/


text:
Q: Chrw() Anomally: Invisible Values I found an anomaly that I don't understand. I generated a list of special characters (into a column of cells) using the Chrw() function and the list was created just fine.  However some of the cells appeared to be empty with no text, numbers, characters or spaces.  I wanted to remove rows that had blank spaces so I ran some code to delete EntireRows that contained nothing in that particular column.  But no rows were deleted.  The blank cells remained and it wasn't because of any problem with my delete code.  Even though the cells were blank, even checking the cell content bar for no spaces or characters, they would not delete unless I first physically clicked on the cell and hit the "delete" key.  So I discovered that there must have been some invisible value produced by the Chrw() function that did not physically show in the cell or the cell content bar.  An example of this anomaly would be Chrw(877)
Alternatively, some of the cells that appeared blank would not show a character in the cell until you clicked on the cell content bar.  Then a character would appear in the cell.  An example of this would be Chrw(860) theough Chrw(866).  Additionally even though the character showed in the content bar you could not copy it or even move the cursor with the arrow key in the bar.
Finally, I tested a couple of different of these invisible values to see if they match.  And they don't.  At least they did not match on the two I compared.  I didn't compare the rest of them.
What is happening?  Can we use these invisible values in code?
Here is the code that produced the list in column H:
Sub Create_Special_Character_List()

    Dim rowCounter As Long

    rowCounter = 1

        For i = 0 To 65535
            Sheet1.Range("H" & rowCounter) = ChrW(i)
            Sheet1.Range("I" & rowCounter) = i
            rowCounter = rowCounter + 1
        Next i

    End Sub

Here is my delete code:
Sub getRidOfBlanks()

    For i = 65536 To 1 Step -1
        If IsEmpty(Sheet1.Range("H" & i)) Or Sheet1.Range("H" & i) = "" Or Sheet1.Range("H" & i) = " " Or Sheet1.Range("H" & i) = "  " Or Sheet1.Range("H" & i) = "   " Then
           Sheet1.Rows(i & ":" & i).EntireRow.Delete
        End If
    Next i

End Sub

Below is the comparison sub:
Sub Compare_Values_Of_2_Different_Cells()

    If Sheet1.Range("H853") = Sheet1.Range("H854") Then
    '   Actually Chrw(855) and Chrw(856)
        Debug.Print "Values Match"
    Else
        Debug.Print "Values Don't Match"
    End If

    Debug.Print "1.  " & Sheet1.Range("H853") '  Chrw(855)
    Debug.Print "2.  " & Sheet1.Range("H853") '  Chrw(856)

End Sub

'  Debug.Print Results:
'
'  Values Don't Match
'  1. ?
'  2. ?

A: Just because you cannot "see" them does not mean that those characters do not exist or be used as actual data in a cell.
They are unicode characters. Specifically they are, as Ramhound mentioned, Combining Diacritical Marks. They are intended to be used with other "normal" characters and not on their own, but that does not mean that they cannot appear in text on their own. How they are then rendered is down to the application, in this case lacking a character to modify they are simply not rendered.
855 is Combining Right Half Ring Above
856 is Combining Do Above Right
So your cells do not contain "blanks" at all, they contain characters that simply do not get rendered or do not appear in your current font.
They are also not matched as the same because they are not. They are quite definitely different characters.


text:
Q: PostgreSQL query gets magnitudes slower when sorting by columns from two different tables Previously, I used this query, which was fast:
cb=# explain analyze SELECT "web_route"."id", "web_crag"."id" FROM "web_route"
INNER JOIN "web_crag" ON ( "web_route"."crag_id" = "web_crag"."id" )
WHERE "web_crag"."type" IN (1, 2)
ORDER BY "web_crag"."name" ASC
LIMIT 20;
                                                                 QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=0.00..2.16 rows=20 width=18) (actual time=0.027..0.105 rows=20 loops=1)
   ->  Nested Loop  (cost=0.00..47088.94 rows=436055 width=18) (actual time=0.026..0.100 rows=20 loops=1)
         ->  Index Scan using web_crag_name on web_crag  (cost=0.00..503.16 rows=1776 width=14) (actual time=0.011..0.020 rows=14 loops=1)
               Filter: (type = ANY ('{1,2}'::integer[]))
         ->  Index Scan using web_route_crag_id on web_route  (cost=0.00..23.27 rows=296 width=8) (actual time=0.004..0.005 rows=1 loops=14)
               Index Cond: (crag_id = web_crag.id)
 Total runtime: 0.154 ms
(7 rows)

The problem with the query is that the order in which the rows are returned is not deterministic, which caused repeating rows across subsequent pages produced OFFSETing (i.e. pagination did not work properly in my web app). I decided to make the ordering strict by additionally sorting by "web_route".id".
cb=# explain analyze SELECT "web_route"."id", "web_crag"."id" FROM "web_route"
INNER JOIN "web_crag" ON ( "web_route"."crag_id" = "web_crag"."id" )
WHERE "web_crag"."type" IN (1, 2)
ORDER BY "web_crag"."name", "web_route"."id" ASC
LIMIT 20;
                                                             QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=29189.04..29189.09 rows=20 width=18) (actual time=324.065..324.068 rows=20 loops=1)
   ->  Sort  (cost=29189.04..30279.18 rows=436055 width=18) (actual time=324.063..324.064 rows=20 loops=1)
         Sort Key: web_crag.name, web_route.id
         Sort Method: top-N heapsort  Memory: 26kB
         ->  Hash Join  (cost=135.40..17585.78 rows=436055 width=18) (actual time=0.882..195.941 rows=435952 loops=1)
               Hash Cond: (web_route.crag_id = web_crag.id)
               ->  Seq Scan on web_route  (cost=0.00..10909.55 rows=436055 width=8) (actual time=0.026..55.916 rows=435952 loops=1)
               ->  Hash  (cost=113.20..113.20 rows=1776 width=14) (actual time=0.848..0.848 rows=1775 loops=1)
                     Buckets: 1024  Batches: 1  Memory Usage: 82kB
                     ->  Seq Scan on web_crag  (cost=0.00..113.20 rows=1776 width=14) (actual time=0.004..0.510 rows=1775 loops=1)
                           Filter: (type = ANY ('{1,2}'::integer[]))
 Total runtime: 324.101 ms
(12 rows)

However, as you can see, the query got more than 2000x slower, which is quite a lot :). I wonder what can be done about that if anything. I plan to do really not a nice hack and duplicate "web_crag"."name" into "web_route" so that I can put an index on the two columns (crag_name, id) but if there is a better way I would be glad.
Here are schemes of "web_route" and "web_crag" in case it matters.
cb=# \d web_crag;
                                      Table "public.web_crag"
     Column      |           Type           |                       Modifiers
-----------------+--------------------------+-------------------------------------------------------
 id              | integer                  | not null default nextval('web_crag_id_seq'::regclass)
 name            | character varying(64)    | not null
 latitude        | double precision         |
 longitude       | double precision         |
 type            | integer                  |
 description     | text                     | not null
 normalized_name | character varying(64)    | not null
 country_id      | integer                  |
 location_index  | character(24)            | not null
 added_by_id     | integer                  |
 date_created    | timestamp with time zone |
 last_modified   | timestamp with time zone |
Indexes:
    "web_crag_pkey" PRIMARY KEY, btree (id)
    "web_crag_added_by_id" btree (added_by_id)
    "web_crag_country_id" btree (country_id)
    "web_crag_location_index" btree (location_index)
    "web_crag_name" btree (name)
Foreign-key constraints:
    "added_by_id_refs_id_1745ebe43b31bec6" FOREIGN KEY (added_by_id) REFERENCES web_member(id) DEFERRABLE INITIALLY DEFERRED
    "country_id_refs_id_1384050a9bd763af" FOREIGN KEY (country_id) REFERENCES web_country(id) DEFERRABLE INITIALLY DEFERRED
Referenced by:
    TABLE "web_route" CONSTRAINT "crag_id_refs_id_3ce1145606d12740" FOREIGN KEY (crag_id) REFERENCES web_crag(id) DEFERRABLE INITIALLY DEFERRED
    TABLE "web_video" CONSTRAINT "crag_id_refs_id_4fc9cbf2832725ca" FOREIGN KEY (crag_id) REFERENCES web_crag(id) DEFERRABLE INITIALLY DEFERRED
    TABLE "web_image" CONSTRAINT "crag_id_refs_id_58210dd331468848" FOREIGN KEY (crag_id) REFERENCES web_crag(id) DEFERRABLE INITIALLY DEFERRED
    TABLE "web_eventdestination" CONSTRAINT "crag_id_refs_id_612ad57c4d76c32c" FOREIGN KEY (crag_id) REFERENCES web_crag(id) DEFERRABLE INITIALLY DEFERRED
Triggers:
    set_crag_location_index BEFORE INSERT OR UPDATE ON web_crag FOR EACH ROW EXECUTE PROCEDURE set_crag_location_index()

cb=# \d web_route
                                        Table "public.web_route"
       Column       |           Type           |                       Modifiers
--------------------+--------------------------+--------------------------------------------------------
 id                 | integer                  | not null default nextval('web_route_id_seq'::regclass)
 name               | character varying(64)    | not null
 crag_id            | integer                  | not null
 sector             | character varying(64)    | not null
 difficulty         | character varying(16)    | not null
 author             | character varying(64)    | not null
 build_date         | character varying(32)    | not null
 description        | text                     | not null
 difficulty_numeric | integer                  |
 length_meters      | double precision         |
 added_by_id        | integer                  |
 date_created       | timestamp with time zone |
 last_modified      | timestamp with time zone |
 normalized_name    | character varying(64)    | not null
 rating_votes       | integer                  | not null
 rating_score       | integer                  | not null
Indexes:
    "web_route_pkey" PRIMARY KEY, btree (id)
    "web_route_added_by_id" btree (added_by_id)
    "web_route_crag_id" btree (crag_id)
Check constraints:
    "ck_rating_votes_pstv_c39bae29f3b2012" CHECK (rating_votes >= 0)
    "web_route_rating_votes_check" CHECK (rating_votes >= 0)
Foreign-key constraints:
    "added_by_id_refs_id_157791930f5e12d5" FOREIGN KEY (added_by_id) REFERENCES web_member(id) DEFERRABLE INITIALLY DEFERRED
    "crag_id_refs_id_3ce1145606d12740" FOREIGN KEY (crag_id) REFERENCES web_crag(id) DEFERRABLE INITIALLY DEFERRED

A: Sadly PostgreSQL is not (yet) good at optimizing these types of sorts, it always wants to sort the whole result set at once if it can't find an index exactly matching the sort clauses.
Starting with PostgreSQL 9.3, you can trick the planner into doing the right thing with a LATERAL subquery. Try this:
SELECT "web_route"."id", "web_crag"."id"
FROM "web_crag",
LATERAL (
    SELECT * FROM "web_route"
    WHERE "web_route"."crag_id" = "web_crag"."id"
    ORDER BY "web_route"."id" ASC
) AS "web_route"
WHERE "web_crag"."type" IN (1, 2)
ORDER BY "web_crag"."name"
LIMIT 20;

With some simple test data I generated (1 million web_crags, 5 million web_routes) here's the query plan and timings... Almost identical to your 1st query plan, apart from the extra Sort for web_route.id:
 Limit  (cost=24.36..120.70 rows=20 width=14) (actual time=0.051..0.169 rows=20 loops=1)
   ->  Nested Loop  (cost=24.36..24084788.95 rows=5000000 width=14) (actual time=0.049..0.143 rows=20 loops=1)
         ->  Index Scan using web_crag_name_idx on web_crag  (cost=0.42..39131.46 rows=1000000 width=10) (actual time=0.018..0.023 rows=4 loops=1)
               Filter: (type = ANY ('{1,2}'::integer[]))
         ->  Sort  (cost=23.93..23.95 rows=5 width=8) (actual time=0.018..0.021 rows=5 loops=4)
               Sort Key: web_route.id
               Sort Method: quicksort  Memory: 25kB
               ->  Index Scan using web_route_crag_id_idx on web_route  (cost=0.43..23.88 rows=5 width=8) (actual time=0.005..0.011 rows=5 loops=4)
                     Index Cond: (crag_id = web_crag.id)
 Total runtime: 0.212 ms

You can avoid the sort with an additional index on web_route (crag_id, id):
 Limit  (cost=0.86..19.49 rows=20 width=14) (actual time=0.031..0.113 rows=20 loops=1)
   ->  Nested Loop  (cost=0.86..4659293.82 rows=5000000 width=14) (actual time=0.029..0.084 rows=20 loops=1)
         ->  Index Scan using web_crag_name_idx on web_crag  (cost=0.42..39293.82 rows=1000000 width=10) (actual time=0.017..0.021 rows=4 loops=1)
               Filter: (type = ANY ('{1,2}'::integer[]))
         ->  Index Only Scan using web_route_crag_id_id_idx on web_route  (cost=0.43..4.52 rows=5 width=8) (actual time=0.005..0.009 rows=5 loops=4)
               Index Cond: (crag_id = web_crag.id)
               Heap Fetches: 0
 Total runtime: 0.151 ms

Here's how I created the test data:
create table web_crag(id serial primary key, type int default 1, name text);
create table web_route(id serial primary key, crag_id int);
insert into web_crag (name) select generate_series(1,1000000)::text;
insert into web_route (crag_id) select id from web_crag cross join generate_series(1,5);
create index on web_crag(name);
create index on web_route(crag_id);
analyze web_route;

PostgreSQL patch
There is a "partial sort" patch to PostgreSQL to do roughly this kind of optimization automatically, but sadly it did not make the cut for PostgreSQL 9.4. Hopefully PostgreSQL 9.5 will have it (roughly second half of 2015).

A: The issue here is that before you were able to use an existing index for ordering
 ->  Index Scan using web_crag_name on web_crag  (cost=0.00..503.16 rows=1776 width=14)      (actual time=0.011..0.020 rows=14 loops=1)
           Filter: (type = ANY ('{1,2}'::integer[]))

But after adding two different columns for ordering it would need to use one index from the first table and another one from the second table. If you want to make it run fast for pagination the only reasonable thing to do is to avoid the third normalized form (meaning no data is duplicated) and just duplicate the data in the other table. It's either web.route_id inside web.crag table or vice versa (did not bother looking into your schema too much) and create a combined index CREATE INDEX ON table ("web_crag"."name", "web_route"."id");
When a combined index exists on the table and the columns are in the right order the scan time will be as good as for your first query.
Also make sure you check intgr-s solution. It works on on 9.3+ and does the trick. Materalization vs. (kind of) hard to read queries are your options. My personal preference goes for materialization but intgr gets my up vote for teaching me something new.


text:
Q: Basic C Bitwise Operations Example int sampleVariable; // declared and initialized and used elsewhere

if (sampleVariable & 2)
     someCodeIwantExecuted();

So if i wanted to manually manipulate sampleVariable so that if statement to evaluate as true and someCodeIwantExecuted() to execute I would do the following ?
sampleVariable |= (1 << 1);

Keep in mind I don't know what the value of sampleVariable is and I want to keep the rest of the bits the same. Just change the bit so that if statement will always be true.

A: The solution is fairly direct.
//  OP suggestion works OK
sampleVariable |= (1 << 1);

// @Adam Liss rightly suggests since OP uses 2 in test, use 2 here.
sampleVariable |= 2

// My recommendation: avoid naked Magic Numbers
#define ExecuteMask (2u)
sampleVariable |= ExecuteMask;
...
if (sampleVariable & ExecuteMask)

Note: when using the shift style as in (1 << 1), insure that the type of 1 matches your target type
unsigned long long x;
x |= 1 << 60;  // May not work if `sizeof(int)` < `sizeof(x)`.
x |= 1ull << 60;

Further: Consider the advantages of unsigned types.
// Assume sizeof int/unsigned is 4.
int i;
y |= 1 << 31;  // Not well defined
unsigned u;
u |= 1u << 31;  // Well defined in C.


text:
Q: How to get \vsplit to separate an equation from the previous line I've been experimenting with determining the height of lines by using \vsplit to break up a paragraph.  I've set pretty much every penalty associated with page breaking to 0.  It's not the end of the world if it can't be split off, but I'd like to know why.
\documentclass{article}
\usepackage{amsmath}

\newcounter{count}
\newlength{\size}
\newlength{\total}
\newlength{\prev}

\begin{document}

\setbox0=\vbox{This is the first line of a paragraph, so there is a penalty for
splitting here.  This is the line before a display, so ditto.
\begin{equation}
x=a
\end{equation}
Everything should return to normal now.}

\noindent\usebox0

\bigskip
\total=\ht0
\advance\total by \dp0
total height = \the\total

\clubpenalty=0
\widowpenalty=0
\displaywidowpenalty=0
\predisplaypenalty=0
\postdisplaypenalty=0
\interlinepenalty=0

\total=0pt
\loop\prev=\dimexpr \ht0+\dp0\relax
  \setbox1=\vsplit0 to \baselineskip
  \stepcounter{count}%
  \size=\dimexpr \prev-\ht0-\dp0\relax
  \advance\total by \size
  \thecount{ = }\the\size\par
  \ifdim\ht0>0pt\repeat

total height = \the\total

\end{document}

A:
the penalties are part of the box structure, so changes after the box is set have no effect, setting them earlier produces four lines rather than 3.
\documentclass{article}
\usepackage{amsmath}

\newcounter{count}
\newlength{\size}
\newlength{\total}
\newlength{\prev}

\begin{document}

\clubpenalty=0
\widowpenalty=0
\displaywidowpenalty=0
\predisplaypenalty=0
\postdisplaypenalty=0
\interlinepenalty=0

\setbox0=\vbox{This is the first line of a paragraph, so there is a penalty for
splitting here.  This is the line before a display, so ditto.
\begin{equation}
x=a
\end{equation}
Everything should return to normal now.}

\usebox0

\bigskip
\total=\ht0
\advance\total by \dp0
total height = \the\total

\total=0pt
\loop\prev=\dimexpr \ht0+\dp0\relax
  \setbox1=\vsplit0 to \baselineskip
  \stepcounter{count}%
  \size=\dimexpr \prev-\ht0-\dp0\relax
  \advance\total by \size
  \thecount{ = }\the\size\par
  \ifdim\ht0>0pt\repeat

total height = \the\total

\end{document}


text:
Q: Does an irreducible operator generate an exact $C^{*}$-algebra? Let $H$ be an infinite dimensional separable Hilbert space and $B(H)$ the algebra of bounded operators.
Definition : An operator $T \in B(H)$ is irreducible if $W^{*}(T)=B(H)$.
Definition : A $C^{*}$-algebra is exact  if it preserves exact sequences under the minimum tensor product.
Property : A $C^{*}$-algebra is exact if and only if :

*

*it's nuclearly embeddable into $B(H)$.

*it's isomorphic to a subalgebra of the Cuntz algebra $\mathcal{O}_2$.

Does an irreducible operator generate an exact $C^{*}$-algebra ?

Counter-example : Is there a non-exact singly generated $C^{*}$-algebra ? And does every $C^{*}$-algebra admit an irreducible faithful representation ? (it's ok for the simple $C^{*}$-algebras).
Remark : $C^{∗}$-algebras book (Eds Cuntz Echterhoff) : by definition, a discrete group $Γ$ is exact if $C^{∗}_{r}(\Gamma)$ is exact. If $Γ$ is amenable, then $C^{∗}_{r}(\Gamma)$ is nuclear and so exact. Then, the amenable groups are exact. Next, Adams (1994) proves also that the hyperbolic groups are exact, in particular the free groups are exact.  Gromov built non-exact discrete random groups (see @OwenSizemore comment).

A: For the main question: Not always. Any simple C*-algebra has a faithful irreducible representation. Dadarlat constructs many examples of simple, non-exact C*-algebras in [Nonnuclear subalgebras of AF algebras. Amer. J. Math. 122 (2000), no. 3, 581–597]. It is also known (see Davidson's C*-algebra book) that the full group C*-algebra of free groups have faithful, irreducible representations (and these C*-algebras are not exact).
For the first question labeled ``Counterexample": Yes. By the paper of Olsen and Zame [Some C∗-algebras with a single generator. Trans. Amer. Math. Soc. 215 (1976), 205–217] for any separable C*-algebra $A$, the C*-algebra $A\otimes U$ is singly generated where $U$ is a UHF algebra. So take any separable non-exact C*-algebra $A$, then $A\otimes U$ is separable, non-exact and singly-generated.
For the second question labeled ``Counterexample." No. Take any nontrivial abelian C*-algebra as a counerexample.


text:
Q: Laravel (vlucas/phpdotenv) changing env values dynamically In my test cases, I try to change some of the environment variables to create better test case coverage.
Laravel by default, only support get environment variable by env($key, $default = null), I cannot change the variable.
The Illuminate\Support\Env only supports get, does not support set.
Also, by default Laravel uses vlucas/phpdotenv to managing the environment variable. Most of them are using ImmutableWriter.
Is there any easy way to support dynamically changing environment variables are stored in ImmutableWriter.
Again, the solution is no necessary to (and should not) be implemented in production for security reasons.

A: PHP 7+ Closure has some interesting features, which can bypass private/protected checks.
It is very hacky, however, pretty good for test cases written.
use Illuminate\Support\Env;

function resetEnvValue($name, $value)
{
    $environmentRepository = Env::getRepository();

    $fn = function () use ($name, $value) {
        $fn = function() use ($name, $value) {
            $this->writer->write($name, $value);
        };
        $fn->call($this->writer);
    };
    $fn->call($environmentRepository);
}

resetEnvValue('TIMER', 1);

var_dump(env('TIMER')); // int(1)

resetEnvValue('TIMER', 2);

var_dump(env('TIMER')); // int(2)

Please do not use it production environment, the above code is only suitable for testing since it bypasses all the ImmutableWriter protection.


text:
Q: How to use dynamic clickable images in emails I am trying to add a dynamic image in my email with a link attached to the image.
In html this would be

The problem is the image is dynamic, so multiple calls will yield different results. So if multiple people open the email at the same time, the same link could generate different images for different people. When they click the image, it should redirect them to my server which should then redirect them to the correct corresponding image site.
However, when they click the image, I have no way of knowing what the image that was rendered on the client was, so I am unable to redirect them to the correct site.
We can't use iframes or javascript in emails. So I can't select the image and feed it back to the redirect.
Is there any way I can ensure that the href + img source are always the correct pair without using javascript or iframe in an email?

A: If I'm understanding correctly, you want the image name passed through on the link? You'll need to use URL parameters to pass the information across.
For example ?image=getImg,

Then on the webpage, you can use any language you want (typically PHP or JavaScript) to extract the parameter details and supply the correct view.


text:
Q: Transform string with optional full names to name and initial I need to transform a string with names into a string with names and initials separated by comma.
Example
Any-Name Tom, Name Brian Joe, Smith Judie, et al.
Any-Name T., Name Brian J., Smith J., et al.
Any-Name T, Name B J, Smith J, et al.
Any-Name Tom,Name Brian Joe,Smith Judie, et al.

...should all get
Any-Name T, Name BJ, Smith J, et al.

The et al. is optional. So...
Any-Name Tom, Name Brian Joe, Smith Judie

... should get
Any-Name T, Name BJ, Smith J

I tried to do it in this way:
var names = string.split(",");
names.forEach(function(name) {
    name = name.trim();
    var parts = name.split(" ");
    parts.forEach(function(part, index) {
        if (index > 0) {
            var initial = part.slice(0,1);
            // get upper case
        }
    });
});

But this seems to be a bit to complicated...

A: You were almost through.
This proposal uses Array#reduce for connecting the parts of the name and applies the wanted uppercase initial.
The 'et al' could be ckecked with an upper case string if necessary. If one found, then it is later added to the result.

function reName(string) {
    var names = string.split(","),
        etal = names[names.length - 1].indexOf('et al') !== -1 ? names.pop().trim() : '',
        condensed = names.map(function (name) {
            return name.trim().split(" ").reduce(function (r, part, index) {
                return index ? r + part[0].toUpperCase() : part + ' ';
            }, '');
        });

    etal && condensed.push(etal);
    return condensed.join(', ');
}

console.log(reName('Any-Name Tom, Name Brian Joe, Smith Judie'));
console.log(reName('Any-Name Tom, Name Brian Joe, Smith Judie, et al.'));

A: This solution doesn't simplify the OP's, but it completes it by creating a new string called newNames and writing the component parts (first names and initials & et al) to it.

var str="Any-Name Tom, Name Brian Joe, Smith Judie";
var names = str.split(",");
var newNames = "";
names.forEach(function(name) {
  var neatName;
  name = name.trim();
  var parts = name.split(" ");
  parts.forEach(function(part, index) {
    if (index === 0) neatName = part + " ";
    if (index > 0) {
      var initial = part.slice(0, 1);
      neatName += initial;
    }
  });
  newNames+=neatName + ", ";
});
newNames+="et al.";
document.write(newNames)


text:
Q: C language variable in executable file Simply coding  C file like bellow:
int main()
{
    int a = 999;
    return 0;
}

after compile and link using gcc, it will generate a executable file (e.g. .exe, .out)
But when I open (NOT RUNNING) the executable file with some Editor, I can not find the value of variable 'a' the number 999 which in hex is 0x3E7.
My question is:

*

*Is the variable number 999 exist in executable file?

*If not, where does the variable number stored? How the executable file get the variable number in running?

P.S: I have a little knowledge about memory section like .data .bss .text .etc and assembly language. Evenly I can not find it using ollydbg.

A: There is no reason for the compiler to put the value 999 anywhere since it is not used anywhere. The program has the same observable behaviour regardless 999 being somewhere in memory or not.
ISO/IEC 9899:TC2 - 5.1.2.3 Program execution:

*In the abstract machine, all expressions are evaluated as specified by the semantics. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object).

A: One of the important functions of optimization is removing unused stuff.  The behaviour of the program doesn't depend at all on the 999, and a isn't volatile, so the assignment isn't part of any visible side-effect, and the program is exactly equivalent to int main(){return 0;}
It's a lot easier to look at compiler output in asm form.
On the Godbolt compiler explorer, you can set it up so you can see asm output for gcc -O0 and gcc -O1 at the same time, in different panes.  https://godbolt.org/z/wNHEnN.
mov     DWORD PTR [rbp-4], 999 is there at -O0, along with stack-frame setup fluff.  So the -O0 output will have 999 as a dword immediate operand to a mov instruction.  The variable is local, so you won't find a symbol-table entry for it in the .data or .rdata sections (like you would with a global with a static initializer).
See also How to remove "noise" from GCC/clang assembly output? for more about looking at compiler output.


text:
Q: How do I add count label to an axis? I created this bar chart using ggplot. I had to create my own count function and called it 'a,' but now the label for that axis just has an a and nothing else... How do I fix it?
a <- count(df, glass)

gl <- ggplot(df, aes(x=glass, y="a", fill=glass)) +
    geom_bar(stat="identity") +
    theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5)) +
    xlab("Glass type") +
    ylab("Count") +
    coord_flip() +
    theme_minimal() +
    theme(legend.position = "none")
gl

Here is my graph

A: The default stat value for geom_bar is "count", which means that geom_bar() uses stat_count() to count the rows of each x value, or glass in this case. Using stat="identity" will override the default geom_bar() stat and require that you provide the y values in order for aggregation to occur. I don't believe you are trying to do this.
Try the following and see if it is what you were looking for:
gl <- ggplot(df, aes(x=glass, fill=glass)) +
        geom_bar() +
        theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5)) +
        xlab("Glass type") +
        ylab("Count") +
        coord_flip() +
        theme_minimal() +
        theme(legend.position = "none")


text:
Q: aws cli fails s3 copy with parameter validation On Windows Server 2008 R2 (64), copying a file to s3 bucket:

aws s3 cp somefile.bak s3://bucket/

*Parameter validation failed: Invalid type for parameter UploadId, value: None, type: <type 'NoneType'>, valid  types: <type 'basestring'>*

Thanks for your help.

A: AWS CLI 64-bit version on Windows Server seems to be the issue.  I had run the 64-bit install since the machine is 64-bit. I uninstalled that version and installed 32-bit and it's working great.


text:
Q: AsyncSocket startTLS : CFNetwork SSLHandshake failed (-9806) on iOS8.0 My app using a self-signed ssl certificate to connect to tcp server. It worked before iOS7.1, after iOS8.0,it has a problem when off net weight, suggesting : CFNetwork SSLHandshake failed (-9806) and can not reconnect.
i am using the method:startTLS for setting the ssl, the code like below:
// Configure SSL/TLS settings

NSMutableDictionary *sslSettings = [[NSMutableDictionary alloc] init];

NSData *pkcs12data = [[NSData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:certificate ofType:@"p12"]];

CFDataRef inPKCS12Data = (CFDataRef)CFBridgingRetain(pkcs12data);

CFStringRef password = CFSTR("123456");

const void *keys[] = { kSecImportExportPassphrase };

const void *values[] = { password };

CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);

CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);

OSStatus securityError = SecPKCS12Import(inPKCS12Data, options, &items);

CFRelease(options);

CFRelease(password);

[pkcs12data release];

if(securityError == errSecSuccess) {

    NSLog(@"Success opening p12 certificate.");

}

CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);

SecIdentityRef myIdent = (SecIdentityRef)CFDictionaryGetValue(identityDict,
                                                              kSecImportItemIdentity);

SecIdentityRef  certArray[1] = { myIdent };

CFArrayRef myCerts = CFArrayCreate(NULL, (void *)certArray, 1, NULL);

[sslSettings setObject:(id)CFBridgingRelease(myCerts) forKey:(NSString *)kCFStreamSSLCertificates];

[sslSettings setObject:NSStreamSocketSecurityLevelSSLv2 forKey:(NSString *)kCFStreamSSLLevel];

[sslSettings setObject:(id)kCFBooleanFalse forKey:(NSString *)kCFStreamSSLValidatesCertificateChain];


text:
Q: ESRI File Geodatabase with a field calculator with an incrementing number I've got a python script that runs on the Field Calculator of a ESRI File Database.  Right now it runs correctly in that it will increment the last three digits of the value.  But this is a script that is run as part of post processing so it will be run everytime there are new entries in the feature class.  My question is how can I modify this so that every time it runs it will look at the last four digits of the FacilityID and increment from there below is a screenshot of my attribute table:

EDIT:
And below is my Python script I need to modify.
cur = arcpy.SearchCursor("Telecommunications Line")
fac_id_values = [int(row.FACILITYID[-4:]) for row in cur]

maximum_value = max(fac_id_values)
if maximum_value:
 rec= maximum_value
else:
 rec = 0

def autoIncrement():
 global rec
 pStart = 1
 pInterval = 1
 if (rec == 0):
  rec = pStart
 else:
  rec += pInterval
 return "COMLI" + "11" +  format(rec, '03d')

Ok after running the code above I got this as a result.  It overwrote the previous values as shown above.  The First item should have a FacilityID of COMLI111001.

A: You can loop through the FC first and find them maximum value.
Example:
import arcpy
nullvalues = ["", " ", None, 0]
# Loop through and get Max value
cur = arcpy.SearchCursor("Telecommunications Line")
fac_id_values = [int(row.FACILITYID[-4:]) for row in cur if row.FACILITYID not in nullvalues]

max_value = max(fac_id_values)

# Loop through and Calculate new values
cur = arcpy.UpdateCursor("Telecommunications Line")
for row in cur:
    max_value = max_value + 1
    if row.FACILITYID in nullvalues:
        row.FACILITYID = "COMLI1" + str(format(max_value,'04d'))
        cur.updateRow(row)

This should ensure that you only update Null values.


text:
Q: Add paperclip new style doesn't affect old uploaded images I have Company model with logo image
has_attached_file :logo

I have created many companies with their logos.
Now, I need to add new style
has_attached_file :logo, :styles => { :small => "30x15>", :medium => "155x85>" }

Should I re-upload all my old data to regenerate the new styles? I don't think so....
Or is there any rake task can regenerate styles?

A: See Thumbnail-Generation. If the rake task doesn't work for you, you should be able to use a snippet in the console to invoke reprocess! on the companies in question


text:
Q: texlive-full and xzdec installed, but tlmgr not working I followed the instructions of the accepted answer of
https://askubuntu.com/questions/485514/how-to-properly-install-and-use-texlive-with-package-manager-in-14-04
but when I try to install any new package, I get
(running on Debian, switching to user mode!)
Unknown directive ...containerchecksum c59200574a316416a23695c258edf3a32531fbda43ccdc09360ee105c3f07f9fb77df17c4ba4c2ea4f3a5ea6667e064b51e3d8c2fe6c984ba3e71b4e32716955... , please fix it! at /usr/share/texlive/tlpkg/TeXLive/TLPOBJ.pm line 210, <$retfh> line 5579.

This is starting to be very frustrating.
Can somebody kindly guide me? Thank you
UPDATE
I'm trying to install manually following
How can I manually install a LaTeX package (Debian/Ubuntu Linux)?
so I downloaded the package from CTNA (aastex.zip, which btw is alread contained in Tex Live, according to CTAN repo) unpacked it and moved the content to /usr/share/tex-common
I then tried calling latex with either of the (seemingly relevant) files: aastex6.cls and aasjournal.bst, but in both cases I get
This is pdfTeX, Version 3.1415926-2.5-1.40.14 (TeX Live 2013/Debian)
 restricted \write18 enabled.
entering extended mode
! I can't write on file `aastex6.log'.
(Press Enter to retry, or Control-D to exit; default file extension is `.log')
Please type another transcript file name:

My first guess is that I should not do this last call. If so, what should I do?
Then, one thing that strikes me is the TeX Live 2013/Debian, but this is latex  which resulted on my machine from the installation procedure linked in the 'how to install the "vanilla" TexLive' (http://tug.org/texlive/acquire-netinstall.html)
Can somebody see through this? Thank you again


text:
Q: Upgrade blocked by grub2 package doing dialog when run by a script While trying to run Ubuntu 18.04 LTS (Bionic) on an AWS EC2 instance, my user data initialization script includes the step to do an upgrade (executing apt-get -y upgrade after executing apt-get update).  During this upgrade, there is a new kernel which requires that the boot loader (grub2) be reinstalled.  The big problem is the grub2 package setup apparently has lost configuration information and is running an interactive dialog using a tool called whiptail.  This means everything comes to a stop while this dialog waits for human response, though no human is present at the instance virtual console.  I have tried this with AMIs ami-0c55b159cbfafe1f0 (the same as the console uses) and ami-0e04554247365d806 (a more recent build from the Canonical account) in region us-east-2 (Ohio) with instance type t3a.small (2GB RAM).
I would like to know if (and how) there is a way to have package grub2 do the necessary boot-loader setup/install w/o doing any interactive dialog.
My user data script does download a tarball of my add-on files, in advance, so adding large or many files to this is practical.  Running similar AMIs for the arm64 architecture (on instance type a1.medium) works just fine (of course, grub is not being used for this architecture).  i am submitting this via a Python3 script over the AWS API with botocore, so I can repeat this with changes, easily.


text:
Q: Generic IComparer for sorting different objects in different properties I'm trying to sort an array of objects with IComparer.
I wrote the code but it works only with the particular object. e.g.:
for this class
public class Cars
{
    public string Name { get; set; }
    public string Manufacturer { get; set; }
    public int Year { get; set; }

    public Cars(string name, string manufacturer, int year)
    {
        Name = name;
        Manufacturer = manufacturer;
        Year = year;
    }
}

My code looks like:
class MySort
{
    public class SortByYears : IComparer
    {
        int IComparer.Compare(Object x, Object y)
        {
            Cars X = (Cars)x, Y = (Cars)y;
            return (X.Year.CompareTo(Y.Year));
        }
    }

    public class SortByName : IComparer
    {
        int IComparer.Compare(Object x, object y)
        {
            Cars X = (Cars)x, Y = (Cars)y;
            return (X.Name.CompareTo(Y.Name));
        }
    }

    public class SortByManyfacturer : IComparer
    {
        int IComparer.Compare(object x, object y)
        {
            Cars X = (Cars)x, Y = (Cars)y;
            return (X.Manufacturer.CompareTo(Y.Manufacturer));
        }
    }
}

But if I add another class with different properties it will be useless.
So is there any chance to modify this code so that it worked for objects with different properties?

A: You may leverage the Create method of Comparer<T> which takes a Comparison delegate and returns Comparer<T>.
var carnameComparer = Comparer<Cars>.Create((x, y) => x.Year.CompareTo(y.Year));
var carManufacturerComparer = Comparer<Cars>.Create((x, y) => x.Manufacturer.CompareTo(y.Manufacturer));

and for another type
var carsComparer = Comparer<SomeType>.Create((x, y) => x.SomeProperty.CompareTo(y.SomeProperty));

If you're in prior to .Net4.5 you can use the following CreateComparer method.
private static IComparer<T> CreateComparer<T>(Comparison<T> comparison)
{
    return new ComparisonComparer<T>(comparison);
}

public class ComparisonComparer<T> : IComparer<T>
{
    private Comparison<T> comparison;
    public ComparisonComparer(Comparison<T> comparison)
    {
        if (comparison == null)
        {
            throw new ArgumentNullException("comparison");
        }
        this.comparison = comparison;
    }

    public int Compare(T x, T y)
    {
        return comparison(x, y);
    }
}

A: class SortComparer<T> : IComparer<T>
{
   private PropertyDescriptor PropDesc = null;
   private ListSortDirection Direction =
      ListSortDirection.Ascending;

   public SortComparer(object item,string property,ListSortDirection direction)
   {
       PropDesc = TypeDescriptor.GetProperties(item)[property];
       Direction = direction;
   }

   int IComparer<T>.Compare(T x, T y)
   {
      object xValue = PropDesc.GetValue(x);
      object yValue = PropDesc.GetValue(y);
      return CompareValues(xValue, yValue, Direction);
   }

   private int CompareValues(object xValue, object yValue,ListSortDirection direction)
   {

      int retValue = 0;
      if (xValue is IComparable) // Can ask the x value
      {
         retValue = ((IComparable)xValue).CompareTo(yValue);
      }
      else if (yValue is IComparable) //Can ask the y value
      {
         retValue = ((IComparable)yValue).CompareTo(xValue);
      }
      // not comparable, compare String representations
      else if (!xValue.Equals(yValue))
      {
         retValue = xValue.ToString().CompareTo(yValue.ToString());
      }
      if (direction == ListSortDirection.Ascending)
      {
         return retValue;
      }
      else
      {
         return retValue * -1;
      }
   }
}

Calling code:
Assuming a list named lst:
lst.Sort(new SortComparer<Cars>(lst[0],"YourPropertyName",ListSortDirection.Ascending));

A: Use an interface and use generic IComparer Interface instead of IComparer
public interface IObjectWithNameProperty
{
    string Name {get; set;}
}

public class MyNameComparer : IComparer<IObjectWithNameProperty>
{
    public int Compare(IObjectWithNameProperty x, IObjectWithNameProperty y)
    {
        ...
    }
}

public class Car: IObjectWithNameProperty
{
     public string Name  {get;set;}
     ...
}
public class Dog: IObjectWithNameProperty
{
     public string Name  {get;set;}
     ...
}

A: Here is another take based on terrybozzio's.
public class PropertyComparer<T> : IComparer<T> where T : new()
{
    private PropertyDescriptor PropDesc = null;
    private ListSortDirection Direction = ListSortDirection.Ascending;

    public PropertyComparer(string property, ListSortDirection direction)
    {
        T item = new T();
        PropDesc = TypeDescriptor.GetProperties(item)[property];
        Direction = direction;

        Type interfaceType = PropDesc.PropertyType.GetInterface("IComparable");

        if (interfaceType == null && PropDesc.PropertyType.IsValueType)
        {
            Type underlyingType = Nullable.GetUnderlyingType(PropDesc.PropertyType);

            if (underlyingType != null)
            {
                interfaceType = underlyingType.GetInterface("IComparable");
            }
        }

        if (interfaceType == null)
        {
            throw new NotSupportedException("Cannot sort by " + PropDesc.Name +
                ". This" + PropDesc.PropertyType.ToString() +
                " does not implement IComparable");
        }
    }

    int IComparer<T>.Compare(T x, T y)
    {
        object xValue = PropDesc.GetValue(x);
        object yValue = PropDesc.GetValue(y);
        IComparable comparer = (IComparable)xValue;
        if (Direction == ListSortDirection.Ascending)
        {
            return comparer.CompareTo(yValue);
        }
        else
        {
            return -1 * comparer.CompareTo(yValue);
        }
    }
}

A: The cleanest way is to define an interface that both object implement, then use that in the comparison.  Otherwise you're going to have a mess of case statements depending on the
possible combination of objects:
public class SortByYears : IComparer
{
    int IComparer.Compare(Object x, Object y)
    {
        if(x is Cars)
        {
            Cars X = (Cars)x
            if(y is Cars)
            {
                Y = (OtherCars)y;
                return (X.Year.CompareTo(Y.Year));

            if(y is OtherCars)
            {
                Y = (OtherCars)y;
                return (X.Year.CompareTo(Y.Year));
            }
        }
        if(x is OtherCars)
        {
             ... repeat upper block
        }
    }
}

A: Another approach would be using the generic IComparer interface and lambda expressions.
class CarComparer<T> : IComparer<Car> where T : IComparable<T>
{
    private readonly Func<Car, T> _sortExpression;

    public CarComparer(Func<Car, T> sortExpression)
    {
        _sortExpression = sortExpression;
    }

    public int Compare(Car x, Car y)
    {
        return _sortExpression(x).CompareTo(_sortExpression(y));
    }
}

This class compares the Car's property passed in parameter in the constructor.
// Sort the cars by name
var nameCarComparer = new CarComparer<string>(car => car.Name);
Array.Sort(myArray, nameCarComparer);


text:
Q: Does deleting unanswered questions improve my accept rate?
Possible Duplicate:
How does accept rate work?

I normally post questions on stackoverflow relating to my programming work, but sometimes the nature of the problem does not make for a speedy solution.
In most cases, if I can't get an answer right away on stackoverflow, I'll come up with a solution or work around to the problem on my own some time after posting the question. This means that I no longer need answers and cannot actually accept any answers as having solved the problem because none did. When this happens I generally delete the question.
Is this a bad thing? (I believe I saw something about someone getting their account deleted for doing this). Does this improve my accept rate?
Mathematically, I believe the accept rate is calculated based on total questions vs accepted answers. So as I figure it, if I have one less unanswered question on one side of that scale, surely the accept percentage should increase...

A: No, it won't help your accept rate, unanswered questions are not counted there.
When you come up with the answer to a question yourself, just post that answer and accept it. All future visitors that come to your question will benefit from the solution. Nobody benefits if you delete the questions.

A: Accept rate is not really something you should worry about. It's a flawed metric at best. Did you accept answers for all the questions where that answer was helpful or correct? Great. You've done just fine. Even if that would (theoretically) mean that your accept rate is 10%. Of course, if most of your questions go unanswered, perhaps your questions can be improved. But that's besides the point.
If you've managed to answer your own question, good for you. Well done. Go ahead and answer your own question. You are explicitly encouraged to do so. The questions you ask here are ideally not only for your own benefit, but for that of others as well. As a result, adding an answer is a good thing as well.
Whatever you do, don't delete your questions. Or, at the very least don't do so with great frequency. That only signals that you ask bad questions to begin with. And while the exact details are not know to us, this does seem to factor in to a possible automatic question ban. That is certainly something you would want to avoid.
All that being said, unanswered questions don't factor in to the accept rate. So in that sense deleting them does not help your rate along anyway.


text:
Q: How to use jaxb in android? is there any example project which includes jaxb. I tried it as in the normal java way but i received the a compile error of the dalvik vm.
Conversion to Dalvik format failed with error 1

Does someone know how to solve this. I know that there are alternatives as simpleXml for android but its more work adapt my existing annotated classes with their annotation. An example or a good tutorial would be usefull. I did not find any good one.
Thanks

A: this is sounds like a solution, see: http://www.docx4java.org/blog/2012/05/jaxb-can-be-made-to-run-on-android/

A: See my answer here on using existing annotated JAXB classes with Android:
https://stackoverflow.com/a/13077912/937715


text:
Q: When using deeplinks with ionic on android, always routed to rootpage I am trying to build a mobile app with ionic (3.19.1), one of my needs is to have deep linking (routing) in the application.
I've followed ionic documentation and successfully created two pages, which can be routed by URL when using the chrome browser on my machine (ionic serve). When I am trying to deploy the application on an android device the routing is failed and root page is being opened.
Looking into it a bit more deeply, I noticed that once the application is opened on my android device (regardless if by clicking the app icon, or by external link leading to specific route in the application such as myapp://www. myapp.com/#/oauthcallback/?oauth_token=Y&oauth_verifier=X) the uri is file:///andoid _assert/www/index.html .
I understand that this is the location used by cordova to serve my app locally, yet in order to distinguish between different routes I must allow other urls (and specifically url parameters) to be passed to the application.
I've tried to play around with the application/urls but it didn't yield any success, any idea will be welcomed!
Thanks in advance!

A: the reason it is redirect to the root page every time is because it matches the URL scheme of your app. Now why its not redirecting, it has two possibilities:

*

*The route is not matching at all.

*Even if the route matches, you have to navigate to the page in the callback function. to elaborate what i am saying following is the example.

this.deeplinks.route({
                '/changePassword/:id': ChangePasswordPage
            }).subscribe((match) => {
                this.nav.setRoot(match.$route, {
                    id: match.$args.id
                })
                console.log('Successfully routed', match);
            }, (nomatch) => {
                console.log('Unmatched Route', nomatch);
            })
To check whats really happening you can put some console.log() and inspect the app on device by using chrome://inspect, or if you don't know about that just put some alerts in the callbacks and see what you are getting.


text:
Q: Ajax: How to get request?
<input type="button" id="ajax" value="click here!"/>


text:
Q: How to train faster-rcnn on dataset including negative data in pytorch I am trying to train the torchvision Faster R-CNN model for object detection on my custom data. I used the code in torchvision object detection fine-tuning tutorial. But getting this error:
Expected target boxes to be a tensor of shape [N, 4], got torch.Size([0])

This has to do with negative data (empty training images / no bounding boxes) in my custom dataset. How can we change the below Dataset class to enable training faster-rcnn on dataset including negative data?
class MyCustomDataset(Dataset):

    def __init__(self, root, transforms):
        self.root = root
        self.transforms = transforms
        # load all image files, sorting them to
        # ensure that they are aligned
        self.imgs = list(sorted(os.listdir(os.path.join(root, "PNGImages"))))
        self.masks = list(sorted(os.listdir(os.path.join(root, "PedMasks"))))

    def __len__(self):
        return len(self.imgs)

    def __getitem__(self, idx):
        # load images ad masks
        img_path = os.path.join(self.root, "PNGImages", self.imgs[idx])
        mask_path = os.path.join(self.root, "PedMasks", self.masks[idx])
        img = Image.open(img_path).convert("RGB")
        # note that we haven't converted the mask to RGB,
        # because each color corresponds to a different instance
        # with 0 being background
        mask = Image.open(mask_path)
        # convert the PIL Image into a numpy array
        mask = np.array(mask)
        # instances are encoded as different colors
        obj_ids = np.unique(mask)
        # first id is the background, so remove it
        obj_ids = obj_ids[1:]

        # split the color-encoded mask into a set of binary masks
        masks = mask == obj_ids[:, None, None]

        # get bounding box coordinates for each mask
        num_objs = len(obj_ids)

        boxes = []
        for i in range(num_objs):
            pos = np.where(masks[i])
            xmin = np.min(pos[1])
            xmax = np.max(pos[1])
            ymin = np.min(pos[0])
            ymax = np.max(pos[0])
            boxes.append([xmin, ymin, xmax, ymax])

        # convert everything into a torch.Tensor
        boxes = torch.as_tensor(boxes, dtype=torch.float32)
        # there is only one class
        labels = torch.ones((num_objs,), dtype=torch.int64)
        image_id = torch.tensor([idx])
        area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])
        # suppose all instances are not crowd
        iscrowd = torch.zeros((num_objs,), dtype=torch.int64)

        target = {}
        target["boxes"] = boxes
        target["labels"] = labels
        target["image_id"] =  torch.tensor([idx])
        target["area"] = area
        target["iscrowd"] = iscrowd

        return img, target

A: We need to make two changes to the Dataset Class.
1- Empty boxes are fed as:
if num_objs == 0:
    boxes = torch.zeros((0, 4), dtype=torch.float32)
else:
    boxes = torch.as_tensor(boxes, dtype=torch.float32)

2- Assign area=0 for empty bounding box case, change the code used for calculating area, and make it a torch tensor:
area = 0
for i in range(num_objs):
    pos = np.where(masks[i])
    xmin = np.min(pos[1])
    xmax = np.max(pos[1])
    ymin = np.min(pos[0])
    ymax = np.max(pos[0])
    area += (xmax-xmin)*(ymax-ymin)
area = torch.as_tensor(area, dtype=torch.float32)

We will incorporate step#2 in existing for loop.
So, the modified Dataset Class will look like:
class MyCustomDataset(Dataset):

    def __init__(self, root, transforms):
        self.root = root
        self.transforms = transforms
        # load all image files, sorting them to
        # ensure that they are aligned
        self.imgs = list(sorted(os.listdir(os.path.join(root, "PNGImages"))))
        self.masks = list(sorted(os.listdir(os.path.join(root, "PedMasks"))))

    def __len__(self):
        return len(self.imgs)

    def __getitem__(self, idx):
        # load images ad masks
        img_path = os.path.join(self.root, "PNGImages", self.imgs[idx])
        mask_path = os.path.join(self.root, "PedMasks", self.masks[idx])
        img = Image.open(img_path).convert("RGB")
        # note that we haven't converted the mask to RGB,
        # because each color corresponds to a different instance
        # with 0 being background
        mask = Image.open(mask_path)
        # convert the PIL Image into a numpy array
        mask = np.array(mask)
        # instances are encoded as different colors
        obj_ids = np.unique(mask)
        # first id is the background, so remove it
        obj_ids = obj_ids[1:]

        # split the color-encoded mask into a set of binary masks
        masks = mask == obj_ids[:, None, None]

        # get bounding box coordinates for each mask
        num_objs = len(obj_ids)

        boxes = []
        area = 0
        for i in range(num_objs):
            pos = np.where(masks[i])
            xmin = np.min(pos[1])
            xmax = np.max(pos[1])
            ymin = np.min(pos[0])
            ymax = np.max(pos[0])
            boxes.append([xmin, ymin, xmax, ymax])
            area += (xmax-xmin)*(ymax-ymin)
        area = torch.as_tensor(area, dtype=torch.float32)

        # Handle empty bounding boxes
        if num_objs == 0:
            boxes = torch.zeros((0, 4), dtype=torch.float32)
        else:
            boxes = torch.as_tensor(boxes, dtype=torch.float32)

        # there is only one class
        labels = torch.ones((num_objs,), dtype=torch.int64)
        image_id = torch.tensor([idx])

        #area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])

        # suppose all instances are not crowd
        iscrowd = torch.zeros((num_objs,), dtype=torch.int64)

        target = {}
        target["boxes"] = boxes
        target["labels"] = labels
        target["image_id"] =  torch.tensor([idx])
        target["area"] = area
        target["iscrowd"] = iscrowd

        return img, target


text:
Q: I wasn't meant to do something. // I didn't mean to do something

*

*I wasn't meant to do something.

*I didn't mean to do something.

How different they are from each other?

A: The first sentence means other people didn't expect you to do something, while the second one means you had no intention to do that something.


text:
Q: Capture all events (click, change, onmouseover, e.t.c) for a given element using jquery Is there anyway that I can check if an existing element has event handlers attached to it?  Suppose a simple javascript method adds a click event to some div.example (sans jquery), so there are not attribute tags, is it possible to then, using jquery, to capture the event that was attached?  I tried to accomplish this using the code below to no avail:
$( '.example' ).each( function() {
var newObj = $(this);
$.each($(newObj).data("events"), function(i, event) {
    alert(i);
        $.each(event, function(j, h) {
            alert(h.handler);
        });
});

});

A: Try this
$( '#elm1' ).each( function() {

 $.each($(this).data("events"), function(i, event) {
        alert(i);
        $.each(event, function(j, h) {
            alert(h.handler);
        });
 });
});


text:
Q: How to sum and subtract one column value based on percentage in SQL Server 2008 DECLARE @BalanceTblRec TABLE
                       (
                           NetAmount decimal(18, 3),
                           Percentage int,
                           [Description] nvarchar(max)
                       )
DECLARE @BalanceTblPay TABLE
                       (
                           NetAmount decimal(18, 3),
                           Percentage int,
                           [Description] nvarchar(max)
                       )

INSERT INTO @BalanceTblRec
VALUES (21, 11, 'ReceiveReceipt'),
       (20, 11, 'ReceiveReceipt'),
       (20, 10, 'ReceiveReceipt'),
       (20, 20, 'ReceiveReceipt'),
       (10, 10, 'ReceiveReceipt')

INSERT INTO @BalanceTblPay
VALUES (10, 11, 'PayReceipt'),
       (10, 11, 'PayReceipt'),
       (10, 2, 'PayReceipt'),
       (5, 15, 'PayReceipt'),
       (30, 10, 'PayReceipt'),
       (20, 10, 'PayReceipt')

;WITH MaPercentage AS
(
    SELECT
        Percentage,
        SUM(NetAmount) AS Net,
        'Receive' AS Flag
    FROM
        @BalanceTblRec
    GROUP BY
        Percentage
    UNION ALL
    SELECT
        Percentage,
        SUM(NetAmount) AS Net,
        'Pay' AS Flag
    FROM
        @BalanceTblPay
    GROUP BY
        Percentage
)
SELECT * FROM MaPercentage

Now here I want subtract net from net based on falg, receive - pay based on percentage.
Like this:
Per Net         Flag
-----------------------
10  30.000 - 50 Receive
11  41.000 - 20 Receive
20  20.000      Receive
2   10.000      Pay
15  5.000       Pay

A: I think this is what you want:
DECLARE @BalanceTblRec TABLE (NetAmount decimal(18,3), Percentage int, [Description] nvarchar(max))
DECLARE @BalanceTblPay TABLE (NetAmount decimal(18,3), Percentage int, [Description] nvarchar(max))

insert into @BalanceTblRec values (21, 11, 'ReceiveReceipt'),(20, 11, 'ReceiveReceipt'),(20, 10, 'ReceiveReceipt'),(20, 20, 'ReceiveReceipt'), (10, 10, 'ReceiveReceipt')
insert into @BalanceTblPay values (10, 11, 'PayReceipt'),(10, 11, 'PayReceipt'),(10, 2, 'PayReceipt'),(5, 15, 'PayReceipt'),(30, 10, 'PayReceipt') ,(20, 10, 'PayReceipt')

;WITH MaPercentage as (
select Percentage, sum(NetAmount) as Net, 'Receive' as Flag from @BalanceTblRec group by Percentage
union all
select Percentage, -sum(NetAmount) as Net, 'Pay' as Flag from @BalanceTblPay group by Percentage
)

select
  Percentage,
  abs(sum(net)) as SumNet,
  case when sum(net) > 0 then 'Receive'
  else 'Pay'
  end as Flag
from MaPercentage
group by Percentage

Just changed the sign in the Pays and sum groupping by percentage.

A: Another way is to FULL JOIN the receivements with the payments.
;WITH RCV AS (
  select Percentage, sum(NetAmount) as Net
  from @BalanceTblRec
  group by Percentage
)
, PAY AS (
  select Percentage, sum(NetAmount) as Net
  from @BalanceTblPay
  group by Percentage
)
SELECT
COALESCE(r.Percentage, p.Percentage) AS Percentage,
ABS(COALESCE(r.Net, 0) - COALESCE(p.Net, 0)) AS Net,
(CASE
 WHEN (COALESCE(r.Net, 0) - COALESCE(p.Net, 0)) < 0 THEN 'Pay'
 ELSE 'Receive'
 END) AS Flag
FROM RCV r
FULL JOIN PAY p ON p.Percentage = r.Percentage


text:
Q: loess warnings errors in geom_smooth in R Why does the following code successfully add a nice lowess smooth through these data points?
When the span is at 0.5, warning are generated that say
  all data on boundary of neighborhood. make span bigger

But even setting the span at 1, you don't get a span, but some of the data points are connected with lines.
This question suggests it is because the x-axis data has multiple entries for some points, and that does happen here. It suggests adding some jitter to the data. I did that with geom_jitter() (not included in code below) but that didn't solve the problem. I also tried using a sequence of numbers as the x-axis values, instead of the date and that did not work either.
Reproducible code follows below.
Thank you for any insights.
myfile<-'https://raw.githubusercontent.com/sjkiss/NDP/master/Data/membership_data_NDP.csv'
members<-read.csv(myfile, colClasses=c('Date', 'numeric','numeric', 'numeric', 'numeric', 'numeric','numeric', 'Date', 'character'))

theme_set(theme_bw())
members %>%
  select(population, votes_previous_election, seats_previous_election, members, date, recent_election) %>%
  mutate(., members_per_capita=members/population, members_votes=members/votes_previous_election, members_seats=members/seats_previous_election) %>%
  rename(., `Members\nper_capita`=members_per_capita, `Members\nper_vote`=members_votes, `Members\nper_seat`=members_seats) %>%
  gather(Variable, Value, 7:9) %>%
  ggplot(., aes(x=date, y=Value, group=recent_election))+geom_point(aes(col=factor(recent_election)))+scale_color_discrete(name = "Recent Election")+scale_x_date() +facet_wrap(~Variable, scales='free')+geom_smooth(method='loess', span=0.5)
warnings()```


text:
Q: Candle Stick MP Chart android is not setting the candle stick size I am creating a CandleStick chart

from API: https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD&limit=10
  Using Library: https://github.com/PhilJay/MPAndroidChart

When I creating the chart with the count of values as X-axis, There is no problem (ploat_point.add(new CandleEntry(i,high,low,open,close); in for loop ).
But when I use ploat_point.add(new CandleEntry(time,high,low,open,close); in for loop, And parse X-axis values using my custom function.
i.e :
xAxis = candle_chart.getXAxis();
xAxis.setValueFormatter(new IAxisValueFormatter() {
                    @Override
                    public String getFormattedValue(float value, AxisBase axis) {
                        Log.e(TAG, "getFormattedValue: " + (int) value);
                        return Utilities.timeStampToMonth((int) value + "");
                    }
                });

This time it is showing the graph only when the paint style is set to Paint.Style.FILL_AND_STROKE, But It does not increasing the bar size with candleDataSet.setBarSize() . It depending only the candleDataSet.setShadowWidth().
my code :
private void drawCandleStickChart(JSONArray dataArr) throws JSONException {

    mChart.setVisibility(View.GONE);

    ArrayList<CandleEntry> plot_point = new ArrayList<>();

    for (int i = 0; i < dataArr.length(); i++) {
        JSONObject point = dataArr.getJSONObject(i);
        int time = Math.round(Float.parseFloat(point.getString("time")));
        float open = Float.parseFloat(String.valueOf(point.getString("open")));
        float close = Float.parseFloat(String.valueOf(point.getString("close")));
        float high = Float.parseFloat(String.valueOf(point.getString("high")));
        float low = Float.parseFloat(String.valueOf(point.getString("low")));
        plot_point.add(new CandleEntry(time, high, low, open, close));
    }

    CandleDataSet cds = new CandleDataSet(plot_point, "Entries");
    cds.setShadowColor(Color.WHITE);

    cds.setDecreasingColor(Color.RED);
    cds.setDecreasingPaintStyle(Paint.Style.FILL_AND_STROKE);
    cds.setIncreasingColor(Color.GREEN);
    cds.setIncreasingPaintStyle(Paint.Style.FILL_AND_STROKE);
    cds.setNeutralColor(Color.BLUE);
    cds.setShowCandleBar(true);
    cds.setBarSpace(0.5f);
    cds.setShadowWidth(0.1f);

    cds.setHighlightEnabled(false);
    cds.setDrawValues(false);
    candle_chart.setMaxVisibleValueCount(20);

    CandleData cd = new CandleData(cds);

    candle_chart.setData(cd);
    candle_chart.invalidate();

    candle_chart.setVisibility(View.VISIBLE);

}

I need X-axis as time and bar size is more than shadow please help me.

A: I acheived it by the changing constant value in library class 'CandleStickChartRenderer'. This has a method 'drawDataSet' with the code block
mBodyBuffers[0] = xPos - 0.5f + barSpace;
mBodyBuffers[1] = close * phaseY;
mBodyBuffers[2] = (xPos + 0.5f - barSpace);
mBodyBuffers[3] = open * phaseY;

This 0.5 constant you have to change to the some bigger value like 1000, As candle stick library has some issue with bigger x value.


text:
Q: How to open and update excel workbook from python dash application (as a callback)? I am trying to open, update and run an excel file from a Python Dash application, based on input that a user can select.
The application is trying to access an excel and update specific fields (using xlwings) and then calculate the model and use output from those calculations to draw some graphs.
I have my input fields and then I am trying to do callback and open and excel (I tried to do that both in the callback and at the beginning of the application, both result in the same error).
The code below shows exactly what I am doing. The application runs without errors, but I encounter runtime error that CoInitialize was not initiated.
pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)

I was trying to start another thread for the Excel, but I couldn't make it work at all.
@app.callback(
    Output('output-container', 'children'),
    [Input('button', 'n_clicks')],
    [dash.dependencies.State('my-input', 'value')]
)
def update_output(n_clicks, value):

    fpath = 'file_xlsx.xlsx'
    app = xw.App(visible=True)
    wb = xw.Book(fpath)

    flexible_inputs = wb.sheets['Inputs']

    flexible_inputs.range('F4').value = value

    new_value = value

    return 'Success in changing the value of F4 Flexible Inputs to "{}"'.format(new_value)

Any help would be appreciated (also if you have another idea on how to make Dash app update the Excel).


text:
Q: Drawing a rainbow colored ring in android I've been trying to draw a rainbow colored ring in android using the following code:
public void init(){
    ringPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    ringPaint.setStyle(Paint.Style.STROKE);
    ringPaint.setStrokeWidth(8f);
    ringPaint.setShader(new SweepGradient(0, 0, COLORS2, null));
}

@Override
protected void onDraw(Canvas canvas) {
    canvas.drawCircle(getWidth()/2f,getHeight()/2f ,getHeight()/2f - 16f,ringPaint);
}

the value for COLOR2 is the following:
final int[] COLORS2 = new int[]{Color.parseColor("#33004c"), Color.parseColor("#4600d2"),
                                Color.parseColor("#0000ff"), Color.parseColor("#0099ff"),
                                Color.parseColor("#00eeff"),Color.parseColor("#00FF7F"),
                                Color.parseColor("#48FF00"),Color.parseColor("#B6FF00"),
                                Color.parseColor("#FFD700"),Color.parseColor("#ff9500"),
                                Color.parseColor("#FF6200"),Color.parseColor("#FF0000"),
                                Color.parseColor("#33004c")};

The problem is that I'm only getting a subset of the colors, maybe 3 or 4 of the distinct colors in the array and I'm not entirely sure why, can anyone offer some suggestion as to why this is the case?

A: you should specify center of view instead of 0,0 when create SweepGradient
look at example please
public class CustomView extends View {

    private Paint ringPaint;

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void init() {
        ringPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        ringPaint.setStyle(Paint.Style.STROKE);
        ringPaint.setStrokeWidth(8f);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        ringPaint.setShader(new SweepGradient(getWidth() / 2, getHeight() / 2, COLORS2, null));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawCircle(getWidth() / 2f, getHeight() / 2f, getHeight() / 2f - 16f, ringPaint);
    }
}


text:
Q: "phpjs" strpos function not returning true In translating a php script to js, I've used some functions from phpjs.org.
However, it seems that the 'strpos' function does not return true under the same conditions.
$string = "aaa:bbb";
$colons = strpos($string, ":");
echo $colons;
if ($colons == true)
    {echo "yup";}

echoes "3yup", however:
var string = "aaa:bbb";
var colons = strpos(string, ":");
console.log(colons);
if (colons == true)
    {console.log("yup");}

only echoes "3".
Is this my mistake, a bug, or aspect of how javascript handles?
And in any case, what method is recommended to get a true result for the presence of a colon in string?
Thanks!

A: If you only want to get string presence based on strpos, then I suppose you can do the following:
if (strpos(string, ":") != false) {
    console.log("string exists!");
}

A: both php and the phpjs implementation are returning the correct value (3) but the semantics of == are different.
The equivalent JS for the test $colons == true is:
Boolean(colons) == true

A: strpos() in JS doesn't return true. Instead it returns the position, In your case it will return 4.


text:
Q: How can I use A2DP Sink and microphone simultaniously on my bluetooth headsets? I have a couple of really cool headsets that are both Bluetooth. One is like a beanie that has Bluetooth speakers built in (by Rotibox) and the other one is just a regular headset by Bluedio which is called a Turbine. Both of these headsets have A2DP Sink in them which sounds really good. However, I have Skype calls sometimes and it's nice to be able to talk to people from another room. I also would like to be able to do voice recordings with them which I do often. The problem is that when I set the headset to H2DP Sink it can't access the microphone. If I set the microphone to the high fidelity feedback it switches the speaker to HSP/HFP. Can I fix this and use H2DP Sink and the high fidelity feedback simultaniously? I was able to do this sometimes on Ubuntu Unity 16.10.
I am using Pulseaudio 10.0 on Ubuntu 17.10 with the Deepin Desktop Environment.