text:
Q: html: Onfocus, onblur, onkeypress is not working when used innerhtml while creating row for table I am trying to add a row to my table with each cell having an input of type text. But

Onfocus, onblur, onkeypress

are not working on the inputs of the newly created row. Following is my javascript code to add a row to the table:
function Addrow(){
    var table = document.getElementById("myTable");
    var row = table.insertRow(3);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);

    cell1.innerHTML =
        '<input type="text" class="form-control" name="cell1'
        + counter + '" id="cell1' + counter + '" value="0.0" '
        + ' onfocus="this.value = this.value=="0.0"?"":this.value;"
        onblur="this.value = this.value==""?"0.0":this.value;"
        onkeypress="return isNumberKey(event)" />	';
    cell2.innerHTML =
        ' <input type="text" class="form-control" name="cell2'
        + counter + '" id="cell2' + counter + '" value="0.0"'
        + ' onfocus="this.value = this.value=="0.0"?"":this.value;"
        onblur="this.value = this.value==""?"0.0":this.value;"
        onkeypress="return isNumberKey(event)" />	';
    cell3.innerHTML = ' <input type="text" class="form-control" name="cell3'
        + counter + '" id="cell3' + counter + '" value="0.0"'
        + ' onfocus="this.value = this.value=="0.0"?"":this.value;"
        onblur="this.value = this.value==""?"0.0":this.value;"
        onkeypress="return isNumberKey(event)" />	';
    return false;
}

Javascript function to check if input is number or not
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57) {
        alerts("Numbers or Decimal only!!!");
        return false;
    }
        return true;
    }

A: You should use addEventListener event delegation to dynamically created HTML

var formControlList = document.querySelectorAll('.form-control');
for (var i = 0; i < formControlList.length; i++)
{
    formControlList[i].addEventListener('blur', function(event)
    {

    });
}

A: see code bellow:(it is not a bug but in js function called with first lower-case letter)

    function addRow(){
        var table = document.getElementById("myTable");
        var row = table.insertRow(3);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);
    var counter=0;
        cell1.innerHTML = '<input type="text" class="form-control" name="cell1' + counter + '" id="cell1' + counter + '" value="0.0" '+
                        'onfocus="focusData(this)" onblur="blurData(this)" onkeypress=" isNumberKey(event)" />';
        cell2.innerHTML = '<input type="text" class="form-control" name="cell2' + counter + '" id="cell2' + counter + '" value="0.0"' +
                              ' onfocus="focusData(this)" onblur="blurData(this)" onkeypress="isNumberKey(event)" />';
        cell3.innerHTML = ' <input type="text" class="form-control" name="cell3' + counter + '" id="cell3' + counter + '" value="0.0"' +
                              ' onfocus="focusData(this)" onblur="blurData(this)"  onkeypress="isNumberKey(event)" />';

    }
    function blurData(el) {
        el.value = el.value == '' ? "0.0" : el.value;
    }
    function focusData(el) {
        el.value = el.value == '0.0' ? '' : el.value;
    }

        Row1 cell1
        Row1 cell2

        Row2 cell1
        Row2 cell2

        Row3 cell1
        Row3 cell2

    <button onclick="addRow()">Try it</button>

A: Instead of the onblur / onfocus / onkeypress, I'd just use placeholder="0.0" and type="number"

function addRow() {
  const table = document.getElementById('myTable')
  const row = table.insertRow()
  for (let i = 0; i < 3; i++) {
    const cell = row.insertCell(i)
    const input = document.createElement('input')
    input.type = 'number' // only accept numeric input
    input.placeholder = '0.0' // placeholder disappears when a value is entered
    input.className = 'form-control'
    input.name = `cell${i+1}${row.rowIndex+1}`
    cell.appendChild(input)
  }
}

<button onclick="addRow()" type="button">Add a row</button>

A: The problem occurs because you used the quotes within quotes. To represent a " character inside an HTML attribute delimited by " characters, use the entity " .
I'd recommend attaching event listeners using JavaScript rather then using intrinsic event attributes though. It simplifies things greatly.
Note however, that browsers will not execute JavaScript added to the document with innerHTML. If you want to add a script programmatically, the use createElement or appendChild or ...

function Addrow() {
 var table = document.getElementById( 'myTable' ),
      row = table.insertRow(3),
    cell1 = row.insertCell(0),
    cell2 = row.insertCell(1),
    cell3 = row.insertCell(2),
      counter = 1;

 cell1.innerHTML = '<input type="text" class="form-control" name="cell1' + counter + '" id="cell1' + counter + '" value="0.0" ' + ' onfocus="this.value = this.value=="0.0"?"":this.value;" onblur="this.value = this.value==""?"0.0":this.value;" onkeypress="return isNumberKey( event )" />	';
 cell2.innerHTML = ' <input type="text" class="form-control" name="cell2' + counter + '" id="cell2' + counter + '" value="0.0"' + ' onfocus="this.value = this.value=="0.0"?"":this.value;" onblur="this.value = this.value==""?"0.0":this.value;" onkeypress="return isNumberKey( event )" />	';
 cell3.innerHTML = ' <input type="text" class="form-control" name="cell3' + counter + '" id="cell3' + counter + '" value="0.0"' + ' onfocus="this.value = this.value=="0.0"?"":this.value;" onblur="this.value = this.value==""?"0.0":this.value;" onkeypress="return isNumberKey( event )" />	';

 return false
}

function isNumberKey ( evt ) {
 var charCode = ( evt.which ) ? evt.which : evt.keyCode;

 if ( charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57 ) ) {
  alert( 'Numbers or Decimal only!!!' );
  return false;
 }

 return true;
}
<button onclick="Addrow()" type="button">Add a row</button>


text:
Q: How to convert joda dateTime to string in swagger In swagger-core version 1.3.x, we were able to control the rendering of DateTime by using this code as also mentioned in this link :
import com.wordnik.swagger.converter.*;

String jsonString = "{" +
"  \"id\": \"Date\"," +
"  \"properties\": {" +
"    \"value\": {" +
"      \"required\": true," +
"      \"description\": \"Date in ISO-8601 format\"," +
"      \"notes\": \"Add any notes you like here\"," +
"      \"type\": \"string\"," +
"      \"format\": \"date-time\"" +
"    }" +
"  }" +
"}";
OverrideConverter converter = new OverrideConverter();
converter.add("java.util.Date", jsonString);

ModelConverters.addConverter(converter, true);

But this solution doesn't work in swagger 2.0 as I am not able to find OverrideConvertor in swagger 2.0.
At present the date Time from my code is being rendered as below :
LocalDateTime {
chronology (Chronology, optional),
weekOfWeekyear (integer, optional),
weekyear (integer, optional),
monthOfYear (integer, optional),
yearOfEra (integer, optional),
yearOfCentury (integer, optional),
centuryOfEra (integer, optional),
millisOfSecond (integer, optional),
millisOfDay (integer, optional),
secondOfMinute (integer, optional),
minuteOfHour (integer, optional),
hourOfDay (integer, optional),
year (integer, optional),
dayOfMonth (integer, optional),
dayOfWeek (integer, optional),
era (integer, optional),
dayOfYear (integer, optional),
fields (Array[DateTimeField], optional),
fieldTypes (Array[DateTimeFieldType], optional),
values (Array[integer], optional)

A: I am not sure how to add your custom converters to swagger 1.5. But these are workarounds for your use case:
You can create a Model and replace it in the generated swagger object, before converting it to Json.
ModelImpl m = new ModelImpl()
          .description("LocalDateTime in ISO format")
          .format("ISO DateTime")
          .name("DateTime")
          .type("string");
Response response = getListingJsonResponse(app, context, sc, headers, uriInfo);
Swagger swagger = (Swagger) response.getEntity();
swagger.getDefinitions().put("LocalDateTime", m);

That will replace the definition of LocalDateTime with a string type model.
The other way will be to iterate through the definitions, and wherever you see the reference type to LocalDateTime, replace that with a string type:
Map<String, Model> definitions = swagger.getDefinitions();
  for(Map.Entry<String, Model> e : definitions.entrySet()){
    Map<String, Property> propertyMap = e.getValue().getProperties();
    for(String key : propertyMap.keySet()){
      Property value = propertyMap.get(key);
      if(value.getType().equals("ref") && ((RefProperty) value).getSimpleRef().equals("LocalDateTime")){
        propertyMap.put(key, new StringProperty("LocalDateTime in ISO format")
                .example("dd-mm-yyyy")
                .pattern("pattern")
                .description("ISO format string"));
      }
    }
  }

As of now I am unaware of any other cleaner way to achieve this.
UPDATE
Swagger has a mapping for DateTime and not LocalDateTime. So you can also consider moving your types to DateTime if that works for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: If record exists fetch the existing column , compare it and then do an update Or else just insert new record If the record doesn't exist , i need to insert a new  record , but if it exists then
i need to select a particular column value from that row and do an update based on it .
I have managed to write down below query , which does insert / Update using duplicate on update
insert into securities(symbol, buyerquan, sellerquan , totaltradedquan) values('BANKBARODA', 73, 0, 4290270) on duplicate key update  buyerquan=buyerquan+VALUES(buyerquan),sellerquan=sellerquan+VALUES(sellerquan),totaltradedquan=totaltradedquan+VALUES(totaltradedquan)

This is my sqlfiddle http://sqlfiddle.com/#!2/aaf91/5
My requirement is
If the record exists , how can i fetch the existing column , compare it and then do an update ??
Do we need to write an another SQL query for fetching  existing column value ??
If record exists fetch the existing column , compare it and then do an update Or else just insert new record
Can we do all this in same query ??
Can anybody please help me .

A: Mysql has a shortcut for that, it's called "INSERT ... ON DUPLICATE KEY UPDATE"
http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html

A: Your question is vague.  For instance, you don't specify what columns are used to define a duplicate.  Based on your query, I am guessing that you mean symbol.
Your query is:
insert into securities(symbol, buyerquan, sellerquan , totaltradedquan)
    values('BANKBARODA', 73, 0, 4290270)
    on duplicate key update buyerquan = buyerquan+VALUES(buyerquan),
                            sellerquan = sellerquan + VALUES(sellerquan),
                            totaltradedquan = totaltradedquan + VALUES(totaltradedquan);

This seems to be the right syntax (which for most people that is the hard part of the question).  The only thing that is missing is the specification of uniqueness:
create unique index securities_symbol on securities(symbol);

You can also specify this condition in the create table statement, using the unique keyword.


text:
Q: Sound distortion when extracting from Jar I have sounds in my jar file directory.
I need to use these sounds and I am trying to extract them using this method:
String charset = "ISO-8859-1";
public void extractSounds(String pathIn, String pathOut) throws IOException {
    BufferedReader r = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(pathIn), charset));
    String line = r.readLine();
    String result = null;
    FileOutputStream fos = new FileOutputStream(pathOut);
    while(line != null) {
        if(result != null) {
            result += "\r" + line;
            line = r.readLine();
        } else {
            result = line;
            line = r.readLine();
        }
    }
    fos.write(result.getBytes(charset));
}}

But when I extract the sounds they get distorted and I don't know what the problem is, because it basically just copies the file.
Sounds:
Original,
Extracted
I would be very grateful if you could help me find a solution or suggest another method to extract the sound files.

A: Don't assume you are reading text. You should not try to mutate the data. Just copy it in chunks.
Try something like
InputStream in = ...;
ByteArrayOutputStream out = new ByteArrayOutputStream();
final int BUF_SIZE = 1 << 8;
byte[] buffer = new byte[BUF_SIZE];
int bytesRead = -1;
while((bytesRead = in.read(buffer)) > -1) {
    out.write(buffer, 0, bytesRead);
}


text:
Q: Is javax.xml.soap better than apache cxf? This week I had to look into a Java WebService project which was using SOAP packages javax.xml.soap.*.
I have not used this before but the Apache CXF library to create a SOAP webservice.
I have a question on javax.xml.soap.*
Is it better than CXF in terms of performance?
In terms of coding I see CXF is amazing as no need to worry about SOAP API at all and simply by using annotations can create a service in minutes.
Also is MessageFactory and SOAPConnection are threadsafe? I am asking this to save the creation of these objects every time. If the creation is not a overhead then no problems, but if it is then I want to create them only once. I couldn't find in the javadoc about thread safety.

A: javax.xml.soap is a low-level API, CXF is an implementation of that API, one of many implementations. CXF uses javax.xml.soap underneath, as do all of the implementations.
A more meaningful comparison is between JAX-WS implementations, such as JAX-WS-RI and CXF.

A: Actually, CXF does NOT use javax.xml.soap (SAAJ) underneath unless its required to do so (JAX-WS handlers are present, Provider type things, etc....).
In general, using SAAJ will be slower than CXF since it doesn't allow streaming which CXF would normally do.   With SAAJ, the entire SOAP message is in memory as a DOM.   That said, if you DO want/need your data as a DOM, it can be a little faster as less processing is needed.


text:
Q: Is it possible to use andStubReturn without replay() in EasyMock Well the question is the same as the title.
Example of what I am aiming at,
Order order = createNiceMock(Order.class);
Products products = createNiceMock(Products.class);
expect(myDomain.getOrder()).andStubReturn(order);
replay(myDomain);
expect(myDomain.getOrder().getProducts()).andSubReturn(products);

I think this is a pretty nice way to handle my test domain. The thing is that I don't want to use replay to be able to do the myDomain.getOrder(). Is it possible to do this without the replay?

A: I think what you're trying to do is this:
Order order = createNiceMock(Order.class);
Products products = createNiceMock(Products.class);
expect(myDomain.getOrder()).andStubReturn(order);
expect(order.getProducts()).andSubReturn(products);
replay(myDomain, order);


text:
Q: How can I add significance labels to a paired boxplot with discrete x-axis values? As the header says, I'm am trying to add significance stars into a boxplot with paired boxplots and a discrete x-axis with geom_signif. Is there any possibility to set the xmin and xmax values above one of the paired boxplots? As you can see in the attached image of the Plot, I managed to show the significance level for the differences in 'Behandlung' (= K and T), but I would also need to give significance levels between silicon '-' and silicon '+'.

Plot
Here is the code that creates the image:
blf <- data.frame(min.Blattlf = c(34,28,27,27,22,23,34,39,39,21,39,24,27,25,24,26,29,21,20,29,23,20,26,20,19,18,17,15),
                   Behandlung = c('K','K','K','K','K','K','K','K','K','K','K','K','K','K','T','T','T','T','T','T','T','T','T','T','T','T','T','T'),
                   Silizium = c('-','-','-','-','-','-','-','+','+','+','+','+','+','+','-','-','-','-','-','-','-','+','+','+','+','+','+','+'))

ggplot(data = blf, aes(x = Behandlung, y = Min.Blattleitfähigkeit, fill = Silizium)) +
  geom_boxplot(outlier.size = 2) +
  theme_bw() +
  labs(x = 'Behandlung', y = expression(paste("min. Blattleitfähigkeit ", (mmol~m^-2~s^-1)))) +
  geom_signif(annotations = "***", y_position = 41, xmin = c('K'), xmax = 'T')
  theme(axis.title.x = element_text(size = 12, margin(b = 0, unit = "pt")),
        axis.title.y = element_text(size = 12, margin(l = 0, unit = "pt")),
        axis.text.x = element_text(size = 10),
        axis.text.y = element_text(size = 10),
        axis.ticks.length = unit(5, "pt"),
        legend.title = element_text(size = 12),
        legend.text = element_text(size = 12))

If it doesn't work with ggsignif, are there any other possible solutions?
Thank you for your help,
Mo


text:
Q: Shortcode not working in widget I created the following shortcode:
function newsletter_signup_shortcode( $atts ) {
$post_type = get_post_type();

// Attributes
extract( shortcode_atts(
    array(
        'location' => get_permalink(),
        'show_title' => 'yes',
    ), $atts )
);

// Return the unfiltered content if we're not on a post.
if ( $post_type != 'post' ) {
    return $content;
}

ob_start();
?>

<!-- MailChimp Signup Form outputs here - code omitted for clarity -->

<?php
// Add the opt-in form after the post content.
return $content . ob_get_clean();
}
add_shortcode( 'newsletter_signup', 'newsletter_signup_shortcode' );

This works great on the home page and blog post pages, within the post and in the sidebar widget.
However, when I view a page, the sidebar widget does not display the shortcode content:
What am I missing here?

A: You have a conditional in your function that will skip (return) if the current "view" is not a single post. You also have an undefined variable $content - the following has the condition removed and undefined variable fixed (always, always have debugging on when building with WordPress):
function newsletter_signup_shortcode( $atts ) {
    $post_type = get_post_type(); // Not sure if you still need this for your MailChimp template?

    // Attributes
    extract( shortcode_atts(
        array(
            'location' => get_permalink(),
            'show_title' => 'yes',
        ), $atts )
    );

    ob_start();
    ?>

    <!-- MailChimp Signup Form outputs here - code omitted for clarity -->

    <?php
    return ob_get_clean();
}


text:
Q: Wake up Arduino in sleep mode after x hours I need to put an Arduino to sleep mode to save battery, but after x hour (A choice that makes the user), I need that the Arduino wakes up, do some action, and then goes to sleep again. How can I do it? I see that the sleep mode can be interrupt by Interrupt, but I need that the interrupt is trigger not by a pin but by the time. Any suggestion?
Thanks in advance!

A: The answer to your question depends on how much low power you need and which time precision you need. Achive 200nA sleep current requires some work and time precision is a compromise with low power.
However, here are some clues:

*

*Use an external RTC module able to generate an interrupt at some precise moment

*Use an external 32kHz Xtal to clock timer2 asynchronously and generate interupt to wake up from "power-save" sleep mode

*Use the internal watchdog timer in interrupt and reset mode to wake up from "power-down" mode. You will wake up every 8s but for very short duration if the code is optimized.

The last solution seems most appropriate for some basic demo. With a good code you will achieve honorable results. And do not forget to read "Minimizing Power Consumption" section of the MCU datasheet.
EDIT

how much more current I consume if the Arduino wakes up every 8 seconds?
  There is a way to calculate it?

Too calculate the average current (I would say estimate) read datasheet at section "atmega328P typical characteristics"

*

*@5V 8MHz the consumption is about 5.5mA,

*in power down @5V with watchdog 6.5µA.

With about 1ms active every 8s you will achieve 7.2µA mean.
Note that the board consumption is not only the MCU on Arduino board. With an Arduino I don't know how much you will globally consume but it will be more than my calculation. To achieve 200nA stated in datasheet, you will need to do your own board and use external low power watchdog...

And second: the AtMega will ruin faster if wakes up every 8 seconds?

An AtMega does not have ageing issues. It can run constantly for 20 years without issues (except if you use EEPROM or flash self-programming).


text:
Q: Не получается поставить Ubuntu У меня HP ProBook 4730s, Windows 8.Загрузил на флешку убунту по этой инструкции: Установка Ubuntu с USB Flash-диска.Перезагружаю комп, жму Esc и там выбираю Boot Option, Hard Drive (или как то так) В общем появляется синее окно, где я выбираю Install Ubuntu, после небольших настроек языка и wifi ноут перегружается. По идее дальше должна пойти сама установка, но у меня запускается винда, как ни в чем не бывало. Что за ерунда? Помогите плиз?P.s. ставить нужно, оставив W8

A: Попробуйте сделать ВСЕ по инструкции... В частности:
*
*выбрать Removable Devices (тогда загрузитесь с флешки - она и есть тот самый "Removable Device"), поскольку, выбрав "Hard Drive (или как то так)" вы указываете, что грузиться надо как обычно - с жесткого диска...
*выбрать НЕ "Install Ubuntu", а, как указано в инструкции, "Default"
A: Попробуйте перед инсталляцией запустить режим "Запустить Ubuntu без установки" таким образом Вы проверите совместимость Вашего железа и увидите систему в действии на Вашем оборудовании.
A: Я правильно понимаю, что вы пытаетесь установить Убунту на тот же NTFS раздел, где у вас уже Windows8 стоит? Похоже, вы первый, кто это пробовал сделать. Надо бы вот что:
*
*Средствами Windows ужать имеющийся NTFS раздел до высвобождения необходимого пространства.
*Далее следовать вот этим инструкциям:http://www.ubuntu.com/download/help/create-a-usb-stick-on-ubuntu иhttp://www.ubuntu.com/download/help/install-desktop-latest
*И пользуясь этими инструкциями, установить Убунту на свободное место из п.1!Загрузчиком там будет GRUB. Седьмую венду он подхватывает, думаю что и восьмую тоже!А если совсем влом с этим ковыряться, то при наличии венды и и-нета можно всё сделать через вендовый инсталлер: http://www.ubuntu.com/download/help/install-ubuntu-with-windowsПравда, он несовместим с восьмёркой и UEFI, но кому-то может эта инфа полезна будет.Но в любом случае надо сперва место под убунтовый раздел освободить (см. п.1).
A: Насколько я знаю на новых пк/нотах с предустановленной win8 вместо BIOS используется UEFI. Если это как раз ваш случай, то почитайте: Установка Ubuntu на новые платы с UEFI/EFI.


text:
Q: L7805CV 5V Voltage Regulator to IP camera over POE I am having a problem with getting my IP cameras to work over my home-made POE cable.
The parts I made in order to have POE are the following:

*

*L7805CV 5V Voltage Regulator (for input to the IP Cameras 5v/ground pin. 12V -> 5V) link: http://www.ebay.com/itm/L7805CV-5V-V...item2a259974bb

*12V 2A DC Power Adapter Supply For CCTV Camera US (for use on the opposite side of the IP camera to inject into the ethernet cable) link: http://www.ebay.com/itm/12V-2A-DC-Po...item4604a8bda9

*Night vision Waterproof Outdoor Wifi Wireless WIFI IP Camera IR 24 LED M-JPEG (The IP camera itself) link: http://www.ebay.com/itm/180810824039...039%26_rdc%3D1

*Power over Ethernet PoE Adapter Injector + Splitter Kit (to hook up between the switch and the IP Camera) link: http://www.ebay.com/itm/160680383412...84.m1423.l2649

*1000Ft Direct Burial Waterproof Cat 5e Outdoor UTP CMX (used from the switch [garage] to the IP Cameras [outside]) link: http://www.ebay.com/itm/1000-Ft-Dire...vip=true&rt=nc
Now the power supply that comes with it says this:
INPUT: 100-240V- 50/60Hz 0.4A max
OUTPUT: 5V 2A

I noticed when I hook up the original power supply to it-it does not power on. I'm just guessing its because I have the 5V Voltage Regulator in there and its feeding it less than 5V?
But once I connected it up using the POE injectors it works just fine (tested with a ethernet cable about 10ft long or so). Now that I placed them outside I have (again guessing) about ~120ft of ethernet cable from one tree IP Camera to my garage. It's using the direct burial ethernet cable for this (the original test was using a standard ethernet cable).
The power is coming from the 12V 2A DC Power Adapter Supply hooked into the POE injector. From there the POE injector is hooked to the switch and the other end to the direct burial ethernet cable that's going outside to the IP Camera. At night I can see the glow of the red IR LEDs so I know it's getting power. And I also see that its blinking (green led) on the switch so I know it's communicating... But when I try to find its IP on my router it does not show up at all?
And again, I tested this out using the 12V 2A DC Power Adapter Supply/ POE injector and a standard 10ft ethernet cable and it worked just fine.
I tested the voltage with a volt meter to make sure it was getting enough from that long run. I had 12V on one side (the garage) going through the injector/ethernet wire and on the other end (outside at the other injector from the ethernet) I had about 12.4V constant so it really did not drop at all from that 150ft ethernet run.
I also tested to make sure my crimping on the ends of the ethernet were correct (had a gizmo that sent out a signal and showed me what order the wires are in). They all came back the same.
So what all should I try testing out first? Second? Third? I already heat shrink all the connections outside so I hope I don't have to pull those apart to disconnect the POE/splitter!

A: Even thought the pins are connected in the right order between the two RJ45 connectors, they still might be using the wrong wires.  It's important that the twisted pairs are matched up correctly.  Did you follow T568B?

A: First of all, you should measure your voltage while the load at its peak of power consumptions, which means your IP camera IR is switched on.
You should'nt disconnect the load and check the voltage, which aparently there is no current circulation which means no voltage drop.
If you measure it while Camera is connected, you most likely having around 5-7 VDC.
Your problem the power supply it doesn't regulate the voltage drop by increasing the voltage input and maintaining a set-point of 12 volts all the time.
In case of having low voltage, you can't predict what type of functionality and behavior your camera will have.


text:
Q: How can I open a VIM process with one user (using su) and then access with another user? I want to open a VIM instance with one user account (using su), then login as another user and access the same session with that user.
Example User1:
su - user2 -c vim somefile.txt
Then I want to login as User2 and then access that VIM process created by that first user. I know it's possible but I'm not sure how to do it.


text:
Q: How can I generate pem file for push notifications in iphone? Using this link for generate pem file for push notification, but I can't understand following steps...

Installing the SSL Certificate and Key on the Server
You should install the SSL distribution certificate and private
  cryptographic key you obtained earlier on the server computer on which
  the provider code runs and from which it connects with the sandbox or
  production versions of APNs. To do so, complete the following steps:

*

*Open Keychain Access utility and click the My Certificates category in the left pane.

*Find the certificate you want to install and disclose its contents.
  You'll see both a certificate and a private key.

*Select both the certificate and key, choose File > Export Items, and export them as a Personal Information Exchange (.p12) file.

*Servers implemented in languages such as Ruby and Perl often are better able to deal with certificates in the Personal Information
  Exchange format. To convert the certificate to this format, complete
  the following steps:

*

*In KeyChain Access, select the certificate and choose File > Export Items. Select the Personal Information Exchange (.p12) option,
  select a save location, and click Save.

*Launch the Terminal application and enter the following command after the prompt: openssl pkcs12 -in CertificateName.p12 -out
  CertificateName.pem -nodes.

*Copy the .pem certificate to the new computer and install it in the appropriate place.

A: Here's a screenshot of what you have to select in step 3. It's not two certificates. It's a certificate + key.

A: I would suggest a much more simple solution. Just use Certifire.
Certifire is a macOS application that generates Apple Push Notification Certificates with just one click in a couple of seconds.
Here are the steps:
1. Download the app.
2. Log in using your Apple Developer Account credentials.
3. Choose the App-ID
4. Click "Generate" button
5. You're done!
You will get APN certificates in .pem format as well as in .p12 format.
Even more, you will get also combined .pem and .p12 too (key+cert)!
Much more, you will get no-passphrase versions of all these certificates also!

A: finally i sloved generate push notification certifcates
complete step for generate push notification certificates.....
1) open key chain and request certificate show in below image.

2) change common name as your project_name.

3) in keychain open key you can show two key public and private

4) write click on private key and export it.

5) make name project_name_key.p12
6) add password ex-1234
7) enter system login password and save it. now you have following certificates.

8) now goto developer account (https://developer.apple.com/devcenter/ios/index.action) and goto identifier create new if not exits. and edit setting.

if push notification disable then enable it from edit.

9) for development you can create first one and distribution you can select last one.

10) after select  and generate download apns certificate and put into desktop and double click on it.
11) then open key chain and goto certificates. and you can show your push service open then you show private key.
export it with 1234 password.

12) now you have following file.

13) open terminal and goto desktop.

14) generate .pem file using following line for push_cert.p12 file
openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in push_cert.p12

then enter password:-1234

15) generate .pem file using following line for project_name_key.p12 file
openssl pkcs12 -nocerts -out apns-dev-key.pem -in project_name_key.p12

then enter password:-1234
Enter PEM pass phrase:1234
Verifying - Enter PEM pass phrase:1234

16) enter following 3 line in terminal
openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem

Enter pass phrase for apns-dev-key.pem:1234
cat apns-dev-cert.pem apns-dev-key-noenc.pem > apns-dev.pem

17) you have following certificate.

18) apns-dev.pem file send on server and it pass is 1234
19) for development you must use gateway.sandbox.push.apple.com server.
and distribution you can use gateway.push.apple.com server.

A: For **

*

*Production Push Notification
**
I took reference from this link
To enable Push Notification for your iOS app, you will need to create and upload the Apple Push Notification Certificate (.pem file) to us so we will be able to connect to Apple Push Server on your behalf.
(Updated version with updated screen shots Here http://www.apptuitions.com/generate-pem-file-for-push-notification/)
Step 1: Login to iOS Provisioning Portal, click "Certificates" on the left navigation bar. Then, click "+" button.

Step 2: Select Apple Push Notification service SSL (Production) option under Distribution section, then click "Continue" button.

Step 3: Select the App ID you want to use for your BYO app (How to Create An App ID), then click "Continue" to go to next step.

Step 4: Follow the steps "About Creating a Certificate Signing Request (CSR)" to create a Certificate Signing Request.

To supplement the instruction provided by Apple. Here are some of the additional screenshots to assist you to complete the required steps:
Step 4 Supplementary Screenshot 1: Navigate to Certificate Assistant of Keychain Access on your Mac.

Step 4 Supplementary Screenshot 2: Fill in the Certificate Information. Click Continue.

Step 5: Upload the ".certSigningRequest" file which is generated in Step 4, then click "Generate" button.

Step 6: Click "Done" to finish the registration, the iOS Provisioning Portal Page will be refreshed that looks like the following screen:

Then Click "Download" button to download the certificate (.cer file) you've created just now. - Double click the downloaded file to install the certificate into Keychain Access on your Mac.
Step 7: On your Mac, go to "Keychain", look for the certificate you have just installed. If unsure which certificate is the correct one, it should start with "Apple Production IOS Push Services:" followed by your app's bundle ID.

Step 8: Expand the certificate, you should see the private key with either your name or your company name. Select both items by using the "Select" key on your keyboard, right click (or cmd-click if you use a single button mouse), choose "Export 2 items", like Below:

Then save the p12 file with name "pushcert.p12" to your Desktop - now you will be prompted to enter a password to protect it, you can either click Enter to skip the password or enter a password you desire.
Step 9: Now the most difficult part - open "Terminal" on your Mac, and run the following commands:
cd
cd Desktop
openssl pkcs12 -in pushcert.p12 -out pushcert.pem -nodes -clcerts

Step 10: By using this link(click here)
You can check weather the .PEM file is valid or not ---> if it's valid you will get success message with notification like:

For **

*

*Development Push Notification
**
Just Watch the following Youtube link Click here and enjoy..

A: Just to add the @Nitin's very well described answer. After creating the pem, you can validate it with the
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert MyKey.pem -key MyKey.pem
where MyKey is the name of your pem file.
Replace the gateway.sandbox.push.apple.com with gateway.push.apple.com, to connect to the live APNS.

A: *

*Right click on your APNs certificate and click on export. This will generate the .p12 certificate on desktop

*open terminal cd desktop and convert .p12 into .pem using following command
openssl pkcs12 -in Certificates.p12 -out Certificates.pem -nodes -clcerts


text:
Q: HOWTO: Decode a single byte into a string using different encodings I would like to represent a single Byte into different types of encodings like unicode, UTF-8, ASCII and Operating System's current ANSI code page, so how could I do this in vb.net?
For example, suppose I have a byte array with numbers from 0 to 255 and its length of 256:
Dim byteArray(255) As Byte

byteArray(0)=0
byteArray(1)=1
byteArray(2)=2
...
byteArray(255)=255

I am not sure at all if below code accomplishes what I want. Anyone could confirm me if it is correct? I am not expert in this area...
Dim unicode_string as String
Dim utf8_string as String
Dim ascii_string as String
Dim default_string as String

For i as Integer = 0 to byteArray.length - 1
   ' As Unicode is UTF-16, uses 2 bytes, we construct a new byte array with its second byte to zero.
   unicode_string = Encoding.Unicode.GetString(New Byte() {byteArray(i), 0})
   utf8_string = Encoding.UTF8.GetString(byteArray, i, 1)
   ascii_string = Encoding.ASCII.GetString(byteArray, i, 1)
   default_string = Encoding.Default.GetString(byteArray, i, 1)

   Console.WriteLine("{0} {1} {2} {3}", unicode_string, utf8_string, ascii_string, default_string)
Next


text:
Q: Click on Dock should switch to full screen app, but this is broken. How to fix? Suppose I have a full screen app. I am on a Desktop space. I click on the full screen app's Dock icon, but nothing happens. I would expect the system to switch to that full screen app.
I vaguely remember turning this off via some defaults mockery a month ago. Now, setting workspaces-auto-swoosh to YES does not help. 'When switching to an application, switch to a Space...' option in Mission Control preferences is turned off but also does not help.
This works on a test account by default on same machine.
Additionally, in the ideal case, it would only switch when I explicitly click on Dock icon, the default behaviour to automatically switch every time an app has some popup dialog to display is also very annoying. I don't know if this is possible.
I am using OS X Yosemite.
Thank You!


text:
Q: Converting temperature to RGB value I am calculating the current temperature to RGB related to a maximum temperature:
val = round(temp / tempMax * 255, 0);
if (val > 255) val = 255;

In maths the function is v=temp/tempMax*255.
This works for a temperature between 0 and tempMax.
I want to do the same but in an area between minTemp and maxTemp-5.
That means if the temp is exactly minTemp, val should be 0 and if it is maxTemp-5 it should be 255. all temperature that are lower than minTemp set val to zero and there will be special if statement for the area between maxTemp-5 and maxTemp. All the ifs are no problem but how do I need to modify my function that it calculating proportionally to the given borders?

A: val = round(((temp - minTemp) * 255) / ((maxTemp - 5) - minTemp), 0);
if (val < 0) val = 0;
else if (val > 255) val = 255;

You subtract minTemp from temp so that the range starts at zero. Then multiply by 255 / ((maxTemp - 5) - minTemp) to scale the range of minTemp -> maxTemp - 5 to 0 -> 255. Finally clamp the result to the allowable range.
I rearranged the formula to do the multiply first, so that it also works using integers. If you wanted it to work with unsigned numbers you could clamp to minTemp before applying the formula and remove the check for v < 0.

A: *

*RGB color of black body at some temperature
is directly related to B-V index see:

*

*Star B-V color index to apparent RGB color
you have the equation t=f(B-V) in the OP just reverse it.

*what you asking is just linear interpolation
simply:
i=i0 + (t-t0)*(i1-i0)/(t1-t0)

where t0,t1 is input temp range and i0,i1 is output intensity range.


text:
Q: I'm having problems whilst creating a quiz using python loops The start of my code works fine but,the bottom part consisting on the score and answer doesn't. I'm doing a school project on this and need a solution quick. But I have to be using loops! The part where i'm trying to tell the user that the answer is correct isn't working. The part where i'm revealing the right answer isn't working as well. The score isn't working as well.
print ('WELCOME TO THE MULTIPLE CHOICE TEST\n')
name = input('WHAT IS YOUR NAME? ')
print ('\nHI THERE ' + name + '! LET''S PLAY A GAME!\n')
print ('I will ask you 10 questions and give you three choices for each question.\n\nYou select which choice is the correct answer. Eg. A, B,C or D\n')

score = 0
score = int(score)

qn1 = ["What's color of sky?", "a)Red", "b)Blue", "c)White", "d)Black"]

def print_question(qn_num):
    print(qn_num[0])

    print(qn_num[1])
    print(qn_num[2])
    print(qn_num[3])
    print(qn_num[4])

print_question(qn1)

answer = input ()
answer =int(answer)
if answer == 2:
   print ("good work")
   score = score + 1

else:

    print ("better luck next time")

    score = score - 1

A: You can ask the answer in an infinite loop, and also show the score
print ('WELCOME TO THE MULTIPLE CHOICE TEST\n')
name = input('WHAT IS YOUR NAME? ')
print ('\nHI THERE ' + name + '! LET''S PLAY A GAME!\n')
print ('I will ask you 10 questions and give you three choices for each question.\n\nYou select which choice is the correct answer. Eg. A, B,C or D\n')

score = 0
score = int(score)

qn1 = ["What's color of sky?", "a)Red", "b)Blue", "c)White", "d)Black"]

def print_question(qn_num):
  for st in qn_num:
    print(st)

print_question(qn1)

allowed_answers = ["a", "b", "c", "d"]
wrong_answer = True
while(wrong_answer):
  answer = input ("select answer: ")

  if answer == 'b':
   print ("good work")
   score = score + 1
   wrong_answer = False
  elif answer not in allowed_answers:
    print ("Bad input, you have to chose between " + ",".join(allowed_answers) )
  else:
    print ("better luck next time")
    score = score - 1
  print("Your score is: " + str(score))


text:
Q: Python SMTP Authenticate email:pass via combolist in txt - Error need to Fi It only works if I have one user@domain.com:password line in accounts.txt
but as soon as i add more than one email:password lines it gives error, e.g
user1@first.com:password
user2@second.com:password
user3@third.com:password
user4@fourth.com:password

all gives error even if the emails are good or bad, so it's not authenticating.
If it's one line alone it authenticates / connects and tell if the email is good or bad
user1@first.com:password

It's only accurate to first line if only one combo is there but gives error to all as soon as I edit the txt and add more lines of combos
i want it to be able to connect and give connect or notconnect to more than one combolist up to 100k and more, guess there should be an array in the smtp server
Here's my code:
import smtplib
import socks
import codecs
import unicodedata
import random
from multiprocessing.pool import ThreadPool

# PROXY_TYPE_HTTP
# PROXY_TYPE_SOCKS5

proxy_type = socks.PROXY_TYPE_SOCKS5
use_proxies = False
thead_count = 1
use_encrpytion = False

accounts = []
accounts_checked = 0
accounts_valid = []
accounts_invalid = []

proxies = []

def check_account(email, password):
    try:
        if (use_proxies):
            proxy = random.choice(proxies)
            proxy_host = proxy.split(':')[0]
            proxy_port = int(proxy.split(':')[1])

            socks.setdefaultproxy(proxy_type, proxy_host, proxy_port)
            socks.wrapmodule(smtplib)

        mailserver = smtplib.SMTP("mail." + email[email.index('@') + 1 : ],587)
        mailserver.ehlo()
        if (use_encrpytion):
            mailserver.starttls()
        mailserver.login(str(email), str(password))
        mailserver.quit()

        return True
    except smtplib.SMTPAuthenticationError:
        return False

def get_status(account):
    global accounts_checked, accounts

    if (':' not in account):
        return False

    email = account.split(':')[0]
    password = account.split(':')[1]

    valid = check_account(email, password)

    if (valid):
        print("Valid: ", account)
        f1 = open("connect.txt", "a+")
        f1.write(account)
        f1.close()
        accounts_valid.append(account)
    else:
        f2 = open("not_connect.txt", "a+")
        f2.write(account)
        f2.close()
        accounts_invalid.append(account)

    accounts_checked += 1

    print("(" + str(accounts_checked) + "/" + str(len(accounts)) + ")")

    return valid

if __name__ == "__main__":

    if (use_proxies):
        print("Reading \"proxies.txt\"...")

        with open("proxies.txt") as f:
            for line in f:
                if (':' in line):
                    proxies.append(line)

        print("Found " + str(len(proxies)) + " proxies.")

    print("Reading \"accounts.txt\"...")

    with codecs.open("accounts.txt", encoding='utf-8') as f:
        for line in f:
            line = unicodedata.normalize('NFKD', line).encode('ascii','ignore').decode('ascii')
            if (':' in line):
                accounts.append(line.replace("\n", "").replace("\t", ""))

    print("Found " + str(len(accounts)) + " accounts.")

    print("Creating thread pool...")

    pool = ThreadPool(thead_count)
    results = pool.map(get_status, accounts)
    pool.close()
    pool.join()

    print("Done checking, writing output...")

    print("Completed!")


text:
Q: Highcharts Tooltip Show Arrow/Caret when followPointer flag is on I am trying to have Highcharts cartesian charts show the caret/arrow on my tooltip despite having followPointer turned on.
Reading the docs, the one way to show the caret is to turn followPointer off. However, for my uses, it would be ideal if I could have it on for all situations as well.
I tried checking the source code for Tooltips here to see how followPointer code is implemented, perhaps it would tell me a little whether there's a flag that switches the arrow on or off, but it doesn't seem like I can find anything of this sorts.
If you need, here's a fiddle to play around with: http://jsfiddle.net/Malinga/oo2njkhs/2/

A: I found the answer here
You basically need to override the move method implemented in Highcharts to set skipAnchor to false.
(function(H) {
  H.wrap(H.Tooltip.prototype, 'move', function(proceed, x, y, anchorX, anchorY) {
    var tooltip = this,
      now = tooltip.now,
      animate = tooltip.options.animation !== false && !tooltip.isHidden &&
      // When we get close to the target position, abort animation and land on the right place (#3056)
      (Math.abs(x - now.x) > 1 || Math.abs(y - now.y) > 1),
      skipAnchor = tooltip.followPointer || tooltip.len > 1;

    skipAnchor = false;

    // Get intermediate values for animation
    H.extend(now, {
      x: animate ? (2 * now.x + x) / 3 : x,
      y: animate ? (now.y + y) / 2 : y,
      anchorX: skipAnchor ? undefined : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
      anchorY: skipAnchor ? undefined : animate ? (now.anchorY + anchorY) / 2 : anchorY
    });

    // Move to the intermediate value
    tooltip.getLabel().attr(now);

    // Run on next tick of the mouse tracker
    if (animate) {

      // Never allow two timeouts
      clearTimeout(this.tooltipTimeout);

      // Set the fixed interval ticking for the smooth tooltip
      this.tooltipTimeout = setTimeout(function() {
        // The interval function may still be running during destroy,
        // so check that the chart is really there before calling.
        if (tooltip) {
          tooltip.move(x, y, anchorX, anchorY);
        }
      }, 32);

    }
  });
}(Highcharts));


text:
Q: Why ContentChild is undefined? I have two components FormComponent and Test1Component.
Test1Component uses ng-content to display FormComponent
FormComponent.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-form',
  template:`

                {{headerTitle}}

            <ng-content select="[form-body]"></ng-content>

                <button class="btn btn-primary">{{resetBtnText}}</button>
            <button class="btn btn-primary" (click)="saveForm()"> {{saveBtnText}} </button>
            <button class="btn btn-primary">{{addBtnText}}</button>

  `
})
export class FormComponent{
  @Input() headerTitle:string = "Header Title";
  @Input() saveBtnText:string = "Save";
  @Input() resetBtnText:string = "Reset";
  @Input() addBtnText:string = "Add";
  @Output() save:EventEmitter<any> = new EventEmitter();

  constructor(){}

  saveForm(e: any){
    this.save.emit("save");
    console.log("FormComponent save");
  }
}

Test1Component.ts
import { Component, Inject, OnInit, ContentChild } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { FormComponent } from './form.component';

@Component({
  selector: 'app-test1',
  template: `
    <app-form headerTitle="my header" (save)="saveForm(complexForm.value, $event)">

                <form [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)">

                        First Name:
                        <input class="form-control" type="text" placeholder="John" [formControl]="complexForm.controls['firstName']">

                </form>

    </app-form>
  `
})
export class Test1Component {
    @ContentChild(FormComponent) contentChildForm: FormComponent;

  complexForm : FormGroup;

  constructor(private fb: FormBuilder){
    this.complexForm = fb.group({
        'firstName' : "",
        'lastName': "",
        'gender' : "Female",
        'hiking' : false,
        'running' : false,
        'swimming' : false
    });
  }

  saveForm(){
    console.log(this.contentChildForm);
    debugger;
    console.log("Test1Component save");
    return true;
  }
}

Why is Test1Component.saveForm() is logging this.contentChildForm as undefined ?
How to fix it ?
This is the plunker I made https://plnkr.co/edit/xbTgRuSd7nBIrOWsE1zO , please open console to see logs.

A: I would use @ViewChild in your case because i don't see any projectable nodes with type FormComponent in your Test1Component
Modified Plunker


text:
Q: How to run mongodb shell command with Spring data mongotemplate When I'm running an aggregation file into mongo , I use the mongo utility
like:
mongo localhost:27017/mydb aggregationfile.js

How I can do the same programmatically with Spring Data MongoTemplate?


text:
Q: how to read if radio button checked and save it as 1 with javascript? I have 3 radio buttons:

    <input type="radio" name="group1" id="antwort1" value="" onmousedown="this.__chk = this.checked" onclick="if (this.__chk) this.checked = false" />

    <input type="radio" name="group1" id="antwort2" value="" onmousedown="this.__chk = this.checked" onclick="if (this.__chk) this.checked = false" />

    <input type="radio" name="group1" id="antwort3" value="" onmousedown="this.__chk = this.checked" onclick="if (this.__chk) this.checked = false" />

I am trying to read if radio button is checked, and save a value (need 1 or/ 0) like this:
var frage1 = document.getElementById("frage1").innerHTML;
var antwort1 = document.getElementById("antwort1");
var antwort2 = document.getElementById("antwort2");
var antwort3 = document.getElementById("antwort3");

antwort1 = $('input[id="antwort1"]:checked').val();
antwort2 = $('input[id="antwort2"]:checked').val();
antwort3 = $('input[id="antwort3"]:checked').val();

antwort 1, 2, 3 are undefined. I need to get 0 or 1.

A: You could just use .length since you're querying IDs:
antwort1 = $('#antwort1:checked').length;
antwort2 = $('#antwort2:checked').length;
antwort3 = $('#antwort3:checked').length;

A: Use prop() like
antwort1 = $('input[id="antwort1"]').prop();
antwort2 = $('input[id="antwort2"]').prop();
antwort3 = $('input[id="antwort3"]').prop();

Fiddle

A: You could do like this:
var antwort1 = $('#antwort1:checked').length;
var antwort2 = $('#antwort2:checked').length;

console.log(antwort1);
console.log(antwort2);

FIDDLE DEMO


text:
Q: Android SwitchCompat style I tested my app on my new device with android 5.1.1. In my SettingsActivity i have a switch. I already read some posts and changed it to android.support.v7.widget.SwitchCompat but the problem still is the following: On my old device the switch looks very nice. you can set two texts for textOn and textOff and it fits perfectly. but since api 21 or whatever I get this little bastard here:

It looks like ****. How can I restyle it for all devices like the lollypop switch?
Edit:
The question above is answered.
One tiny thing is missing: How to change the color of the text on the switch.(Not the tag on the left side!!!)
styles.xml
<style name="SwitchTextAppearance" parent="TextAppearance.AppCompat.Widget.Switch">
        <item name="android:textSize">12sp</item>
        <item name="android:textColor">#3F51B5</item>
    </style>

layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    android:paddingBottom="12dp"
    android:paddingTop="12dp">

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/mySwitch"
        android:layout_width="match_parent"
        android:switchMinWidth="56dp"
        android:layout_height="wrap_content"
        android:switchTextAppearance="@style/SwitchTextAppearance"
        android:thumb="@drawable/thumb"
        android:track="@drawable/track"
        app:showText="true"
        android:textOn="ON"
        android:textOff="OFF"
        android:text="Toggle Switch"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:background="@android:color/transparent"
        android:button="@null"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"/>

</RelativeLayout>

A: Using SwitchCompat.setSwitchTextAppearance you can set the style for the text that appears inside the switch itself.
Add a style something like this and set it using setSwitchTextAppearance:
<style name="SwitchTextAppearance" parent="TextAppearance.AppCompat.Widget.Switch">
  <item name="android:textSize">12sp</item>
  <item name="android:textColor">#3F51B5</item>
</style>

And you should be able to customize the size, color, etc of your "OFF" text.


text:
Q: Is moving documents between collections a good way to represent state changes in MongoDB? I have two collections, one (A) containing items to be processed (relatively small) and one (B) with those already processed (fairly large, with extra result fields).
Items are read from A, get processed and save()'d to B, then remove()'d from A.
The rationale is that indices can be different across these, and that the "incoming" collection can be kept very small and fast this way.
I've run into two issues with this:

*

*if either remove() or save() time out or otherwise fail under load, I lose the item completely, or process it twice

*if both fail, the side effects happen but there is no record of that

I can sidestep the double-failure case with findAndModify locks (not needed otherwise, we have a process-level lock) but then we have stale lock issues and partial failures can still happen. There's no way to atomically remove+save to different collections, as far as I can tell (maybe by design?)
Is there a Best Practice for this situation?

A:
There's no way to atomically remove+save to different collections, as far as I can tell (maybe by design?)

Yes this is by design. MongoDB explicitly does not provides joins or transactions. Remove + Save is a form of transaction.

Is there a Best Practice for this situation?

You really have two low-complexity options here, both involve findAndModify.
Option #1: a single collection
Based on your description, you are basically building a queue with some extra features. If you leverage a single collection then you use findAndModify to update the status of each item as it is processing.
Unfortunately, that means you will lose this: ...that the "incoming" collection can be kept very small and fast this way.
Option #2: two collections
The other option is basically a two phase commit, leveraging findAndModify.
Take a look at the docs for this here.
Once an item is processed in A you set a field to flag it for deletion. You then copy that item over to B. Once copied to B you can then remove the item from A.

A: I've not tried this myself yet but the new book 50 Tips and Tricks for MongoDB Developers mentions a few times about using cron jobs (or services/scheduler) to clean up data like this. You could leave the documents in Collection A flagged for deletion and run daily job to clear them out, reducing the overall scope of the original transaction.
From what I've learned so far, I'd never leave the database in a state where I rely on the next database action succeeding unless it is the last action (journalling will resend the last db action upon recovery). For example, I have a three phase account registration process where I create a user in CollectionA and then add another related document to CollectionB. When I create the user I embed the details of the CollectionB document in CollectionA in case the second write fails. Later I will write a process that removes the embedded data from CollectionA if the document in CollectionB exists
Not having transactions does cause pain points like this, but I think in some cases there are new ways of thinking about it. In my case, time will tell as I progress with my app


text:
Q: KDB/Q building a stock market index I'm trying to build a stock index and I'm using Q for the purpose. As you can probably tell, I'm very new at this. Whereas I've built it in SQL, it takes way too long to process, hence my resorting to Q.
The setup so far is the following:

*

*The table; add data to the table, sort it:
tickers:`ibm`bac`dis`gs`ibm`gs`dis`bac
pxs:100 50 30 250 110 240 45 48
dates:2013.05.01 2013.01.05 2013.02.03 2013.02.11 2013.06.17 2013.06.21 2013.04.24 2013.01.06
sectors:`auto`money`funny`money`auto`money`funny`money
trades:([sectors;tickers;dates];pxs)
`sectors`dates`tickers xasc `trades

*The processing so far (thanks to other friendly SO users):

*

*I've calculated by how much has each stock price changes from the previous time the price was recorded
trades: update delta:{0,1_deltas x}pxs by tickers from trades

*I've calculated the total market value of the components of the sectorial index
trades: update idxmv:sums[?[delta<>0;delta;pxs]] by sectors from trades

*How it looks:
sectors tickers dates     | pxs delta idxmv
--------------------------| ---------------
auto    ibm     2013.05.01| 100 0     100
auto    ibm     2013.06.17| 110 10    110
funny   dis     2013.02.03| 30  0     30
funny   dis     2013.04.24| 45  15    45
money   bac     2013.01.05| 50  0     50
money   bac     2013.01.06| 48  -2    48
money   gs      2013.02.11| 250 0     298
money   gs      2013.06.21| 240 -10   288

*What I want to do:
I want compute a sector index, that changes when its components change; in order to do this I need to compute a divisor column and the actual index column. The logic I'm trying to implement is as follows:

*

*if delta != 0, then divisor = the last value of the divisor, in the same sector

*if delta != 0, then index = idxmv % the value of the divisor computed above

*if delta = 0, then index = the last value of the index, in the same sector

*if delta = 0, then divisor = idxmv % the value of the index computed above, where the initial value of the index is 100; all the sector have a starting value of the index of 100

So essentially, what I want to end up with, is something similar to the below:
    sectors tickers dates     | pxs delta idxmv divisor index
    --------------------------| ------------------------------
    auto    ibm     2013.05.01| 100 0     100   1       100
    auto    ibm     2013.06.17| 110 10    110   1       110
    funny   dis     2013.02.03| 30  0     30    0.30    100
    funny   dis     2013.04.24| 45  15    45    0.30    150
    money   bac     2013.01.05| 50  0     50    0.50    100
    money   bac     2013.01.06| 48  -2    48    0.50    96
    money   gs      2013.02.11| 250 0     298   3.10    96
    money   gs      2013.06.21| 240 -10   288   3.10    92.78

Thanks for your help,
Dan

A: trades1:update index:{100f,1_count[x]#0n}[delta] by sectors from trades; / starting value of index as 100
trades1:update divisor:?[delta=0;idxmv%index;0n] by sectors from trades1;  / divisor=y%z when delta=0
trades1:update divisor:?[delta<>0;fills divisor;divisor] by sectors from trades1; / divisor=last divisor when delta <> 0
trades1:update index:?[delta<>0;idxmv%divisor;index] by sectors from trades1; / index=i%d when delta <>0
trades1:update index:?[delta=0;fills index;index] by sectors from trades1 / index=last index when delta=0
trades1:update divisor:?[delta=0;idxmv%index;divisor] by sectors from trades1; /divisor=y%z when delta=0

This should solve your problem.
The last row doesn't seem to be matching.I have taken sectors as a primary key.You should be able to match the last row by changing the primary key to sectors/tickers.


text:
Q:  was not declared in this scope I'm trying to overload operator<< in C++ to use a recursive private method to get the content of a binary search tree as a string. I keep getting the "not declared in this scope" error despite checking the method signature for inconsistencies. I don't understand why the call to recursiveOutput() in operator<< causes this error.
operator<< definition:
friend std::ostream& operator<<(std::ostream&, const BinTree&);

recursive method definition:
void recursiveOutput(Node*, string&);

operator<< implementation:
std::ostream& operator<<(std::ostream& os, const BinTree& rhs)
{
    string result;
    recursiveOutput(rhs.root, result);
    os << result;
    return os;
}

The BinTree class has the private member "root" which is a pointer to the structure "Node".
EDIT: Example code
class BinTree
{
    public:
        friend std::ostream& operator<<(std::ostream&, const BinTree&);
    private:
        struct Node
        {
            string data;
            Node* left;
            Node* right;
        };

        Node* root;

        void recursiveOutput(Node*, string&);
};

std::ostream& operator<<(std::ostream& os, const BinTree& rhs)
{
    string result;
    rhs.recursiveOutput(rhs.root, result);
    os << result;
    return os;
}

void BinTree::recursiveOutput(Node* currentRoot, string& result)
{
    // if currentRoot is NULL return
    if (currentRoot == NULL)
    {
        return;
    }
    // traverse left branch
    recursiveOutput(currentRoot->left, result);
    // append string from NodeData
    std::ostringstream stream;
    stream << *currentRoot->data;
    result.append(stream.str());
    result.append(" ");
    // traverse right branch
    recursiveOutput(currentRoot->right, result);
}

EDIT: The reason this causes an error is because operator<< is not a member of BinTree, so it cannot call a member function without a BinTree object to call it.


text:
Q: How do I redirect different apps into a single domain with Nginx Ubuntu 16 I'm in charge of setting up a testing server in which all web applications should respond to a single domain, like this, for example:
dev.test.com/
What I want to do is to be able to pass the location of a different app and still be in the same domain, like so:
dev.test.com/thisapp
or
dev.test.com/differentapp
and I want to do it with Nginx, wich is the tool that I'm using. Problem is, I can only add them as diffent subdomains. I tried a few ways like putting all apps in one folder and trying to rename them all, with no luck. I have no idea how to achieve what I want and I already searched for weeks on end with nothing to help me achieve this. Some help would be greatly appreciated!

A: Use can use the location tag for that. Edit your configuration file under /etc/nginx/sites-enabled, and add a location tag for each sub-site
server {
    location / {
        root /path/to/default;
    }

    location /thisapp/ {
        root /path/to/thisapp;
    }

    location /differentapp/ {
        root /path/to/differentapp;
    }
}

You can read more in the nginx beginners guide


text:
Q: Sharepoint 2010 - Custom Ribbon i'm developing a sharepoint project and central admin pages (located in _layouts), and i want to use Ribbon bar.
i have found this sample but i hope so, it is wrong..
http://sharepointsolutions.com/sharepoint-help/blog/index.php/2009/10/creating-a-custom-ribbon-tab-in-sharepoint-2010/
page throw this error:
Ribbon  node must have a  subnode.
Element.xml have a  and  subnode, i don't found any error this file..
How can i add Ribbon to the custom page?
Do you have a suggestion?
Thanks,

A: please check out the
http://www.projectserver2010blog.com/2010/01/sharepoint-2010-ribbon-customization.html
and relative blog posts. There is a solution you are looking for.


text:
Q: GEF + EMF: Why doesn't my editor remove the Figure for a removed object when refreshChildren() is called? I have implemented a GEF editor for a graph-like EMF model, with a remove command for a certain type of node in the graph. I think I've done all the necessary steps in order to make this set up work (vainolo's blog has been a great help).
However, when I'm deleting a model element, the view doesn't get refreshed, i.e., the figure for the model element isn't removed from the editor view, and I have no idea why. I'd be extremely grateful if somebody could have a look at my sources and point me to any problems (and possibly solutions :)). Many thanks in advance!
Below are what I think are the important classes for this issue. Please do let me know should I add further code/edit the code, etc. (I've left out code that I thought doesn't help, e.g., getters and setters, class variables). Thanks!
DiagramEditPart
public class DiagramEditPart extends AbstractGraphicalEditPart {

    public DiagramEditPart(Diagram model) {
        this.setModel(model);
        adapter = new DiagramAdapter();
    }

    @Override protected IFigure createFigure() {
        Figure figure = new FreeformLayer();
        return figure;
      }

      @Override protected void createEditPolicies() {
        installEditPolicy(EditPolicy.LAYOUT_ROLE, new DiagramXYLayoutPolicy());
      }

      @Override protected List<EObject> getModelChildren() {
          List<EObject> allModelObjects = new ArrayList<EObject>();
          if (((Diagram) getModel()).getMyNodes() != null)
          allModelObjects.addAll(((Diagram) getModel()).getMyNodes());
          return allModelObjects;
      }

      @Override public void activate() {
          if(!isActive()) {
              ((Diagram) getModel()).eAdapters().add(adapter);
          }
          super.activate();
      }

      @Override public void deactivate() {
          if(isActive()) {
              ((Diagram) getModel()).eAdapters().remove(adapter);
          }
          super.deactivate();
      }

    public class DiagramAdapter implements Adapter {

          @Override public void notifyChanged(Notification notification) {
              switch (notification.getEventType()) {
            case Notification.REMOVE: refreshChildren();
                break;
            default:
                break;
            }
          }

          @Override public Notifier getTarget() {
              return (Diagram) getModel();
          }

          @Override public void setTarget(Notifier newTarget) {
              // Do nothing.
          }

          @Override public boolean isAdapterForType(Object type) {
              return type.equals(Diagram.class);
          }

      }

}

MyNodeEditPart
public class MyNodeEditPart extends AbstractGraphicalEditPart {

    public MyNodeEditPart(MyNode model) {
         this.setModel(model);
         adapter = new MyNodeAdapter();
    }

    @Override protected IFigure createFigure() {
        return new MyNodeFigure();
    }

    @Override protected void createEditPolicies() {
        installEditPolicy(EditPolicy.COMPONENT_ROLE, new MyNodeComponentEditPolicy());
    }

    @Override protected void refreshVisuals() {
        MyNodeFigure figure = (MyNodeFigure) getFigure();
        DiagramEditPart parent = (DiagramEditPart) getParent();
        Dimension labelSize = figure.getLabel().getPreferredSize();
        Rectangle layout = new Rectangle((getParent().getChildren().indexOf(this) * 50),
                (getParent().getChildren().indexOf(this) * 50), (labelSize.width + 20),
                (labelSize.height + 20));
        parent.setLayoutConstraint(this, figure, layout);
    }

    public List<Edge> getModelSourceConnections() {
        if ((MyNode) getModel() != null && ((MyNode) getModel()).getDiagram() != null) {
            ArrayList<Edge> sourceConnections = new ArrayList<Edge>();
            for (Edge edge : ((MyNode) getModel()).getDiagram().getOutEdges(((MyNode) getModel()).getId())) {
                sourceConnections.add(edge);
            }
            return sourceConnections;
        }
        return null;
    }

    // + the same method for targetconnections

    @Override public void activate() {
        if (!isActive()) {
            ((MyNode) getModel()).eAdapters().add(adapter);
        }
        super.activate();
    }

    @Override public void deactivate() {
        if (isActive()) {
            ((MyNode) getModel()).eAdapters().remove(adapter);
        }
        super.deactivate();
    }

    public class MyNodeAdapter implements Adapter {

        @Override
        public void notifyChanged(Notification notification) {
            refreshVisuals();
        }

        @Override
        public Notifier getTarget() {
            return (MyNode) getModel();
        }

        @Override
        public void setTarget(Notifier newTarget) {
            // Do nothing
        }

        @Override
        public boolean isAdapterForType(Object type) {
            return type.equals(MyNode.class);
        }

    }

}

MyNodeComponentEditPolicy
public class MyNodeComponentEditPolicy extends ComponentEditPolicy {

    @Override
    protected Command createDeleteCommand(GroupRequest deleteRequest) {
        DeleteMyNodeCommand nodeDeleteCommand = new DeleteMyNodeCommand((MyNode) getHost().getModel());
        return nodeDeleteCommand;
    }

}

DeleteMyNodeCommand
public class DeleteMyNodeCommand extends Command {

    public DeleteMyNodeCommand(MyNode model) {
        this.node = model;
        this.graph = node.getDiagram();
    }

    @Override public void execute() {
        getMyNode().setDiagram(null);
        System.out.println("Is the model still present in the graph? " + getGraph().getMyNodes().contains(getMyNode()));
            // Returns false, i.e., graph doesn't contain model object at this point!
    }

    @Override public void undo() {
        getMyNode().setDiagram(getGraph());
    }

}

EDIT
Re execc's comment: Yes, refreshChildren() is being called. I've tested this by overriding it and adding a simple System.err line, which is being displayed on the console on deletion of a node:
@Override
public void refreshChildren() {
    super.refreshChildren();
    System.err.println("refreshChildren() IS being called!");
}

EDIT 2
The funny (well...) thing is, when I close the editor and persist the model, then re-open the same file, the node isn't painted anymore, and is not present in the model. But what does this mean? Am I working on a stale model? Or is refreshing/getting the model children not working properly?

EDIT 3
I've just found a peculiar thing, which might explain the isues I have? In the getModelChildren() method I call allModelObjects.addAll(((Diagram) getModel()).getMyNodes());, and getMyNodes() returns an unmodifiable EList. I found out when I tried to do something along the lines of ((Diagram) getModel()).getMyNodes().remove(getMyNode()) in the delete command, and it threw an UnsupportedOperationException... Hm.

EDIT 4
Er, somebody kill me please?
I've double-checked whether I'm handling the same Diagram object at all times, and while doing this I stumbled across a very embarassing thing:
The getModelChildren() method in DiagramEditPart in the last version read approx. like this:
@Override protected List<EObject> getModelChildren() {
    List<EObject> allModelObjects = new ArrayList<EObject>();
    EList<MyNode> nodes = ((Diagram) getModel()).getMyNodes();
    for (MyNode node : nodes) {
        if (node.getDiagram() != null); // ### D'Uh! ###
            allModelObjects.add(node);
    }
    return allModelObjects;
 }

I'd like to apologize for stealing everyone's time! Your suggestions were very helpful, and indeed helped my to finally track down the bug!
I've also learned a number of lessons, amongst them: Always paste the original code, over-simplifaction may cloak your bugs! And I've learned a lot about EMF, Adapter, and GEF. Still:

A: There is one semi-colon too many in line 5 of the following part of the code, namely after the if statement: if (node.getDiagram() != null);:
1   @Override protected List<EObject> getModelChildren() {
2       List<EObject> allModelObjects = new ArrayList<EObject>();
3       EList<MyNode> nodes = ((Diagram) getModel()).getMyNodes();
4       for (MyNode node : nodes) {
5           if (node.getDiagram() != null);
6               allModelObjects.add(node);
7       }
8       return allModelObjects;
9    }


text:
Q: Preventing a project from being discovered as a test project I have for several project a common util project which consits of some base test classe, helper class and so on.
The project definition looks like this:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup Label="Globals">
    <SccProjectName>SAK</SccProjectName>
    <SccProvider>SAK</SccProvider>
    <SccAuxPath>SAK</SccAuxPath>
    <SccLocalPath>SAK</SccLocalPath>
  </PropertyGroup>

  <PropertyGroup>
    <TargetFrameworks>net461;netstandard2.0</TargetFrameworks>
    <RootNamespace>SomeRoot.Util</RootNamespace>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="FluentAssertions" Version="5.10.2" />
    <PackageReference Include="xunit" Version="2.4.1" />
  </ItemGroup>
</Project>

I assume that since it references xUnit, that both the visual studio and the dotnet test command treat it like a test project.
But since it isn't I would like to somehow prevent both the visual studio and dotnet test to not recognize this project as a test project.
Removing the reference to xUnit is not an option since the base classes needs some interfaces from the xUnit package.

A: Based on https://github.com/microsoft/vstest/issues/1129, there seems to be two things it checks for: IsTestProject property and ProjectCapability item of TestContainer. I remove both to be safe.
Add this to the project file:
  <PropertyGroup>
    <IsTestProject>false</IsTestProject>
  </PropertyGroup>

  <ItemGroup>
    <ProjectCapability Remove="TestContainer" />
  </ItemGroup>

This is the error that I was running into that is fixed by adding the above:
========== Starting test discovery ==========
Test project {ProjectName} does not reference any .NET NuGet adapter. Test discovery or execution might not work for this project.
It's recommended to reference NuGet test adapters in each test project in the solution.
Loaded 0 test records from the solution cache in 0.220 sec.
Microsoft.VisualStudio.TestPlatform.ObjectModel.TestPlatformException: Testhost process exited with error: Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.TestPlatform.CoreUtilities, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
File name: 'Microsoft.TestPlatform.CoreUtilities, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at Microsoft.VisualStudio.TestPlatform.TestHost.Program.Main(String[] args)
. Please check the diagnostic logs for more information.
   at Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyOperationManager.ThrowOnTestHostExited(Boolean testHostExited)
   at Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyOperationManager.SetupChannel(IEnumerable`1 sources, String runSettings)
   at Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyDiscoveryManager.DiscoverTests(DiscoveryCriteria discoveryCriteria, ITestDiscoveryEventsHandler2 eventHandler)


text:
Q: PL/SQL on SquirreL SQL Client 3.8.1 I am trying to execute a PL/SQL anonymous block with SQuirrel SQL:
BEGIN
    NULL;
END;
/

However, I get this error:
Error: ORA-06550: line 2, column 5:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:

   ;

SQLState:  65000
ErrorCode: 6550
Error occurred in:
begin
    NULL

I am using an Oracle 11g Express DB with the Oracle Thin Driver.
The reason for wanting to execute a PL/SQL block is so that I can create a table, and catch the exception caused if it already exists.
I have looked into similar questions such as https://stackoverflow.com/a/43265502 and https://stackoverflow.com/a/42287207 and others, but still cannot get SQuirrel to be happy with anonymous PL/SQL blocks. From what these other questions seem to say, it should be possible to use these blocks.
Why will this script not compile?


text:
Q: How to suspend a work item on the main queue I want to know if it is possible to suspend and then resume a work item on the main queue whilst maintaining the '.asyncAfter' time. If not, is there a workaround to achieve this?
At a certain point, I queue up the following DispatchWorkItem:
dispatchWorkItem = DispatchWorkItem(qos: .userInteractive, block: {
            self.view.backgroundColor = UIColor.workoutBackgroundColor
            self.runTimer()
            self.timerButton.animateableTrackLayer.removeAnimation(forKey: "strokeEndAnimation")
            self.isRestState = false
        })

I queue this up using:
    DispatchQueue.main.asyncAfter(deadline: delayTime, execute: self.dispatchWorkItem))

(delayTime being a parameter to the function)
Now, the problem I am running into is how can I suspend this work item if the user performs a 'pause' action in my app.
I have tried using the DispatchQueue.main.suspend() method but the work item continues to execute after the specified delay time. From what I have read, this method should suspend the queue and this queued work item since it is not being executed. (Please correct me if I am wrong there!)
What I need to achieve is the work item is 'paused' until the user performs the 'resume' action in the app which will resume the work item from where the delay time left off.
This works on background queues that I have created when I do not need to make UI updates; however, on the main queue is appears to falter.
One workaround I have considered is when the user performs the pause action, storing the time left until the work item was going to be executed and re-adding the work item to the queue with that time on the resume action. This seems like a poor quality approach and I feel there is a more appropriate method to this.
On that, is it possible to create a background queue that on execution, executes a work item on the main queue?
Thanks in advance!

A:
On that, is it possible to create a background queue that on execution, executes a work item on the main queue?

You are suggesting something like this:
var q = DispatchQueue(label: "myqueue")
func configAndStart(seconds:TimeInterval, handler:@escaping ()->Void) {
    self.q.asyncAfter(deadline: .now() + seconds, execute: {
        DispatchQueue.main.async(execute: handler())
    })
}
func pause() {
    self.q.suspend()
}
func resume() {
    self.q.resume()
}

But my actual tests seem to show that that won't work as you desire; the countdown doesn't resume from where it was suspended.

One workaround I have considered is when the user performs the pause action, storing the time left until the work item was going to be executed and re-adding the work item to the queue with that time on the resume action. This seems like a poor quality approach and I feel there is a more appropriate method to this.

It isn't poor quality. There is no built-in mechanism for pausing a dispatch timer countdown, or for introspecting the timer, so if you want to do the whole thing on the main queue your only recourse is just what you said: maintain your own timer and the necessary state variables. Here is a rather silly mockup I hobbled together:
class PausableTimer {
    var t : DispatchSourceTimer!
    var d : Date!
    var orig : TimeInterval = 0
    var diff : TimeInterval = 0
    var f : (()->Void)!
    func configAndStart(seconds:TimeInterval, handler:@escaping ()->Void) {
        orig = seconds
        f = handler
        t = DispatchSource.makeTimerSource()
        t.schedule(deadline: DispatchTime.now()+orig, repeating: .never)
        t.setEventHandler(handler: f)
        d = Date()
        t.resume()
    }
    func pause() {
        t.cancel()
        diff = Date().timeIntervalSince(d)
    }
    func resume() {
        orig = orig-diff
        t = DispatchSource.makeTimerSource()
        t.schedule(deadline: DispatchTime.now()+orig, repeating: .never)
        t.setEventHandler(handler: f)
        t.resume()
    }
}

That worked in my crude testing, and seems to be interruptible (pausable) as desired, but don't quote me; I didn't spend much time on it. The details are left as an exercise for the reader!


text:
Q: QFileDialog - create files without an extension I'd like to use the QFileDialog to get the name of a new directory, where I will create several configuration files.
It will be nice if a directory name will not contain an extension part. How can I force a user, to do not provide the QFileDialog with filename.extension?
I tried to use the following code:
QString fileName =
    QFileDialog::getSaveFileName(this, tr("create a directory),
                                QDir::homePath(), tr("Directories (*)"));

But obviously it allows user to input any filename with or without an extension. Any other ideas?

A: You can use QFileDialog::GetExistingDirectory
QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"), QDir::homePath(),
                                                QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

See the QFileDialog Documentation.


text: Q: How can I run John Walker's ent program effectively on some data streams? So the original ent program can be found here. The website doesn't give me a sufficient explanation, so I ask, how can I use this program effectively on Windows?


text:
Q: WinForms (.NET Framework) doesn't seem to notice DPI sessions between RDP sessions It seems that, in the following scenario, Windows Forms won't notice a DPI change without a restart of the app:

*

*connect to an RDP session

*launch the app

*disconnect; reconnect, but with a different DPI setting in the RDP client

This seems to be because in such a scenario, Windows never sends WM_DPICHANGED (as of Windows 11 22000.194, anyway), and that seems to be the only way Windows Forms notices changes.
Windows does send WM_DISPLAYCHANGE, though, which includes the new DPI.
From decompiling WinForms, it seems I could listen to that message and construct my own DpiChangedEventArgs to have controls notice the change.
Before I endeavour on that,

*

*can someone confirm this behavior? There are probably other scenarios it applies to? (i.e., a display gets disconnected, then on reconnect has a different DPI, and WinForms doesn't notice as a result)

*is there a nicer fix I'm missing, other than to send the event myself?


text:
Q: bigQuery - how to use row values to create columns for a new table I have the following genomic table (over 12K rows) in BigQuery. A long list of the PIK3CA_features (column 2) are related to the same sample_id (column 1)
Row sample_id   PIK3CA_features
1   hu011C57    chr3_3930069__TGT
2   hu011C57    chr3_3929921_TC
3   hu011C57    chr3_3929739_TC
4   hu011C57    chr3_3929813__T
5   hu011C57    chr3_3929897_GA
6   hu011C57    chr3_3929977_TC
7   hu011C57    chr3_3929783_TC

I would like to generate the following table:
Row sample_id   chr3_3930069__TGT   chr3_3929921_TC chr3_3929739_TC
1   hu011C57    1                   1               0
2   hu011C58    0

Meaning, one row for every sample ID and a 1/0 if the PIK3CA_feature exist at this sample.
Any idea how to easily generate this table?
Many thanks for any idea!

A: The only idea that comes to mind is using the concepts of ARRAYS and STRUCTS to get somewhat close to what you need, like so:
WITH data AS(
SELECT 'hu011C57' sample_id, 'chr3_3930069__TGT' PIK3CA_features union all
SELECT 'hu011C57', 'chr3_3929921_TC' union all
SELECT 'hu011C57', 'chr3_3929739_TC' union all
SELECT 'hu011C57', 'chr3_3929813__T' union all
SELECT 'hu011C57', 'chr3_3929897_GA' union all
SELECT 'hu011C57', 'chr3_3929977_TC' union all
SELECT 'hu011C57', 'chr3_3929783_TC' union all
SELECT 'hu011C58', 'chr3_3929783_TC' union all
SELECT 'hu011C58', 'chr3_3929921_TC'
),

all_features AS (
  SELECT DISTINCT PIK3CA_features FROM data
),

aggregated_samples AS(
  SELECT
    sample_id,
    ARRAY_AGG(DISTINCT PIK3CA_features) features
FROM data
GROUP BY sample_id
)

SELECT
  sample_id,
  ARRAY(SELECT AS STRUCT PIK3CA_features, PIK3CA_features IN (SELECT feature FROM UNNEST(features) feature) FROM all_features AS present ORDER BY PIK3CA_features) features
FROM aggregated_samples

This will return for you one row per sample_id and a correspondent array of structs with each feature and its presence in the sample_id.
As BigQuery natively supports this type of data structure maybe you could have this representation for your data without losing any capacity for advanced analyzes such as using analytical functions, subqueries and so on.

A: You can accomplish this by grouping on the sample id.
SELECT
    sample_id,
    COUNTIF(PIK3CA_features = 'chr3_3930069__TGT') as chr3_3930069__TGT,
    COUNTIF(PIK3CA_features = 'chr3_3929921_TC') as chr3_3929921_TC,
    COUNTIF(PIK3CA_features = 'chr3_3929739_TC') as chr3_3929739_TC
FROM [your_table]
GROUP BY sample_id;

Assuming you have no duplicate PIK3CA_features per sample id, this should give you what you need.


text:
Q: Getting jQuery unrecognized expression error I have an HTML template that contains a jQuery function that executes an Ajax request to my web server.  The data in the response contains strings with car brand names and numbers which are used to set the value in an input checkbox for each particular car brand.  Here's an example from the template:
<input type="checkbox" name="list" value="2">
<label for="brand">Mercedes</label>

I'm trying to use the following jQuery code to see if the input checkbox is checked for each car brand.  index.name is a string and contains the car brand (e.g. "Mercedes") and index.id contains the value 2 which is a JavaScript number type (I confirmed this in the console):
$.each(data, function(key, index) {
    if ( $('input[type=checkbox][value=index.id]').prop('checked', true) ) {
        console.log("Checkbox is checked");
    }
});

When I run the jQuery code, I'm getting this error:
    Uncaught Error: Syntax error, unrecognized expression: input[type=checkbox][value=index.id]

Can anyone tell me what I'm doing wrong?  I've read other Stackoverflow questions on how to do this and what I'm doing appears to be correct.

A: You need to quote the parameter to an attribute selector if it contains any special characters (in this case, the . character):
 $('input[type=checkbox][value="index.id"]')

However, this will looks for a checkbox whose value is the literal string index.id. If you're actually trying to use the value of the expression index.id, neither way will do it, since variables aren't expanded inside strings. You need to concatenate:
$('input[type=checkbox][value="' + index.id+ '"]')

or use an ES6 template literal:
$(`input[type=checkbox][value="${index.id}"]`)


text:
Q: Clarify or disambiguate notation from textbook I'm reading Murphy's Machine Learning: A probabilistic perspective. Exercise 2.9 asks:
Exercise 2.9
Conditional independence
Are the following properties true? Prove or disprove. Note that we are not restricting attention to distributions that can be represented by a graphical model.

*

*True or false?
$$
(X \perp W \mid Z, Y)\wedge (X \perp Y \mid Z) \implies (X \perp Y, W \mid Z)
$$
where $(A \perp B \mid C)$ means
$$
p(A, B \mid C) = p(A \mid C) p(B \mid C)
$$

I need clarification on how to parse
$$
(X \perp Y, W \mid Z)
$$
Does this mean that
$$
p(X, Y, W \mid Z) = p(X \mid Z)p(Y, W \mid Z)
$$


text:
Q: Google Chrome notifications don't show I want send notification by Google Chrome Extension
Manifest
{
  "name": "Test",
  "description": "Test",
  "version": "1.1",
  "background": {
    "scripts": ["background.js"]
  },
  "permissions": [
    "tabs", "http://*/*", "https://*/*",
    "notifications"
  ],
  "browser_action": {
      "default_title": "Test",
      "default_icon": "test_16x16.png"
  },
  "manifest_version": 2
}

background.js
chrome.browserAction.onClicked.addListener(function() {
chrome.notifications.create(
    'name-for-notification',{
    type: 'basic',
    iconUrl: 'image.jpeg',
    title: "This is a notification",
    message: "hello there!"
    },

function() {}

);
});]

Why doesn't it work?


text:
Q: Php Simple Html - How to convert the DOM to an Element I'm using  PHP Simple HTML DOM Parser library in my project, but I can't figure out how to make a method working.
First I convert a string into a DOM object:
$html = str_get_html($rarr[$i]);

the $rarr variable is an array of html string elements. I want to remove their class and title attributes, so I use the following code:
$html = $html->removeAttribute('class');
$html = $html->removeAttribute('title');

but I get the following error:

Fatal error: Call to undefined method simple_html_dom::removeAttribute() in /scripts/defios.php on line 198

According to Documentation, the str_get_html() Creates a DOM object from a string. and I think the removeAttribute() method is not a DOM method but an Element method and that's why I get the error. So I need to convert somehow the DOM to Element. I think the find() method would do the job, but the problem is that I can't use it because the html elements in the array are randomly (some are divs, spans and they don't have a common class or id), so the method doesn't really help me. More the DOM itself is the element so I do not want to select something inside the DOM but to convert the entire DOM to an Element.
All I need to do is to remove that class and title, so any help would be appreciated.

A: Here's how I would remove those:
foreach($html->find('[class]') as $el) $el->removeAttribute('class');
foreach($html->find('[title]') as $el) $el->removeAttribute('title');

A: The key is to access the children attribute: Take a look at the following example and tweak it to work!
    $html = str_get_html($rarr[$i]);
    foreach($html as $e)
    {
        $tag = $e->children[0]; // get the outer most element
        $tag->removeAttribute('class');
        $tag->removeAttribute('title');
    }


text:
Q: Отобразить в случайном порядке слова без дубликатов import random
WORDS=str(["слово","слово2","слово3","слово"])
word=random.choice(WORDS)
list=""
# while list in range(len(WORDS)):
#   word=random.choice(WORDS)
#   if word != list:
#       list+=word+" "
#
# print(list)
# input("\nНажмите клавишу для выхода")

# for i in WORDS:
#   if i != list
#       list+=i

while WORDS != "":
    word=str(random.choice(WORDS))
    if word != list:
        list+=word
        del WORDS[word]
print(list)

http://s020.radikal.ru/i722/1406/a7/52fb8723f829.png - скриншот
Уже почти все перепробовал, что вспомнил.
Вывод в этом примере должен быть: слово слово2 слово3
A: Ничего не понял из вашего вопроса.
Но если вам нужно отобразить в случайном порядке слова без дубликатов:
import random

words = ['word', 'word1', 'word2', 'word']
unique_words = list(set(words))
random.shuffle(unique_words)
print unique_words


text:
Q: Adding small arrow under current page in WordPress with CSS I have a menu that has one gradient type for default state, and one for the hover/active state. The current page is just like the hover/active state, but with an arrow under it. I can't figure out the best way to get that arrow to show up. I tried a border image, but that didn't look right since the button size is different depending on the length of the menu item. Here is the current CSS I am using to create the two different styles:
.main-nav li a {
    float: left;
    font-size: 15px;
    color: #333;
    padding: 10px 15px;
    text-shadow: 1px 1px #DDD;
    border-right: 1px solid rgba(0, 0, 0, .3);
    border-left: 1px solid rgba(255, 255, 255, .5);
    background-image: -webkit-gradient(
        linear,
        left top,
        left bottom,
        color-stop(0.0, #B3D09E),
        color-stop(0.75, #A0B88E)
    );
    background-image: -o-linear-gradient(bottom, #B3D09E 0%, #A0B88E 75%);
    background-image: -moz-linear-gradient(bottom, #B3D09E 0%, #A0B88E 75%);
    background-image: -webkit-linear-gradient(bottom, #B3D09E 0%, #A0B88E 75%);
    background-image: -ms-linear-gradient(bottom, #B3D09E 0%, #A0B88E 75%);
    background-image: linear-gradient(to bottom, #B3D09E 0%, #A0B88E 75%);
    transition: all 300ms;
    -moz-transition: all 300ms;
    -o-transition: all 300ms;
    -webkit-transition: all 300ms;
}
.main-nav .current-menu-item a, .main-nav .current-page-ancestor a, .main-nav li a:hover {
    color: #FFF;
    background-image: -webkit-gradient(
        linear,
        left top,
        left bottom,
        color-stop(0, #043420),
        color-stop(1, #075A36)
    );
    text-shadow: none;
    background-image: -o-linear-gradient(bottom, #043420 0%, #075A36 100%);
    background-image: -moz-linear-gradient(bottom, #043420 0%, #075A36 100%);
    background-image: -webkit-linear-gradient(bottom, #043420 0%, #075A36 100%);
    background-image: -ms-linear-gradient(bottom, #043420 0%, #075A36 100%);
    background-image: linear-gradient(to bottom, #043420 0%, #075A36 100%);
}

I would like to avoid using jquery if I can. I feel like there should be some way to do this using just CSS instead of placing an image in the center of the button with jquery. Do I place an invisible div under each button with the arrow image centered and display it on the current page?
This is what I was given to follow for my menu. They didn't use quite the correct terminology. The 'Active' part of the image is the Current Page style:

A: You can use pseudo elements in CSS to add content, like ::after. By using the border property with different widths and colors you get a triangle shape. The only thing that can be a bit tricky is if you need the gradient to continue on to the arrow.
I put together a small demo. Hover the links in the menu to see the arrow.
DEMO
li:hover::after {
    content: ' ';
    position: absolute;
    border: solid 10px transparent;
    border-top: solid 0px transparent;
    border-width: 10px;
    left: 50%;
    margin-left: -10px;
    border-color: #222 transparent transparent transparent;
}


text:
Q: SQL to Zend Framework I am trying to convert my SQL statement to a query statement in Zend Framework
SELECT COUNT( FechaCita ) AS Num_de_Citas, FechaCita FROM cita WHERE idEspecialista = 13018 GROUP BY FechaCita

any ideas?

A:     $select = $this->select()
                    ->from('cita', array('COUNT( FechaCita ) AS Num_de_Citas'), 'FechaCita' )
                    ->where('idEspecialista = ?',13018)
                    ->group('FechaCita');
    $this->fetchRow($select);

This is the query for Zend 1.12.
Please read this SO manual before posting a question How do I ask a good question?

A: I resolved with fetchAll
I post my solution
PHP code:
$select = $db   ->select()
                ->from(array('c'=>'cita'), array('numCitas' => 'COUNT(*)', 'FechaCita', 'idEspecialista'))
                ->where('c.idEspecialista = ?',$_GET['idEspSelect'])
                ->group('c.FechaCita');
$stmt = $select->query();
$result = $stmt->fetchAll();


text:
Q: How to count with letters instead of numbers What I want to do is count with a certain number of letters. the inputs will be n and x, where n is the number of letters to be used and x is the number I'm trying to count to. Say n is 3 and x is 12. It would go like this: 'a', 'b', 'aa', 'ab', 'ba', 'bb', 'aaa', 'aab', 'aba', 'abb', 'baa', 'bab'. 'bab' is 12 when using 2 numbers to count. I know there is a mathematical way to do this, but I can't figure it out. Another test case is n = 16 and x = 248832. It would return 'clkop'. I'm sorry if someone has asked something like this before, I couldn't find anything. Also, let me know if this belongs on a different website. For clarity, the number of letters can range from 1 to 26. if it is 1, then 8 would be expressed as 'aaaaaaaa'. If the number of letters is 2, 8 would be expressed as 'aab'. If it is 3, then 17 would be expressed as 'abc' etc. I thought that it would be as simple as converting to base n, but it isn't. Hopefully, that helps. When I was writing this question, I saw a similar one that was in javascript, but it only did all 26 letters. I don't know how to convert javascript code into python code, and I want to be able to do any number of letters from 1-26. I know there is also a way to brute force this, but I don't know how
Let me know if the question needs more clarification
Edit: I figured out how to convert the string of letters into a number given the number of letters. For 16 letters, clkop = 3 * (16^4) + 12 * (16^3) + 11 * (16^2) + 15 * 16 + 16 = 248832 (or for an x length where v = the value of the current letter when iterating through the string, and n = number of letters, v * (n^x-1) + v * (n^x-2)... + v. Hopefully there is something you can do with that.

A: You're basically asking how to convert a number into a different base, with the letters being the possible digits:
import string
namespace = string.ascii_lowercase
def convert(base, num):
  result = []
  while num:
    num -= 1
    num, mod = divmod(num, base)
    result.append(namespace[mod])
  return "".join(reversed(result))

A: from string import ascii_lowercase

def alphabetic_counter(n, x):
    letterNums = [0]
    for i in range(x):
        yield ''.join(reversed([ascii_lowercase[l] for l in letterNums]))
        letterNums[0] += 1
        currIdx = 0
        while letterNums[currIdx] == n:
            if currIdx == len(letterNums) - 1:
                letterNums[currIdx] = 0
                letterNums.append(0)
            else:
                letterNums[currIdx] = 0
                currIdx += 1
                letterNums[currIdx] += 1

print(list(alphabetic_counter(2,12)))

Output:
['a', 'b', 'aa', 'ab', 'ba', 'bb', 'aaa', 'aab', 'aba', 'abb', 'baa', 'bab']

Not the prettiest solution, I have to admit, but either I have bad day for this sort of tasks or it is much harder than it looks on the first glance.

A: With n different letters, we can form

different words of length at most k.
Solving for y yields that the yth word has length
.
If we start our count with 0 and the empty word '',  counting to x requires x+1 different words.
from math import log as ln
from math import ceil
from itertools import  chain, product

def xth_word(x, n):
    '''returns  the xth word over the alphabet consisting of
       the first n lowercase letters
       The empty word '' is the 0th word
    '''
    letters = [chr(97 + i) for i in range(n)]
    word_length = ceil(ln((x + 1) * (n - 1) + 1) / ln(n))
    it = chain.from_iterable((product(letters, repeat=i)\
                              for i in range(word_length)))
    word = next(w for i,w in enumerate(it) if i == x)
    return ''.join(word)

print([xth_word(i, 2) for  i in range(13)])
print(xth_word(248832, 16))

Output:
['', 'a', 'b', 'aa', 'ab', 'ba', 'bb', 'aaa', 'aab', 'aba', 'abb', 'baa', 'bab']
clkop