text:
Q: MySQL Join Tables with Multiple Duplicate Values in Join Columns Constraints

*

*Tables are de-normalized

*Cannot use sub-query

Tables
Name: Locations
+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| id        | int(11)     | NO   | PRI | 0       | auto_increment |
| zip_code  | varchar(12) | NO   |     |         |                |
| city      | varchar(64) | NO   | MUL |         |                |
| county    | varchar(64) | NO   | MUL |         |                |
| state     | varchar(64) | NO   | MUL |         |                |
| info      | varchar(99) | NO   |     |         |                |
+-----------+-------------+------+-----+---------+----------------+

Name: Addresses
+------------------+---------------+------+-----+-------+-----------+
| Field            | Type          | Null | Key | Default   | Extra |
+------------------+---------------+------+-----+-----------+-------+
| id               | int(11)       | NO   | PRI | 0         |       |
| address_one      | varchar(255)  | NO   |     |           |       |
| address_two      | varchar(255)  | NO   |     |           |       |
| city             | varchar(30)   | NO   | MUL |           |       |
| state            | varchar(25)   | NO   | MUL |           |       |
| zip_code         | varchar(7)    | NO   | MUL | NULL      |       |
| country_code     | char(2)       | YES  |     |           |       |
+------------------+---------------+------+-----+-----------+-------+

The Problem

*

*Tables Locations and Addresses will have state duplicated across many rows.

*Locations table has around 100k rows and the Addresses table has about 1M rows.

The Question
I need to get a unique list of states with their info from the Locations table where there is at least one address in the Addresses table for any the respective state.
Any join I have, without using sub-queries, ends up taking forever.
What query will satisfy the Constraints?

A: It is a myth that subqueries are a performance problem. Sometimes they are; sometimes they are not.  There is no such simple rule.
In your case, I might suggest:
select l.*
from (select distinct state, info
      from locations l
     ) l
where exists (select 1
              from addresses a
              where a.state = l.state
             );

For performance, you want indexes on locations(state, info) and addresses(state).
There are two subqueries, but with appropriate indexes, this may just be the fastest way to express this logic.

A: You could use:
SELECT state, info FROM locations LEFT JOIN addresses USING (state) WHERE address_one IS NOT NULL GROUP BY state;

That query does not use a subquery.


text:
Q: Reverse DNS PTR entries matching to MX entries Confusion over what reverse DNS applies to and where it gets set...  Although there are answers on how to do this, I still cannot determine what needs to get done and why.
A domain is registered at Registrar A, which holds the DNS tables.
Registrar A also serves up mail services via the Registrar's owned domain.
Two VPS serve different 3rd level domain services.
The spf record in DNS table points to the domain of the mail server for MX services, while the MX record points to
mail.registeredDomain.com

v=spf1 a mx ptr include:mailServer.net ~all

MX toolbox states Reverse DNS does not match SMTP Banner
are reverse DNS lookups based on the service (mx) or the domain?
I can see the mismatch with MX record, but the mail provider had instructions to set up PTR record as stated.
How should the SPF PTR record be set? and why?

A: No, the Reverse DNS records does not have anything to do with Your domain records
Lets say your domain is company.com. You have SOA, NS, MX, A and TXT -SPF records defined, pointing to an IP address of Yours.
The reverse zones for an IP address works like any other domain name lookup, but are located in domain suffix .in-addr.arpa . The domain delegation for sub domains under "in-addr.arpa" is not to be mixed up with the .com, .net  etc.
Normally the "owners" of a subdomain to in-addr.arpa is the ISP owning the address space. So to get a correct DNS reverse lookup for "your" IP-address, you must ask your ISP to set it, or ask that you  get an delagation for your subnet and add it to your own public dns.
And for your SPF PTR question, see open SPF syntax guide

If at all possible, you should avoid using this mechanism in your SPF record, because it will result in a larger number of expensive DNS lookups.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Big O complexity of creating a recursive ternary tree with k width I want to know the complexity of my algorithm.
I'm trying to optimize the profit of buying stocks at every leaf of a tree from a list of prices. For every price we can do 3 options, buy one unit, sell one unit or do nothing. There is a constraint which bounds the amount of stocks we can have at a time, like 0 stocks min and 5 stocks max so if we have a list of 20 prices, which actions should I take to maximize the profit and end with 3 stocks.
For this task I created this recursive method:
    def _next_price_unit(self, load, prices, money=0, depth=0):
"""Recursive dynamic programming step
            Tree load has a depth index where the max depth is the length of the
            prices array while load index is the level of current stocks.The
            tree load will return the best revenue at that depth and stock load."""

        if len(prices) is depth:  # Max depth, stop condition
            return
        if self.tree_load[depth][load] < money:  # No change in load
            self.tree_load[depth][load] = money
            self._next_price_unit(load, prices, money, depth + 1)

         #Check load in stock boundaries and money increases at -1 or +1 load
        if load - 1 >= self.stock_min\
                and money + prices[depth] > self.tree_load[depth][load - 1]:
            self.tree_load[depth][load - 1] = money + prices[depth]  # Sell
            self._next_price_unit(load - 1, prices, money + prices[depth],
                                  depth + 1)

        if load+1 <= self.stock_max\
                and money - prices[depth] > self.tree_load[depth][load+1]:
            self.tree_load[depth][load + 1] = money - prices[depth]  # Buy
            self._next_price_unit(load + 1, prices, money - prices[depth],
                                  depth + 1)

Without the constraint of min and max stock I know the complexity of a ternary tree would be O(3^n) and I know this could be solved in O(k*n) if I use dynamic programming comparing the values at each level of depth and then going forward.
This algorithm will go all the way to the depth end, then backwards, forwards,backwards backwards and so on.
Can someone tell me what is the complexity? I cant get my head around it.


text:
Q: No respeta valores de mi Base de Datos Tengo un problema esta es una parte de mi formulario para editar, en mi código utilizo select para realizar un catalogo pero a la hora de editar cualquier campo y guardarlo toma la primera opción del select. ¿Como le hago para que respete los datos del select que previamente se habían ingresado y al guardar respete esos campos?

 Administración de equipos registrados

Edición de equipos

    <?php
    extract($_GET);
    require("connect_db.php");

    $sql="SELECT * FROM equipos WHERE ID=$ID";
//la variable  $mysqli viene de connect_db que lo traigo con el require("connect_db.php");
    $ressql=mysqli_query($mysqli,$sql);
    while ($row=mysqli_fetch_row ($ressql)){
            $ID=$row[0];
            $etiqueta_equipo=$row[1];
            $departamento=$row[2];
            $id_estatus=$row[3];
            $id_tipo_equipo=$row[4];
            $id_estado_equipo=$row[5];
            $observaciones=$row[6];
            $marca=$row[7];
            $modelo=$row[8];
            $caracteristicas=$row[9];
            $ip_equipo=$row[10];
            $identificador=$row[11];
        }

    ?>

    <form action="ejecutaactualizar_equipos.php" method="post">
            Id
<input type="text" name="ID" value= "<?php echo $ID?>" readonly="readonly">

            Etiqueta del equipo
 <input type="text" name="etiqueta_equipo" value="<?php echo $etiqueta_equipo?>">

            Departamento
 <input type="text" name="departamento" value="<?php echo $departamento?>">

            Estatus
 <select   name="id_estatus" value="<?php echo $id_estatus?>">
            <option value="Entregado">Entregado</option>
             <option value="Pendiente">Pendiente</option>
              <option value="Resguardo">Resguardo</option>
               <option value="Baja">Baja</option>
                </select>

            Tipo del Equipo
 <select  name="id_tipo_equipo" value="<?php echo $id_tipo_equipo?>">
             <option value="CPU">CPU</option>
              <option value="Monitor">Monitor</option>
               <option value="Impresora">Impresora</option>
                <option value="Scanner">Scanner</option>
                 <option value="Reulador">Regulador</option>
                  <option value="Teclado">Teclado</option>
                   <option value="Mouse">Mouse</option>
                    </select>

            Estado del Equipo
 <select  name="id_estado_equipo" value="<?php echo $id_estado_equipo?>">
             <option value="Bueno">Bueno</option>
              <option value="Regular">Regular</option>
               <option value="Malo">Malo</option>
                </select>

            Observaciones
 <input type="text" name="observaciones" value="<?php echo $observaciones?>">

            Marca
 <input type="text" name="marca" value="<?php echo $marca?>">

            Modelo
 <input type="text" name="modelo" value="<?php echo $modelo?>">

            Caracteristicas
 <input type="text" name="caracteristicas" value="<?php echo $caracteristicas?>">

            IP del Equipo
 <input type="text" name="ip_equipo" value="<?php echo $ip_equipo?>">

            identificador

                    <?php
               require("connect_db.php");

              $query = "SELECT DISTINCT id_usuarios, identificador FROM usuarios";
              $res = $mysqli->query($query);
              $option = '';
                 while ($row = $res->fetch_assoc())
                 {

                      $option.="<option value=\"$row[identificador]\">$row[identificador] </option>";
                 }
           ?>

               <select name="identificador">
                  <?php echo $option; ?>
                    </select>

            <input type="submit" value="Guardar" class="btn btn-success btn-primary">
        </form>

A: Estás definiendo mal el valor "por defecto" del select. Este es tu código:
<select name="id_estatus" value="<?php echo $id_estatus?>">

El tag select no tiene una propiedad value (ver https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select).
Para preseleccionar el valor, te conviene iterar cada una de las options y compararla con el valor guardado. Mi sugerencia para tu primer select:
<?php $options = ['Entregado', 'Pendiente', 'Resguardo', 'Baja']; ?>

<select name="id_estatus">
    <?php foreach ($options as $option): ?>
         <?php $selected = ($option == $id_estatus) ? 'selected' : '' ?>
         <option value="<?= $option ?>" <?= $selected ?>><?= $option ?></option>
    <?php endforeach; ?>
</select>


text:
Q: Why can I build this package (aspectC) in Ubuntu, but not Cygwin? I'm trying to get started with this library and following the directions on that page, Cygwin returns this, despite the project's page claiming to support Cygwin.
The Makefile works just fine in a fresh Ubuntu VM, and I've run Cygwin's setup.exe to include Devel, Interpreters, Perl, etc. which I thought may have fixed a broken dependency, but it won't build after installing all of the relevant packages.
Has anyone run into an issue like this before? Do you have any advice?
Update: The previous output was the result of me trying 0.8. I re-ran the 0.9RC Makefile and the problem seems to be:
/usr/local/bin/ACC/src/.acc_dir/matchaa_ac.c:63:1: error: expected specifier-qualifier-list before '__ac__type__insert'
/usr/local/bin/ACC/src/.acc_dir/matchaa_ac.c:63:1: error: stray '@' in program

I can't think of why Cygwin is choking on the '@' character. Google is useless because it doesn't parse special characters.

A: The first error is:
/usr/local/bin/ACC/src/.acc_dir/matchinfo_ac.c:180:39: error: expected specifier-qualifier-list before 'PointcutType'

I would take a look at line 180 character 39 of matchinfo_ac.c for clues as to what is different between your two build environments.  Since the error is output by tacc, perhaps you need a later version of tacc to build tacc?  Syntax changes?  From v0.9 RC (note it is a development version)
struct _IO_FILE_plus ;

but be certain to check your own copy.  Anyways, this line doesn't have 39 characters.
Good luck.


text:
Q: Custom delete button for UITextField on iPad I am making an iPad app that has a key board with extra large buttons fixed on the screen at all times.  The outputted text is being displayed into a Text Field and everything works fine except the delete button I have created.  I originally set the text to be displayed in a text view and the delete button worked fine, but when I changed it into a text field it stopped working unless the apple keyboard is on the screen.  Here is the code I am using for the delete button
- (IBAction)del:(id)sender
{

    [textField deleteBackward];

}

My question is how do I get my delete button to work in the text field?

A: I think a hint to this issue may be in the documentation for deleteBackward which says:

Remove the character just before the cursor from your class's backing
  store and redisplay the text.

If the keyboard is not on screen (and the textfield is not the first responder), then there is no cursor so that might be why it doesn't work. If all you want to do is delete the last character you could just do it manually by doing something like this:
- (IBAction)del:(id)sender
{
  textField.text = [textField.text substringToIndex:textField.text.length - 1];
}


text:
Q: Is MSP430 internal flash write working well I am working on MSP430 and processing internal flash.
I have a doubt with MSP430 flash write lib.
In my opinion, with this implementation, the last byte might not be written in some cases.
This is function implementation.
void FlashCtl_write8(uint8_t *data_ptr,uint8_t *flash_ptr,uint16_t count){
//Clear Lock bit
HWREG16(FLASH_BASE + OFS_FCTL3) = FWKEY;

//Enable byte/word write mode
HWREG16(FLASH_BASE + OFS_FCTL1) = FWKEY + WRT;

while(count > 0)
{
    //test busy
    while(HWREG8(FLASH_BASE + OFS_FCTL3) & BUSY)
    {
        ;
    }

    //Write to Flash
    *flash_ptr++ = *data_ptr++;
    count--;
}

//Clear WRT bit
HWREG16(FLASH_BASE + OFS_FCTL1) = FWKEY;

//Set LOCK bit
HWREG16(FLASH_BASE + OFS_FCTL3) = FWKEY + LOCK;

}
Is it a better solution if the function is implemented as below :
void FlashCtl_write8(uint8_t *data_ptr,uint8_t *flash_ptr,uint16_t count){
//Clear Lock bit
HWREG16(FLASH_BASE + OFS_FCTL3) = FWKEY;

//Enable byte/word write mode
HWREG16(FLASH_BASE + OFS_FCTL1) = FWKEY + WRT;

//test busy
while(HWREG8(FLASH_BASE + OFS_FCTL3) & BUSY)
{
  ;
}
while(count > 0)
{
    //Write to Flash
    *flash_ptr++ = *data_ptr++;
    while(HWREG8(FLASH_BASE + OFS_FCTL3) & BUSY)
    {
      ;
    }
    count--;
}

//Clear WRT bit
HWREG16(FLASH_BASE + OFS_FCTL1) = FWKEY;

//Set LOCK bit
HWREG16(FLASH_BASE + OFS_FCTL3) = FWKEY + LOCK;

}

A: Section 7.3.3.1 of the User's Guide says:

A byte or word write operation can be initiated from within flash memory or from RAM. When initiating from within flash memory, all timing is controlled by the flash controller, and the CPU is held while the write completes. After the write completes, the CPU resumes code execution with the instruction following
  the write.

That code works because it is not actually necessary to check the BUSY bit.

A: As CL mentioned, as long as you run the code from flash, busywaiting is not necessary.
If, on the other hand, you would execute that code from RAM - for example, to dynamically rewrite the binary program code itself - you would need full locking.
The code below will do the same job. It is also slightly optimized for speed - no need to decrement another variable in the body of the loop.
void FlashCtl_write8(uint8_t *data_ptr, uint8_t *flash_ptr, uint16_t count)
{
    const uint8_t *end = data_ptr + count;

    // Clear Lock bit
    HWREG16(FLASH_BASE + OFS_FCTL3) = FWKEY;

    // Enable byte/word write mode
    HWREG16(FLASH_BASE + OFS_FCTL1) = FWKEY + WRT;

    while(data_ptr < end)
    {
        // Write to flash
        *flash_ptr++ = *data_ptr++;
    }

    // Clear WRT bit
    HWREG16(FLASH_BASE + OFS_FCTL1) = FWKEY;

    // Set LOCK bit
    HWREG16(FLASH_BASE + OFS_FCTL3) = FWKEY + LOCK;
}


text:
Q: What are good uses of the css `content` property? Does the css content property break the rule of content and separation because css is for presentation not to generate content?
What are other good uses of the css content property? I've seen it only in clearfix hacks.

A: One popular place that this shows up is in WordPress' default theme
.entry ul li:before, #sidebar ul ul li:before {
    content:"» ";
}

A: It could be used in print style sheets to show urls for links for example:
p a:after {
  content: " (" attr(href) ")";
}

Some link (http://www.somesite.com)

A: It's good for structured content. I wrote a number of test cases for the W3C's next print CSS rules and the one that seemed cool to me was being able to put "Chapter " and things like that into certain elements, especially when paired with counters. A simplistic example would be something like:
li.chapter:before {content: "Chapter" counter(chapter) ": ";}

None of that's print-specific and it's all presentation information. If you don't want your chapters to be preceded with the word "Chapter", take it out of the CSS. Controlling that in a stylesheet means your print version could have different chapter headings from your screen version your mobile could be different again, without having to have any knowledge of the viewer's device inside your application logic.

A: A common use I see for it is with :before and :after tags to format quotations with some sort of stylized quote box. It can be a quick and easy way to get in stylized elements that you would otherwise have build images out of.
blockquote:before, blockquote:after {
    content: '"';
}

I think this is an okay use for it, because it doesn't really break rules of content and style separation. My feeling is that if it is part of the design of the page, rather than the content, it's probably okay for content:

A: CSS is presentational data. Any content that's only presentation-related is fine in a CSS file. For instance, suppose I want to put « and » around my <h1> tags; that's purely presentational. You could do it with the :before and :after selectors.
It should also be noted that content can also display images:
content: url('my/image.png');

I'd like to add, on a side note, that I'd consider the use of the content property to override already existing content an extremely bad practice.

A: I'm using it to display accesskey in admin panel menu
.menu a[accesskey]:after { content:' [' attr(accesskey) ']'; }

A: One interesting use case, although maybe not recommended, is for placeholder text on contenteditables.
[contenteditable]:empty:after
{
    color: #aaa;
    content: 'Enter some text';
}

A:
Does css "content" property break the rule of content and separation because css is for presentation not to generation content?

Good point. I'd say it does if it's used for actual data.
The quirksmode page on content shows the limitations pretty well. You can't add any kind of styled content at the moment - it will work with too few browsers. You can add only character data.
The author of the quirksmode airs an interesting opinion:

I feel that we shouldn't use the content declaration at all. It adds content to the page, and CSS is meant for adding presentation to the page, and not content. Therefore I feel that you should use JavaScript if you want to dynamically generate content. CSS is the wrong tool for this job.

I agree with this in general, but sometimes there may be cases where you don't want to rely on JavaScript to do the job. The comma example shown by Martin is a case where I find using content justified (although I personally would be feeling better if the commas would already be served coming from server side - it's what I personally would stick to.)
Also, keep in mind that adding commas and quotes through the content property may look bad when your content is viewed from elsewhere - for example in a search results page.
I'd say use it only sparingly, if you really need it.

A: Like zneak said, it is also possible to replace images. I find it practical to replace "content images" (not "asset images", which should be done via css background images) with higher resolution variants on iPhone 4 and other devices that have more than one real pixel per virtual pixel.
E. g.:
<img id="people9" src="//lorempixum.com/200/150/people/9/" width="200" height="150" alt="People"/>
@media all and (-webkit-min-device-pixel-ratio: 2) {
  /* e. g. iphone 4 */
  #people9 { content: url(//lorempixum.com/400/300/people/9/); }
}

It works, at least, on iPhone 4 and Android Nexus S, but I consider it experimental and haven't tested it on other devices. Here is a complete example:
https://gist.github.com/1206008

A: I just want to add to what has already been said.
With Cascading Style Sheets you can apply styles to a lot of types of documents.
The common use case is to apply CSS to HTML pages. In this case, the general idea is to use the content property only for aesthetic purposes.
Another use case is instead to apply CSS to XML documents. In this case the document usually does not contain elements for page structure (div, h1, etc...). So, in this scenario, by using the content CSS property more frequently, you can better define the page and the relations between elements and data.
For example you could prepend a description paragraph before a table, or appending the email address after the name of a person. Note that in HTML pages these page-structure elements should be part of the HTML document itself while they are usually omitted in a XML document and so they can be added using the content CSS property.

A: One of interesting use cases would be localization of a User Interface.


text:
Q: VLAN support on Juniper EX - 2200 switches I have 6 Juniper switches (EX - 2200) connected to each other as shown in the network topology.
I have two PC's that I am using
PC1 - (used for configuring the 6 switches via minicom) PC2 - to monitor the traffic between the switches via the Ports that are marked with arrows in the diagram.
STEP 1:
I create a new vlan On Switch 3 (SW3) that includes Port 12 and Port 22.
I also assign l3-interface to the vlan (vlan_2) with ip address - 192.168.1.7.
Now I plug-in Port 0 of Switch 3 on PC2.

Now I try pinging 192.168.1.7 from PC2 (192.168.1.10)

I want to know what will happen? My postulation is that I will not be able to ping SW3 from PC2.This is because SW3 (Port 12 and Port 22) is a part of a vlan_2 and vlan_2 logically breaks up broadcast domains and so 192.168.1.7 will not be reachable from 192.168.1.10.
Now I have an l3-interface on SW1 with IP  192.168.1.1  using default vlan( vlan-id 0).
 Similarly I have enabled IP on SW2 - 192.168.1.2
                                SW3 - 192.168.1.3
                                SW4 - 192.168.1.4
                                SW5 - 192.168.1.5
                                SW6 - 192.168.1.6

all using default vlan.
Now I plug in Port 12 of SW3 (blue cable) into the PC2.
I try to ping 192.168.1.1 from PC2.
What will happen at this stage.?
My postulation is that I will be able to ping switch 1.Is this correct?
Also another question is that can a single port on a Switch be added multiple VLANS?
I am a beginner at network configuration? Any help would be highly appreciated.
(Please ignore the CISCO symbol on the switches in the diagram.All swithes are Junper EX 22-00.)

A: Intra-VLAN Routing
In your first question, your correct in your first assumption that users in VLAN 0 won't be able to contact users in VLAN 2, to include the l3-interface you have set up on SW3, but only because you haven't set up a default-gateway on PC2 or SW3.
What is the next thing a host does if it sends out a broadcast on its VLAN and receives nothing?  It sends it to its default gateway, which you don't have set up in this instance.  Remember, your switch isn't just a switch anymore; it's a layer 3 switch, which means it routes.
VLAN Switching
Your second question seems pretty simple given a few more things happen.  As long as ge-0/0/12 is setup for an access port, then you should have simple layer 2 connectivity.
Multi-VLAN Ports
A single switch port, in access mode, cannot be set up for multiple VLAN access.  You could set the port up for 802.1q, trunking, and span all the VLANs to it; this would require you to have the proper software and a compatible NIC on your machine though.  On Linux, check out vconfig.

A: I can see two orders of problems with this setup:

*

*You need to setup trunks between the switches or nothing that is not in the default vlan will actually be delivered. Any link between two switches needs to be setup as a 802.1q trunk.

*Port 12 and Port 22 are in a different broadcast domain. All the "l3 interfaces" on  the switches are (as you said) in vlan0, while Port 12 and 22 on SW3 are in vlan2. If you need different VLANs to be able to talk to each other, you need InterVLAN routing.

The theory behind point 1 is that VLAN traffic can only pass through a trunk. These stops "client" devices (such as your PC2) from seeing traffic that doesn't belong to them.
You seem familar at least in principles with the concept of "broadcast domain". You should also know that the only device that can traverse multiple broadcast domain is a Layer3 or higher device. It seems to me that these switches are managed L2 devices. You need a router and a good bit of vlan theory :) Later tonight i'll post a quick sketch with all the bits needed to get this working.
Your second question: "Can a port be added to multiple vlans?" No it can't. In port-based vlans, such as the ones you're using, it's a moot point. THere are different flavors of VLANs. If you need more than one vlan to go through that port, again, you need a trunk and a capable device on the other end that can handle them. But i doubt that is your requirement.
You should stick to port-based vlans since they're the most common form, the easiest to setup and the one most people use.
Why do you need more than one vlan on a client port? what kind of device do you have on that port? The only common use case is a virtualization Hypervisor. In that case, you need a trunk on that port.
Also: Unrelated but i felt i needed to point it out. Your topology is very prone to failure. If top or bottom switches should die, a big chunk of your network would collapse. Consider a different topology and some spanning-tree.


text:
Q: MySQL union, joins & limit I have the following query:
SELECT result.globalId AS id, result.date, p1.playerName AS player, p2.playerName AS   target, w.weaponIngameName AS weapon, result.headshot, s.serverName AS server, result.origin
FROM (
(

SELECT globalId, date, serverId, playerId, targetId, weaponId, headshot, 'playerkills' AS origin
FROM playerkills
WHERE (
playerkills.playerId =976
OR playerkills.targetId =976
)
ORDER BY date DESC
)
UNION (

SELECT globalId, date, serverId, playerId, NULL , NULL , NULL , 'playersuicides' AS origin
FROM playersuicides
WHERE (
playersuicides.playerId =976
)
ORDER BY date DESC
)
)result
LEFT JOIN players p1 ON result.playerId = p1.playerId
LEFT JOIN players p2 ON result.targetId = p2.playerId
LEFT JOIN weapons w ON result.weaponId = w.weaponId
LEFT JOIN servers s ON result.serverId = s.serverId
ORDER BY result.date DESC , result.globalId DESC

And I want to limit the result union to have a maximum of 300 results, before any of the JOINs are being applied. How do I accomplish this?
Simply adding LIMIT 300 after (...) result does not work, it gives the following MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN players p1 ON result.playerId = p1.playerId LEFT JOIN players p2 ON r' at line 9

A: When changing the query to the following, it does work:
SELECT result.globalId AS id, result.date, p1.playerName AS player, p2.playerName AS   target, w.weaponIngameName AS weapon, result.headshot, s.serverName AS server, result.origin
FROM (
(

SELECT globalId, date, serverId, playerId, targetId, weaponId, headshot, 'playerkills' AS origin
FROM playerkills
WHERE (
playerkills.playerId =976
OR playerkills.targetId =976
)
ORDER BY date DESC
)
UNION (

SELECT globalId, date, serverId, playerId, NULL , NULL , NULL , 'playersuicides' AS origin
FROM playersuicides
WHERE (
playersuicides.playerId =976
)
ORDER BY date DESC
) ORDER BY date DESC LIMIT 300) result
LEFT JOIN players p1 ON result.playerId = p1.playerId
LEFT JOIN players p2 ON result.targetId = p2.playerId
LEFT JOIN weapons w ON result.weaponId = w.weaponId
LEFT JOIN servers s ON result.serverId = s.serverId
ORDER BY result.date DESC , result.globalId DESC

Note that I added the ORDER BY date DESC LIMIT 300 before calling the table result, so now the following happens roughly:
1) Individual SELECTs inside UNION are being ran.
2) UNION is used to combine the results.
3) The ORDER BY and LIMIT is being applied to the UNION.
4) The UNION is named as result.
5) The rest of the query happens.


text:
Q: (clearification of proof) definition of operator norm
Hi, I am having difficulty understanding the proof of Theorem 4.3(b) in the book Linear Operations in Hilbert Spaces by Weidmann. Can someone please explain the 3 statements
$$ \|Tf\|\geq |\langle Tf,g\rangle | \text{ for all $g$ with } \|g\|=1, $$
$$ \exists g_n:\|g_n\|=1, g_n\rightarrow \|Tf\|^{-1}Tf, $$
and $$ |\langle Tf,g_n \rangle |\rightarrow \|Tf\|. $$
Thanks.

A: Statement 1: This is just Cauchy Schwarz
Statement 2: This follows from the facts that $R(T) \subseteq \overline{M}$ and $Tf \in R(T)$ (and thus $||Tf||^{-1}Tf \in R(T)$)
Statement 3: This follows from inner producting both sides of statement 2 with $Tf$.


text:
Q: How to pass javascript function as a parameter in the route values of Ajax Actionlink I need to pass javascript function as a parameter value to the ajax actionlink in asp.net mvc app. how can we achieve this?
Thanks in advance.

A: I don't think you can pass javascript functions in Route Values! Are you sure this is exactly what you meant?


text:
Q: Prettier format on save formats file but leaves changes unsaved On save, the file is formatted as it should be, but the formatted file is left unsaved, so that I need to ctrl+s twice to actually format and save a given file.
This is a very recent issue, not sure if it just started with the latest insiders build or a new version of Prettier. I've removed all other extensions, reinstalled prettier, etc, but nothing has helped so far.
Anyone else seen the same issue?
It's not an issue with the Ctrl-S keybinding, that's set to default for me, and I see no issues in the debugger:
[2021-07-16 20:55:09.729] [renderer1] [info] [KeybindingService]: | Resolving ctrl+S
[2021-07-16 20:55:09.729] [renderer1] [info] [KeybindingService]: \ From 1 keybinding entries, matched workbench.action.files.save, when: no when condition, source: built-in.

A: Looks to be a new insiders issue: https://github.com/microsoft/vscode/issues/128869


text:
Q: what happens in linux glibc if keep increasingly accessing memory exceeding malloc() allocated size Seems comments/answers just simply stops at C standard description, let's discuss a bit more deep with implementation specific.
I saw below code in other discussion:
struct { size_t x; char a[]; } *p;
p = malloc(sizeof *p + 100);
if (p)
{
    /* You can now access up to p->a[99] safely */
}

Then what if keep accessing p->a[i], 99< i < 0xffff or even bigger value?

*

*malloc implementation should have a virtual memory block backed area for "(sizeof *p + 100)", so after "i" exceeds 100, initially it should be just corrupt data within the virtual memory block which might be non harmful.

*if later "i" exceed that virtual memory block size, while next block is available and is never physical memory backed up(means ready to be allocated), would copy-on-write in kernel physical memory happens for next block on this bad access? And would malloc() later aware of this?

*if next block is not in heap management, should p->a[i] get a virtual memory access violation error? Because malloc() is not called, so brk/sbrk won't be triggered to expand memory region of process heap.
Just curious how damage it is in this case...

A: Accessing stuff outside of the allocated memory is undefined behavior.   Anything can happen.  I hear nasal demons are a possibility.

If you are really lucky, you might get an access violation/segfault.  If you aren't lucky, then some other variable in the program may be overwritten, or nothing observable may happen, The moon may turn into the 7UP logo, or maybe something nasty squeezes out of your right nostril.


text:
Q: Reverse Engineering Regex in R? I found this Regex code (in R) that can recognize the following "class" of pattern: "LETTER-NUMBER-LETTER NUMBER-LETTER-NUMBER" in a set of strings:
apply(my_string, 1, function(x) gsub('(([A-Z] ?[0-9]){3})|.', '\\1', toString(x)))

Based on the above code, it appears that the corresponding Regex "class" for "LETTER-NUMBER-LETTER NUMBER-LETTER-NUMBER" is "(([A-Z] ?[0-9]){3})|."
This leads me to my question:
Suppose I had the following input in R:
input = "A1B 2C3"

Is there some way I can determine what "class" of Regex is contained within this string? For example, does such a function exist?
output = some_function("A1B 2C3")

> output
'(([A-Z] ?[0-9]){3})|.'

I found this website (https://regex-generator.olafneumann.org/?sampleText=the%20follow%20abc&flags=i&selection=11%7CMultiple%20characters) that appears to perform a similar task - but is there a way to do this in R? For example (I am not sure if this is correct) :
string = c("s0me strIngz123", "someString3s", "S0M3 5t1ngs")

#imaginary conversion function

regex_class = some_function(string)

# output

           string                  regex_class
1 s0me strIngz123 ^[A-Za-z0-9]+.*[a-zA-Z]+123$
2    someString3s               ^[A-Za-z0-9]+$
3     S0M3 5t1ngs  ^[A-Za-z0-9]+ [A-Za-z0-9]+$

Is there some way in R to determine the general "Regex Class" for different strings?
Thank you!

A: I think it is not possible to make a generalized pattern and I'll try to explain why.
As soon as there are almost no scalars in R I'll use terms for data types from Pascal:

*

*char (character) - a single character symbol (letter, digit or special) In R it will be for instance the result of intToUtf8(strtoi("0x000A")).

*string - an array of char (characters) - no exact match in R. In terms of our discussion we can take "ABC" or "ABC"[1].

*array of string (character in R). For instance c("ABC", "DEF").

We can build our explanation either from the level of a char (character) towards array of string or vice versa.
First. The generalized algorithm is impossible for char (character). The reason is simple. Say we have a char A. The generalized pattern can be

*

*A only,

*A or a,

*A or B or other limited vector of permitted characters (for instance from my previous sample: letters used in hex spelling "A":"F" with or without "a":"f"),

*(uppercase) letters,

*(all) letters and digits,

*any char (letters, digits, space, punctuation marks and special).

You see that a single character does not give any sufficient information to predict the generalized pattern of regex.
Second. The generalized algorithm is impossible for a single string.

*

*It is not possible to automatically predict permitted position of a certain character within the string.

*There is no cybernetic reason to decide that the length of the string must be the same as the length of the sample string as well as to know the range of allowed lengths.

*It is not also possible to find out limitations of char groups that must be present (absent) inside the string.

*It is also impossible to exclude that NA or "" are allowed values for such a strings upon having analysed a single !is.na() string. The opposite conclusion is also lawful. Having a single string == "" for instance we can not state that all strings must be empty.

So the position of characters, the length of the string and group of chars can not be uniquely limited upon the analysis of the single sample string.
Third. The array of strings is also not sufficient to build regex.

*

*At least it can be never estimated must this array have at least one member or can be null / 0 length.

*How many members must it have and in general is there (any) law for allowed number of such memebers.

Actually limitations for array of string have much in common with those for string.
Conclusion.
Upon these considerations we can make the following conclusions.

*

*At least the single pattern is ever possible. This pattern will equal to analysed string.

*The patterns for a specific char / string / array of string are not unique, and it is ever possible to build n regex'es depending upon the specific qualities of the analysed string. n is infinite (as soon as we assume that strings of infinite length  are allowed) or at least (very) large.

*Adding machine learning and other AI algorithms we can reduce n and build more suitable regex'es. But all the results of AI are statistically limited and can have higher or lower significance that never reaches 1. So these methods will give us m regexes. Though m <= n still m != 1. Even consideration that m < n is doubtfull as some regexes form m will be less likely but still possible.


text:
Q: Run php from jquery click, return array from php file which calls another file yesterday i managed to get my data from a database outputting and storing to a java array. However that was on load, now that code wont work for on click.
So I have read about ajax and have this function:
  var infArray = new Array();
  var country;
    $('#australia').click(function() {
        //console.log("you clicked"+txt);
        country = 'Australia';
        $.ajax({
            type: 'POST',
            url: 'php/Maps.php',
            data: {country: country},
            success: function(data){
            alert("success"+data); // this will hold your $result value
            infArray = JSON.parse(data)
            console.log( 'Return:' + data );
            }
        });
    });

By my understanding this opens the php file containing the function and allows you to use the variable "country" by using $_POST.
So my php file looks like this :
<?php
require '../classes/Mysql.php';

function get_Stockist(){ // if su = 0 then stockist if = 1 then member
    $mysql = new Mysql();
    $result = $mysql->getInfo($_POST['country']);
    echo json_encode($result);
}

so again in my eyes, $result is set to the result of the method :
in Mysql.php :
function getinfo($country){

    $rows = array();
    $query = "SELECT Name,add1 FROM stockistsWorld WHERE Country = '". mysql_escape_string($country) ."' LIMIT 5";
    //$query = "SELECT Name,add1 FROM stockistsUK LIMIT 10";
    $result = mysqli_query($this->conn, $query);
    /* numeric array */

    while($row = mysqli_fetch_array($result, MYSQLI_NUM)){

         $rows[] = $row;

        }
    return $rows;
}

However the result in my html is null

A: You never call your function get_Stockist() in your PHP file that gets called by AJAX.
Add get_Stockist() to your PHP file to call your function.
And your other function is getinfo, without capital i.
So it would be $mysql->getinfo($_POST['country']); instead of $mysql->getInfo($_POST['country']);


text:
Q: Excel VBA Using GetObject for Word Document causes Source Application May Be Busy Error Alright, so I'm try to reference an open Word document. But no matter what I do it stalls out and causes an error. The error takes 20-30 seconds before it pops up
"The object is not responding because the source application may be busy"
Dim oWord As Object

Set oWord = GetObject(, "Word.Application")
Debug.Print oWord.Documents.Count

Just a simple code block like above when I try Documents.Count it errors out. So I can't do anything with the GetObject object. Anyone have any clue on how to solve this problem?
Thanks
I've tried everything I can find on the Internet. I can open the file using CreateObject, but once it is open I cannot access it.
SOLVED
I'm an idiot. So I went to the task manager and it turns out there were like 20 Word instances that were created through my testing processes, so the GetObject was just timing out. When I closed all the instances, then opened one instance and ran the GetObject it worked and Documents.Count gave the correct answer.
Sorry for wasting your time!!

A: Your code works just fine for me - provided Word is running - returning a result after about 1 second. What it lacks is code to start Word if it isn't already running, in which case it errors out.
What you need is something like:
Dim wdApp As Object, bStrt As Boolean
' Test whether Word is already running.
On Error Resume Next
bStrt = False ' Flag to record if we start Word, so we can close it later.
Set wdApp = GetObject(, "Word.Application")
'Start Word if it isn't running
If wdApp Is Nothing Then
  Set wdApp = CreateObject("Word.Application")
  If wdApp Is Nothing Then
    MsgBox "Can't start Word.", vbExclamation
    Exit Sub
  End If
  ' Record that we've started Word, so we can terminate it later.
  bStrt = True
End If
MsgBox wdApp.Documents.Count

Perhaps you should check in Task Manager for an orphaned Word session running in the background. Other than that, you may need to restart Windows. If the problem persists, you may need to repair your Office installation.


text:
Q: Nodejs:Executing a shell command with switches & populating variables within that command What am I doing wrong here? I am trying to have the node_ip variable to populate the knife bootstrap command with the specific switches and bootstrap the node which is represented by that noe_ip variable. I am new to node.js ,any help is appreciated. How can I fix the issue and write this code better?
    var exec = require('child_process').exec;
var child;
child = exec("tugboat info test-node-004|grep -w Status|sed -r 's:\x1B\[[0-9;]*[mK]::g'|grep -o '[^:]*$'|sed -e 's/^[ \t]*//' -e 's/[ \t]*$//'",
  function (error, stdout) {
    //process.stdout.write(stdout);
  if (stdout.indexOf("active")!= -1) {
          console.log('Node is ACTIVE');
          var child;
          child = exec("tugboat info test-node-004|grep -w IP|sed -r 's:\x1B\[[0-9;]*[mK]::g'|grep -o '[^:]*$'|sed -e 's/^[ \t]*//' -e 's/[ \t]*$//'",
          function (error, stdout) {console.log("IP ADDRESS:" + stdout);
          var child;
          var user = "root";
          var path = "~/.ssh/id_rsa";
          var role = "'role[webmin]'";
          var node_ip = stdout;
          console.log(node_ip);
         var util  = require('util');
         var spawn = require('child_process').spawn;
         var bootstrap = spawn('/usr/local/rvm/gems/ruby-2.1.1/bin/knife bootstrap', ['-x', 'root'], ['-i', '~/.ssh/id_rsa'], ['-r', "'recipe[apt]'"], [node_ip]);
         bootstrap.stdout.on('data', function (data) {console.log('stdout: ' + data);});
         console.log(node_ip);
         })
        //console.log(stdout);
        }
//});
  else {console.log("Node is INACTIVE")}
});

I get this below error:
    root@app-test-001:~/chef-repo# node ~/test.js
Node is ACTIVE
IP ADDRESS:103.xxx.yy.zz

103.xxx.yy.zz

103.xxx.yy.zz

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:1011:11)
    at Process.ChildProcess._handle.onexit (child_process.js:802:34)

A: spawn takes three arguments:
child_process.spawn(command, [args], [options])

args should be a single list of arguments to the command, so what you want is more like:
spawn('/usr/local/rvm/gems/ruby-2.1.1/bin/knife bootstrap', ['-x', 'root', '-i', '~/.ssh/id_rsa', '-r', "'recipe[apt]'", node_ip]);


text:
Q: Make exceptions to the exceptions of gitignore Git enables one to ignore folders / files.
For instance:
folderName

Git also enables one to make exceptions.
For instance:
!folderName

My question is, if it is possible to make exceptions of the exception.
For instance, given the following folder structure:

*

*sub1

*

*subsub1

*

*exceptedFolderThatShouldNotBeExcepted

*exceptedFolder

*exceptedFile

*exceptedFile2

*subsub2

*subsub3

*sub2

*sub3

It has a folder, subsub1, which may contain lots of files that usually are ignored, but should not be ignored.
This is why !sub\subsub1 is added to gitignore.
But there should be an exception to that: exceptedFolderThatShouldNotBeExcepted should be ignored.
Thus, I am looking for an option like!!exceptedFolderThatShouldNotBeExcepted that leads to git ignoring just that folder.
The motivation for this is not having to except all the other folders and files (exceptedFolder, exceptedFile, exceptedFile2).


text:
Q: How do you make the Windows Components option appear in Setup Manager? Supposedly there is a "Windows Components" option under Advanced Settings when you run the Setup Manager (included in the \Tools\Deploy.cab from a Windows 2003 CD).
I can't get this to show up.
Is there a special trick?
Here is a screenshot of what it is supposed to look like:

When I run it, it looks exactly the same except there is no "Windows Components" option above Telephony.

A: I did a lot of searching on this for you and turned up exactly nothing. Perhaps n-lite can help? Its for building custom or slipstreamed installs, but it may accomplish the same thing.

A: Well I can't get it to show up in the GUI but the next best thing is to control those from the unattended.txt or the winbom.ini directly after saving from Setup Manager.  Once you've done your first unattended.txt you likely will use it as a jumping off point for all future customization and won't go back to Setup Manager which only supports a subset of what you can do in the config files.
Example:
[Components]
AccessOpt = On
Appsrv_console = Off
Aspnet = Off
BitsServerExtensionsISAPI = On
BitsServerExtensionsManager = On
Search the ref.chm Help file included in deploy.cab for "components section" for a list of all options and details of each.
Also be sure you are using the SP2 version of the deploy.cab
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=93f20bb1-97aa-4356-8b43-9584b7e72556&displaylang=en


text:
Q: TableRowSorter use LookAndFeel of TableHeader, but own Comparator Java SE 6
Arrows for ASC/DESC are above Header-Text (is must have by customer)
I use to show arrows above header-text:
TableRowSorter sorter = new TableRowSorter();
sorter.setModel(table.getModel());
table.setRowSorter(sorter);

or
table.setAutoCreateRowSorter(true);

Arrows for ASC/DESC are above Header-Text, that's right. I want to use my own comparator, but in my example, comparator is called, but it does not functioned. What code is to change to sort table-rows by my own comparator with arrows above header-text sorting asc/desc?
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class JTableExample extends JFrame {

    private JTable table;

    private FooTableModel model;

    public JTableExample() {
        super("JTableExample");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
            String plaf = UIManager.getSystemLookAndFeelClassName();
            try {
                UIManager.setLookAndFeel(plaf);
            }
            catch (ClassNotFoundException e) {}
            catch (InstantiationException e) {}
            catch (IllegalAccessException e) {}
            catch (UnsupportedLookAndFeelException e) {}
            SwingUtilities.updateComponentTreeUI(this);

        Object[][] rowData = { { "a", "c" }, { "b", "b" }, { "c", "a" } };
        Object[] columnHeaders = { "Header1", "Header2" };
        model = new FooTableModel(rowData, columnHeaders);

        table = new JTable(model);
        table.setAutoCreateRowSorter(true);

        table.getTableHeader().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
               model.sortByColumn(table.columnAtPoint(evt.getPoint()));
            }
        });

        Container c = getContentPane();
        c.add(new JScrollPane(table), BorderLayout.CENTER);

        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        new JTableExample();
    }

    class FooTableModel extends DefaultTableModel {
        public FooTableModel(Object[][] rowData, Object[] headers) {
            super(rowData, headers);
        }

        public void sortByColumn(final int clm) {
            Collections.sort(this.dataVector, new Comparator() {
                public int compare(Object o1, Object o2) {
                    Vector v1 = (Vector) o1;
                    Vector v2 = (Vector) o2;

                    String s1 = (String) v1.get(clm);
                    String s2 = (String) v2.get(clm);

                    return s1.compareTo(s2);
                }
            });
        }
    }
}

A: Whatever your problem is exactly (hard to tell from your description), you are doing the sorting incorrectly: in Swing JTable the sorting is considered the responsibility of the view (vs. the model as in your implementation).
Custom comparators (per column) are configured in the rowSorter, something like:
table.setAutoCreateRowSorter(true);
((TableRowSorter) table.getRowSorter()).setComparator(columnIndex, myComparator);

BTW: the location of the sort icon is controlled by the LAF, not much you can do to change that (short of writing a custom LAF)


text:
Q: Enums, What's the use of static methods and implementing interface methods? I am having some small doubts regarding Enums. I have the following confusions :-

*

*What is the use of static methods in Enums? Mostly we use Enums for declaring constants. What is the use of this feature?

*I see, an Enum can implement an interface. What would be the use? I am just confused about practical life usage.

*Another confusion is, see the code snippet below,
enum Position {
    FIRST, SECOND, THIRD;
    public static void main(String[] args) { //line 1
        Position p = Position.SECOND; //line 2
        switch(Position.THIRD) { //line 3
            case FIRST: //line 4
                System.out.println("Congrats, You are the winner");//line 5
                break; //line 6
            case SECOND : //line 7
                System.out.println("Congrats, You are the runner");//line 8
                break; //line 9
            default : //line 10
                System.out.println("Better luck next time"); //line 11
        }
    }
}

If use in case statement like Position. First,it gives a compile time error. I understand JLS does not allow this. Reason written is with a class format, it can't make a symbolic linkage. But reverse is true. Like in line-3, i am using the enum itself with fully qualified name. So, my point is, what is the meaning of symbolic linkage and why line-3 is allowed also?
Note
It was basically a typo mistake. My main question was, we are using syntax Position.THIRD in switch condition(which is allowed by compiler) but when we use same syntax in case, it is not allowed. Why is that?
Quote From JLS

(One reason for requiring inlining of constants is that switch
  statements require constants on each case, and no two such constant
  values may be the same. The compiler checks for duplicate constant
  values in a switch statement at compile time; the class file format
  does not do symbolic linkage of case values.)

Here it mentions about Symbolic linkage. But when i wrote something like this in switch condition switch(Position.THIRD), it was allowed where as in CASE statement it was.

A:
What is the use of static methods in Enums?

Same as in any other type. For enums, they're often "given this string value, return the equivalent enum" or something similar. (In cases where valueOf isn't appropriate, e.g. where there are multiple representations.)

I see, an Enum can implement an interface. What would be the use?

Same as with any interface - to decouple implementation from usage. For example, I've made enums implement a localization-related interface before now.

My main question was, we are using syntax Position.THIRD in switch condition(which is allowed by compiler) but when we use same syntax in case, it is not allowed. Why is that?

It's just a language decision - the enum type has to be the same as the type of the switch value itself, so it's redundant information. It has nothing to do with the section of the JLS you quoted.

A: Enums can make pretty nice Singletons ... that basically answers all of your questions :)

A: Enums are a lot like normal classes, except they have certain restrictions on instantiation and they can't extend classes, etc.
Static methods are typically factory methods that return instances of the enum, often looking up the instance whose field matches a parameter. See this example.
Enums can have fields, getters and setters and other methods and can thus implement interfaces - including generic ones. See this example.
You use an enum instead of a class when you want a finite set if named instances.


text:
Q: Error when using ajax load google map api I have a file index.php using jquery:

<input type="hidden" value="36.753671,-119.768336" />test

When I enter input id=('36.753671,-119.768336') is ajax not result,
  Can I help me ? I want this ideas

A: I see that the script tage in map.php is within PHP code which should not be. Two ways to fix.
1)
$id = $_POST['id'];
?> //close php tag here

2)
$id = $_POST['id'];
   echo '

    ';


text:
Q: Offline Python Speech Recognition I am creating a project that must respond to voice commands. I want this to work offline and I need it to be fast. I have tried PocketSphinx but it is not accurate enough. I will say, "hello", and in a quiet room it will display "mello" or "chello" my mic is good. What should I do? If I try to recognize it with google recognition then I get the perfect results. But my internet is slow and it takes forever. Any help is appreciated!

A: Try snowboy.kitt.ai it is a wake word engine so you can have it recognize commands like "turn on the lights" or "hey Jarvis"


text:
Q: Wrong result from K-means algorithm I want to put these 8 points into 3 clusters using K-means. If I pick up -5, -1, and 2 as the initial centroids, it will return this result at the first round, and the algorithm will stop correcting because all the points seem to be assigned to the correct cluster now.

However, we know this is not the best result. The result shall be in the picture below:

I think I calculate everything correctly following the algorithm. Was there anything wrong?  Or is it a disadvantage of this algorithm that it does not always return the best result with the smallest sum of squared error (SSE)?
I applied the algorithm on the following data in Python. It seems the result is not the one with the smallest SSE.


text:
Q: How to hide series name and color displaying at the bottom of the highchart? I've highlighted the content to be removed from displaying in my chart

A: You are looking for legend.enabled. Just add this to your chart:
legend: {
    enabled: false
}

See example.


text:
Q: Overwrite characters in a TextBox When I type in this textbox, I need that the default behavior is overwrite, instead insert.
I don´t know if I made my self clear.
For example: I have a textbox with MaxLenght = 4. When it get focus, it need to overwrite chars, from the first to last.
I can do this using the "Insert" button. But I need an automatic solution.

A: You can do that using reflection by setting _OvertypeMode to True on TextEditor property of TextBox.
Suppose you have TextBox declaration in XAML:
<TextBox x:Name="textBox"/>

and in code behind, you can do:
PropertyInfo textEditorProperty = typeof(TextBox).GetProperty(
                  "TextEditor", BindingFlags.NonPublic | BindingFlags.Instance);

object textEditor = textEditorProperty.GetValue(textBox, null);

// set _OvertypeMode on the TextEditor
PropertyInfo overtypeModeProperty = textEditor.GetType().GetProperty(
               "_OvertypeMode", BindingFlags.NonPublic | BindingFlags.Instance);

overtypeModeProperty.SetValue(textEditor, true, null);

Source - MSDN link.

A: You could try handling the key down event, for example:
private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{
    int myCaretIndex = MyTextBox.CaretIndex;
    char[] characters = MyTextBox.Text.ToCharArray();

    if (myCaretIndex < characters.Length)
    {
        characters[myCaretIndex] = char.Parse(e.Key.ToString());

        MyTextBox.Text = string.Join("", characters);

        MyTextBox.CaretIndex = myCaretIndex + 1;

        e.Handled = true;
    }
}


text:
Q: Modify a method declared in the superclass with Javassist I'm trying to modify a method with CtMethod#insertBefore that is declared in the superclass. However, it seems to not be possible with Javassist.
private class AbstractTestDataSource {
    public Connection getConnection() throws SQLException {
        return connection;
    }
}

private class TestDataSource extends AbstractTestDataSource implements DataSource {
    public Connection getConnection(String username, String password) throws SQLException {
        return connection;
    }
    // other methods omitted
}

This is my ClassFileTransformer
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                                  ProtectionDomain protectionDomain, byte[] classfileBuffer)
        throws Exception {
    if (!className.equals("org/example/TestDataSource")) {
        return classfileBuffer;
    }
    final CtClass ctClass = createCtClass(loader, classfileBuffer);
    for (CtMethod method : ctClass.getMethods()) {
        if (method.getName().equals("getConnection")) {
            System.out.print(method.getName());
            System.out.println(method.getSignature());
            method.insertBefore("System.out.println(\"foo\");");
        }
    }
    return ctClass.toBytecode();
}

When I'm calling the getConnection(String, String) method, foo is printed to the console, but if I call the getConnection() method that is declared in AbstractTestDataSource nothing happens.
What am I doing wrong?
Edit
I can confirm that both methods are instrumented because this is what is printed to the console:
getConnection(Ljava/lang/String;Ljava/lang/String;)Ljava/sql/Connection;
getConnection()Ljava/sql/Connection;

A: My solution is to check whether the getConnection method is declared in a class other than the current one.
if (!ctClass.equals(method.getDeclaringClass())) {
    method = overrideMethod(ctClass, method);
}

If so, I create (and thus override) the getConnection method and delegate to the superclass.
private CtMethod overrideMethod(CtClass ctClass, CtMethod getConnectionMethodOfSuperclass)
        throws NotFoundException, CannotCompileException {
    final CtMethod m = CtNewMethod.delegator(getConnectionMethodOfSuperclass, ctClass);
    ctClass.addMethod(m);
    return m;
}

It doesn't feel like the ideal solution, but it is working fine.

A: You are not overriding the method getConnection() in the super class, that method has this method signature:
public Connection getConnection() throws SQLException

In your child class you'll have to override this method with the same method signature, otherwise you are just creating a new method in the child class


text:
Q: Location of #th iteration of a character or a word in a sql text field How can I get the location for the #th iteration of a character or a word in a sql server text field?

A: There's no specific support for this in Transact-SQL.
You could write your own function using CHARINDEX.
Alternatively, you could use a library that someone else has already written, for example the SQLsharp SQLCLR extension library. Among the over 240 functions and procedures is SQL#.String_NthIndexOf:
-- Result: 13
SELECT SQL#.String_NthIndexOf
(
    N'abc abc abc abc abc',  -- Input string
    N'abc',                  -- Search for this
    1,                       -- Starting at position
    4,                       -- Nth occurrence
    1,                       -- Case sensitive
    0                        -- Don't count overlaps
);

I have no association with this (mostly free) product, I am just a fan.

A: Before I even begin, these solutions deliver what's asked, but they should never be expected to perform well inside of SQL Server. Outside of Paul's suggestion to use SQLSharp, I think you will have much better results - if you care about performance - pulling these strings apart in your application logic, be it C#, PHP, what have you. That said...
Single Character
For a specific character, this isn't altogether too terrible, but I still suspect you will be better off doing this kind of thing in the application tier once you've pulled back the full value. First, create a numbers table, if you don't already have one - this one creates 50,000 rows, but you could easily extend the source set to a much higher number if need be:
CREATE TABLE dbo.Numbers(Number INT PRIMARY KEY);

;WITH [set] AS
(
  SELECT TOP (50000) Number = ROW_NUMBER()
    OVER (ORDER BY s1.[object_id])
    FROM sys.objects AS s1
    CROSS JOIN sys.objects AS s2
    ORDER BY Number
)
INSERT dbo.Numbers WITH (TABLOCKX) (Number)
  SELECT Number FROM [set];

Now, you can create a function that just breaks the string into single characters, applying a number to represent the location within the string, and then a window function to indicate the appearance of that character:
CREATE FUNCTION dbo.FindCharacter
(
  @string VARCHAR(255),
  @character_to_find CHAR(1),
  @instance_of_character TINYINT
)
RETURNS INT
WITH SCHEMABINDING
AS
BEGIN
  RETURN
  (
    SELECT n FROM
    (
      SELECT n = number,
        s = SUBSTRING(@string, number, 1),
        r = ROW_NUMBER() OVER
        (
          PARTITION BY SUBSTRING(@string, number, 1)
          ORDER BY number
        )
        FROM dbo.Numbers_Set
        WHERE Number <= LEN(@string)
     ) AS x
     WHERE s = @character_to_find
       AND r = @instance_of_character
  );
END
GO

Sample usage:
DECLARE @x TABLE(i INT, s VARCHAR(255));

INSERT @x VALUES(1,'dhsjdhsdxshdsjdxkjsdxlsd'),
                (2,'sdsdxsdsdsxsxsdsd'),
                (3,'yyyyyyy');

DECLARE
  @character_to_find VARCHAR(255) = 'x',
  @instance_of_character TINYINT = 3;

SELECT i, s, dbo.FindCharacter
  (s,@character_to_find,@instance_of_character)
  FROM @x;

Results:
i    s                          loc
---- -------------------------- ---
1    dhsjdhsdxshdsjdxkjsdxlsd   21
2    sdsdxsdsdsxsxsdsd          13
3    yyyyyyy                    NULL

"Word" (sequence of characters)
In this case the easiest approach I could think of was to use the same Numbers table as above, but from within an inline table-valued function. I am assuming that by "word" you simply mean "sequence of characters", and not literally a word separated by spaces (which would also be possible, but that's not what I solved for here).
CREATE FUNCTION dbo.FindWord
(
  @string VARCHAR(255),
  @word_to_find VARCHAR(255),
  @instance_of_word TINYINT
)
RETURNS TABLE
WITH SCHEMABINDING
AS
   RETURN ( SELECT loc FROM
   (
     SELECT loc, rn = ROW_NUMBER() OVER (ORDER BY loc)
     FROM
     (
       SELECT loc = Number + CASE Number WHEN 1 THEN 0 ELSE 1 END
         FROM dbo.Numbers WHERE Number <= CONVERT(INT, LEN(@string))
         AND SUBSTRING
         (@word_to_find + @string, Number, LEN(@word_to_find))
           = @word_to_find
     ) AS x
    ) AS y WHERE rn = @instance_of_word
   );
GO

Sample usage:
DECLARE @x TABLE(i INT, s VARCHAR(255));

INSERT @x VALUES(1,'dhsjdhsdxshdsjdxkjsdxlsd'),
                (2,'sdsdxsdsdsxsxsdsd'),
                (3,'yyyyyyy');

DECLARE
  @word_to_find VARCHAR(255) = 'sd',
  @instance_of_word TINYINT = 3;

SELECT x.i, x.s, f.loc
  FROM @x AS x
  OUTER APPLY dbo.FindWord
    (x.s, @word_to_find, @instance_of_word) AS f;

Results:
i    s                          loc
---- -------------------------- ---
1    dhsjdhsdxshdsjdxkjsdxlsd   22
2    sdsdxsdsdsxsxsdsd          6
3    yyyyyyy                    NULL

Word (separated by spaces)
This is a slight variation of the above, but we need to split by spaces first, then find all the instances of the word we're after in that set.
CREATE FUNCTION dbo.FindWord2
(
   @string VARCHAR(255),
   @word_to_find VARCHAR(255),
   @instance_of_word TINYINT
)
RETURNS TABLE
WITH SCHEMABINDING
AS
   RETURN
   ( SELECT loc = Number FROM
     (
       SELECT Number, rn = ROW_NUMBER() OVER (ORDER BY Number)
       FROM
       (
         SELECT Number,
           Item = SUBSTRING(@string, Number,
           CHARINDEX(' ', @string + ' ', Number) - Number)
         FROM dbo.Numbers
         WHERE Number <= CONVERT(INT, LEN(@string))
           AND SUBSTRING(' ' + @string, Number, 1) = ' '
       ) AS x WHERE Item = @word_to_find
     ) AS y WHERE rn = @instance_of_word
   );
GO

Sample usage:
DECLARE @x TABLE(i INT, s VARCHAR(255));

INSERT @x VALUES(1,'hot axe hot goo shot fud hot'),
                (2,'hot bling foo hot x hot what'),
                (3,'yyyyyyy');

DECLARE
  @word_to_find VARCHAR(255) = 'hot',
  @instance_of_word TINYINT = 3;

SELECT x.i, x.s, f.loc
  FROM @x AS x
  OUTER APPLY dbo.FindWord2
    (x.s, @word_to_find, @instance_of_word) AS f;

Results:
i    s                            loc
---- ---------------------------- ----
1    hot axe hot goo shot fud hot 26
2    hot bling foo hot x hot what 21
3    yyyyyyy                      NULL

Once again
This is not going to break any performance records; if you can seek more efficient ways to do this outside of the constructs of plain T-SQL, I highly advise that you do so.


text:
Q: Classic asp persist custom classes in session Is it possible to persist a class in session that I define in VBScript in classic asp:
<script runat=server language=vbscript>

Class clsCourse
Private Sub Class_Initialize
' Statements go here.
End Sub
End Class

dim oCourse
set oCourse=new clsCourse
</script>

How would I persist oCourse in session and recover it from session?
I know session is bad, but this is a high volume application and I'm concerned about hitting the database multiple times in a page call.

A: EDIT: Take a look at these answers for a more thorough explanation Classic ASP Store objects in the session object
Unfortunately you can't store classes in session. This page gives a good explanation:
https://web.archive.org/web/20061026090950/http://www.4guysfromrolla.com/aspfaqs/ShowFAQ.asp?FAQID=195
One solution could be to make the class a wrapper for an array and just store that array in session.


text:
Q: Easiest/Cheapest alternative of an oscilloscope to observe PWM signal, if any Is there a tool/method that I can make use of instead of an oscilloscope to be able to display or at least gather information such that its frequency and on-off times of a PWM signal, out of a microcontroller let's say. A cheaper alternative, of course.

A: Here's a few options:

*

*Chinese Logic Analyzer. There are knockoffs available of the "Saleae logic 16" for around 50 bucks on ebay. These work great for debugging digital connections. If you can afford it get the genuine one of course.

*Read the signal with a microcontroller and transmit it over USB as DKNguyen suggested. The simplest would be digital read, then transmit in a loop but that might not be fast enough, in which case you might need to pack multiple samples into 1 character or something like that. You will also need to manage the timing of the samples, while simultaneously transmitting via serial, so the code won't be trivial.

*Same as 2, but a better way that just occurred to me is this: Don't read and transmit simultaneously. Simply read data into an array, and once the array is full, stop sampling and transmit the captured data over serial.

A: *

*For audio range 20~20kHz use the Audio card with free software and make your own custom 10:1 probe with low inductance ground lead  for coil spring 2 pin probe. Hopefully you have Line Input.

 ref
Record on Audacity for exact Voltages and Spectrum Analyzer.up to +/-1V on Line in.

*Make a Logic Probe, "0", "1" with Vcc, Gnd and counter with 2^14 to LED.  Use 1 shot to extend short pulses and toggle. (flash)


text:
Q: Unable to connect to MongoDB using Embeded MongoDB using replicaSet for Junit test cases I am facing the following problem while connecting to embeded MongoDB with replicaSet for executing Junit test cases. I am getting the following exception.
[mongod output] 2021-03-06T23:28:13.202+0530 I CONTROL  [initandlisten] ** WARNING: This server is bound to localhost.

[mongod output] 2021-03-06T23:28:13.202+0530 I CONTROL  [initandlisten] **          Remote systems will be unable to connect to this server.

[mongod output] 2021-03-06T23:28:13.202+0530 I CONTROL  [initandlisten] **          Start the server with --bind_ip <address> to specify which IP

[mongod output] 2021-03-06T23:28:13.202+0530 I CONTROL  [initandlisten] **          addresses it should serve responses from, or with --bind_ip_all to

[mongod output] 2021-03-06T23:28:13.202+0530 I CONTROL  [initandlisten] **          bind to all interfaces. If this behavior is desired, start the

[mongod output] 2021-03-06T23:28:13.202+0530 I CONTROL  [initandlisten] **          server with --bind_ip 127.0.0.1 to disable this warning.

[mongod output] 2021-03-06T23:28:13.202+0530 I CONTROL  [initandlisten]

[mongod output] 2021-03-06T23:28:13.206+0530 I STORAGE  [initandlisten] createCollection: local.startup_log with generated UUID: 05d4a8b0-4709-4a0d-91fa-0de499c942a0

[mongod output] 2021-03-06T23:28:13.856+0530 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory 'C:/Users/mishrd5/AppData/Local/Temp/embedmongo-db-9c4148c7-97f4-498d-bf55-a03c88a38830/diagnostic.data'

[mongod output] 2021-03-06T23:28:13.857+0530 I STORAGE  [initandlisten] createCollection: local.replset.oplogTruncateAfterPoint with generated UUID: 3fd3b9bc-3f44-4975-ba81-8b995268f49d

[mongod output] 2021-03-06T23:28:13.879+0530 I STORAGE  [initandlisten] createCollection: local.replset.minvalid with generated UUID: a1e095da-9f04-4cda-bd3c-cda0297f4453

[mongod output] 2021-03-06T23:28:13.910+0530 I REPL     [initandlisten] Did not find local voted for document at startup.

[mongod output] 2021-03-06T23:28:13.910+0530 I REPL     [initandlisten] Did not find local Rollback ID document at startup. Creating one.

[mongod output] 2021-03-06T23:28:13.910+0530 I STORAGE  [initandlisten] createCollection: local.system.rollback.id with generated UUID: c82cb441-efd9-4605-abc5-c2a18bbb06c1

[mongod output] 2021-03-06T23:28:13.938+0530 I REPL     [initandlisten] Initialized the rollback ID to 1

[mongod output] 2021-03-06T23:28:13.938+0530 I REPL     [initandlisten] Did not find local replica set configuration document at startup;  NoMatchingDocument: Did not find replica set configuration document in local.system.replset

[mongod output] 2021-03-06T23:28:13.939+0530 I CONTROL  [LogicalSessionCacheRefresh] Sessions collection is not set up; waiting until next sessions refresh interval: Replication has not yet been configured

[mongod output] 2021-03-06T23:28:13.939+0530 I CONTROL  [LogicalSessionCacheReap] Sessions collection is not set up; waiting until next sessions reap interval: Replication has not yet been configured

[mongod output] 2021-03-06T23:28:13.939+0530 I NETWORK  [initandlisten] waiting for connections on port 27023

[mongod output] 2021-03-06 23:28:13.939  INFO 18616 --- [           main] d.f.embed.mongo.MongodExecutable         : start de.flapdoodle.embed.mongo.config.MongodConfigBuilder$ImmutableMongodConfig@6870c3c2
2021-03-06 23:28:14.023  INFO 18616 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[host:27021], mode=MULTIPLE, requiredClusterType=REPLICA_SET, serverSelectionTimeout='30000 ms', requiredReplicaSetName='rs0'}
2021-03-06 23:28:14.024  INFO 18616 --- [           main] org.mongodb.driver.cluster               : Adding discovered server host:27021 to client view of cluster
--------------------------------------
MongoClient : com.mongodb.client.internal.MongoClientImpl@53f0d09c
--------------------------------------
2021-03-06 23:28:14.092  INFO 18616 --- [           main] org.mongodb.driver.cluster               : No server chosen by com.mongodb.client.internal.MongoClientDelegate$1@5eabff6b from cluster description ClusterDescription{type=REPLICA_SET, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{address=host:27021, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
2021-03-06 23:28:28.297  INFO 18616 --- [ll'}-host:27021] org.mongodb.driver.cluster               : Exception in monitor thread while connecting to server host:27021

com.mongodb.MongoSocketException: host
    at com.mongodb.ServerAddress.getSocketAddresses(ServerAddress.java:211) ~[mongodb-driver-core-4.0.5.jar:na]
    at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:75) ~[mongodb-driver-core-4.0.5.jar:na]
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-4.0.5.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:127) ~[mongodb-driver-core-4.0.5.jar:na]
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117) ~[mongodb-driver-core-4.0.5.jar:na]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_261]
Caused by: java.net.UnknownHostException: host
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method) ~[na:1.8.0_261]
    at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:929) ~[na:1.8.0_261]
    at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1324) ~[na:1.8.0_261]
    at java.net.InetAddress.getAllByName0(InetAddress.java:1277) ~[na:1.8.0_261]
    at java.net.InetAddress.getAllByName(InetAddress.java:1193) ~[na:1.8.0_261]
    at java.net.InetAddress.getAllByName(InetAddress.java:1127) ~[na:1.8.0_261]
    at com.mongodb.ServerAddress.getSocketAddresses(ServerAddress.java:203) ~[mongodb-driver-core-4.0.5.jar:na]
    ... 5 common frames omitted

I provide below my code.
@Profile("test")
@ActiveProfiles("test")
@TestConfiguration
public class TestMongoDBConfig implements InitializingBean, DisposableBean {

    /** The executable. */
    private MongodExecutable executable;

    private MongoTemplate mongoTemplate;

    private MongodProcess node1Mongod;
    private MongodProcess node2Mongod;
    private MongodExecutable node1MongodExe;
    private MongodExecutable node2MongodExe;
    private int node1Port = 27021;
  private int node2Port = 27023;
    private static final String CONNECTION_STRING = "mongodb://%s:%d";
    private int port = 27021;

    @Override
    public void afterPropertiesSet() throws Exception {

//      IFeatureAwareVersion version = de.flapdoodle.embed.mongo.distribution.Versions
//              .withFeatures(new GenericVersion("4.0.0"), Version.Main.PRODUCTION.getFeatures());
//      IMongoCmdOptions cmdOptions = new MongoCmdOptionsBuilder().useNoPrealloc(false).useSmallFiles(false)
//              .master(false).verbose(false).useNoJournal(false).syncDelay(0).build();
//      port = Network.getFreeServerPort();
//      System.out.println("-------------------------");
//      System.out.println("Test Mongo PORT : "+port);
//      System.out.println("-------------------------");
//      IMongodConfig mongodConfig = new MongodConfigBuilder().version(version)
//              .net(new Net(port, Network.localhostIsIPv6()))
////                .replication(new Storage(null, "testRepSet", 5000))
//              .replication(new Storage(null, "rs0", 5000))
//            .configServer(true)
////            .withLaunchArgument("--replSet", "rs0")
////                .configServer(false)
//              .cmdOptions(cmdOptions).build();
//      MongodStarter starter = MongodStarter.getDefaultInstance();
//      executable = starter.prepare(mongodConfig);
//      executable.start();

        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        MongodStarter runtime = MongodStarter.getDefaultInstance();

        node1MongodExe = runtime.prepare(new MongodConfigBuilder().version(Version.Main.V4_0)
                  .withLaunchArgument("--replSet", "rs0")
                  .cmdOptions(new MongoCmdOptionsBuilder().useNoJournal(false).build())
                  .net(new Net(node1Port, Network.localhostIsIPv6())).build());
          node1Mongod = node1MongodExe.start();

          node2MongodExe = runtime.prepare(new MongodConfigBuilder().version(Version.Main.V4_0)
                  .withLaunchArgument("--replSet", "rs0")
                  .cmdOptions(new MongoCmdOptionsBuilder().useNoJournal(false).build())
                  .net(new Net(node2Port, Network.localhostIsIPv6())).build());
          node2Mongod = node2MongodExe.start();

    }

    /**
     * Mongo client.
     *
     * @return the mongo client
     */
//  @Primary
    @Bean(name = "test1")
    public MongoClient mongoClient() {
        MongoClient mongoClient = MongoClients.create(cs);
        System.out.println("--------------------------------------");
        System.out.println("MongoClient : "+mongoClient);
        System.out.println("--------------------------------------");

        MongoDatabase adminDatabase = mongoClient.getDatabase("admin");

          Document config = new Document("_id", "rs0");
          BasicDBList members = new BasicDBList();
          members.add(new Document("_id", 0)
                  .append("host", "localhost:" + node1Port));
          members.add(new Document("_id", 1)
                  .append("host", "localhost:" + node2Port));
          config.put("members", members);

          adminDatabase.runCommand(new Document("replSetInitiate", config));

        return mongoClient;
    }

    @Override
    public void destroy() throws Exception {
        executable.stop();
    }
}

Please ignore the commented code. I have also refered the follwoing links, but no success.
https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo/issues/257
Test @Transactional with Flapdoodle Embedded MongoDB in Spring Boot
Configuring flapdoodle embedded mongo with Mongodb version 4 and replica
Please help me.


text:
Q: How to style odd rows in a table in this vue.js example? I am trying to add style to every odd number of rows in a table.  But the example below fails.
template: `

test title

      [[ item.result ]]

`,

computed: {
  tdStyle() {
    return {
        'border': '1px solid #C0C0C0',
        'padding': '8px',
    };
  },
  tdGray() {
    return {
        'background-color': gray,
    };
  },

What's interesting to me is this example works with class.
[[ item.result ]]

So works with :class but not :style.
If there is not an easier solution, is there a way I can move this logic into a function and then call the function to color odd rows?

A: You can do that in pure CSS. There is absolutely no reason to put this in conditional code or JavaScript, which makes it much harder to maintain. Vue has a way to combine HTML templates, JSS and CSS into components but I'm no expert on that aspect.

.zebra tr:nth-child(even) {
  background: #eee;
}
.zebra tr:nth-child(odd) {
  background: #ccc;
}

foo

bar

baz

fizz

buzz

As to specifically why your code didn't work, vue uses :class to add classes conditionally. When passing a JavaScript object to :class, each key is understood as a class name, which is present if its value is true.
The :style attribute has a different special behavior where each key of the object passed is a CSS attribute. This is useful if, for example, you want to always set an attribute on an element, but its value is conditional.
Your code uses :style with things that aren't CSS attributes.

If you wanted to use it without setting up a CSS class, you'd need to do something like this. It's been a while since I haven't done vue though, and I would strongly advise against putting this kind of logic in HTML attributes.

Finally, your code is not even valid HTML with a div inside a table, which most certainly will cause issues as the browser doesn't know where to put the div and where to put the tbody.

A: While as the previous answer mentioned, yes you could probably do this using pure CSS (better IMO too), just wanted to answer your question on why class binding works but style does not.
If you look at the Vue docs, you will see that your syntax for style is not correct. For class, what you have is correct and it should look like this:

However, for binding style, you actually have to return the CSS styles as an object:

So in your scenario, the style object becomes this (assuming on an even index):
{
  tdStyle: true,
  tdGrey: false
}

This is obviously not valid CSS. If you want to actually put the values of the functions, I suggest you use the spread operator for object destructuring in ES6, and for a cleaner code, use the JS ternary operator as well:

Alternatively, if you don't want to add any more styles, you can omit the object syntax completely and use this:

In here, what basically happens is the binding says "if index is even, then return the result of tdStyle function, else return the result of tdGray function".
But of course as mentioned just CSS is the superior solution here. If you really want add some special styling that CSS can't help with, you are still better off using class binding instead of style, that way your CSS can live inside the style tag of your component:


text:
Q: How to find the network interface of a server listening on 0.0.0.0 in cpp in linux? I have a server written in cpp. It is listening on 0.0.0.0. Now i want to find the network interface from where the server receives the packet. Is there any way to do that?

A: *

*Use getsockname() to get the IP-address the socket descriptor receiving the packets is bound to.

*Then use getifaddr() to loop over the interfaces available, to find which one matches the IP-address found in the 1st step.


text:
Q: Problems with IBM Terraform provider: ibm_service_instance first of all: Invitation via https://cloud.ibm.com/schematics/slack appears to be not working. I did not get an invitation for schematics@slack on any on my mail accounts, so I post my questions here:
Terraform 0.13, ibm provider 1.23.1
1.) while trying to run the sample ibm-app (the CloudFoundry sample) from https://github.com/IBM-Cloud/terraform-provider-ibm/tree/master/examples/ibm-app, I noticed it needs an API key to run. Why is that? Why can't the schematics workspace provide its own? There are samples which run fine without the need of an IAM key. What's so special with CloudFoundry that I have to provide a key?
2.) A CloudFoundry service instance (see: https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs/data-sources/service_instance) creates a service instance in CloudFoundry and a service  outside with an arbitrary name. "terraform destroy" destroys only the service instance, but keeps the service outside of CloudFoundry untouched. Is that a bug? Is there a way to create a resource, then a CF service, and then bind that service to the resource (using terraform)?
3.) ibm_app (see: https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs/resources/app) takes a zip file as input. Why no resource (some github repo)? Furthermore, how do I access a private git repository @git.cloud.ibm.com? There appears a JWT token in terraform environment which can be fetched via data "ibm_iam_auth_token". But how do I use that to access a git repo? -- Of course I can always provide an access token, which is probably the right way to do it. But why can a devops pipeline access a private git.cloud.ibm.com repo but terraform can't? Which brings me to the last question:
4.) How do I create a devops pipeline via terraform in ibm cloud? -- Creating a toolchain works fine in aws. but what about ibm cloud?

A: *

*Due to IAM limitations, for CF and classic infrastructure resources, you need to provide the API key. More info here: https://cloud.ibm.com/docs/schematics?topic=schematics-schematics-limitations#provider-block

*Sounds like it could be a bug - can you open an issue for that here?: https://github.com/IBM-Cloud/terraform-provider-ibm/issues/. It appears there isn't a way to bind a service to a Cloud Foundry app with Terraform alone. We can treat this as a feature request.

*This sample shows how you can use a provisioner "local-exec" to prepare a app zip from a GitHub repo: https://github.com/IBM-Cloud/terraform-provider-ibm/blob/master/examples/ibm-app/main.tf. You'll need to use access tokens to access private repos.

*Use Schematics to first create a workspace based on your GitHub repo that holds your Terraform code. Next, navigate to the "settings" tab and press "Enable Continuous Delivery". This will create a toolchain for you powered by IBM DevOps Toolchains.


text:
Q: ggplot display geom_segment as a sequence of points I am trying to display some data, where I don't only need to display a point using geom_point, but also want to trace a line to it from the axis. I figured I can do it with geom_segment, but I want to display a sequence of discrete dots instead.
Say I have a data like this:
df2 <- data_frame(x = c("a", "b", "c" ,"d"), y = c(3:6))

# A tibble: 4 × 2
      x     y
  <chr> <int>
1     a     3
2     b     4
3     c     5
4     d     6

What I want to get is like the graph below, only having a dot in each of 4 variables between 0 and their value (with the desired points marked manually in red):
ggplot(df2, aes(x=x)) + geom_point(aes(y=y)) + geom_point(aes(y=0))

A: This works... you could wrap it up in a function to make it more generalizable if needed.
First we use expand.grid to create all combinations of x and 1:(max(y) - 1), join it to the original data, and filter out the unnecessary ones.
library(dplyr)
df3 = left_join(expand.grid(x = unique(df2$x), i = 1:max(df2$y - 1)),
          df2) %>%
    filter(i < y)

Once the data is constructed, the plotting is easy:
ggplot(df2, aes(x=x)) +
    geom_point(aes(y=y)) +
    geom_point(y = 0) +
    geom_point(data = df3, aes(y = i), color = "red") +
    expand_limits(y = 0)

I'm not sure if you actually want the dots to be red - if you want them to all look the same then you could use 1:max(df2$y) (omit the -1) and use <= in the filter to and then only use the resulting data frame.

A: If you wanted to use a data.table approach, using a similar expansion methodology you could use:
dt <- setDT(df2)
dt_expand<-dt[rep(seq(nrow(dt)),dt$y),]
dt_expand[,y2:=(1:.N),by=.(x)]
ggplot(dt_expand, aes(x=x)) + geom_point(aes(y=y2)) + geom_point(aes(y=0))

Note I didn't include the red coloring, but that is easily done if you want it

A: Here a solution in base R. The idea is to create 2 different datasets , one for red points:
dat1 <- do.call(rbind,Map(function(x,y)data.frame(x=x,y=seq(0,y)),df2$x,df2$y))

And another for the black points
dat2 <- do.call(rbind,Map(function(x,y)data.frame(x=x,y=c(0,y)),df2$x,df2$y))

Then the plot is just the juxtopsition of 2 layers of the same plot  but with different datas:
library(ggplot2)

ggplot(data=dat1,aes(x=x,y=y)) +
  geom_point(col="red") +
  geom_point(data=dat2)

A: Yet another option, which is similar to @Gregor's, in that it's creating a new data vector.
d <- data.frame(x = c("a", "b", "c" ,"d"), y = c(3:6))

new_points <- mapply(seq, 0, d$y)
new <- data.frame(new = unlist(lapply(new_points, as.data.frame)),
                     x = rep(letters[1:4], d$y + 1),
                     group = 1)

d <- merge(d, new, by = "x")
d$group <- as.factor(ifelse(d$y == d$new|d$new == 0, 2, d$group))

ggplot(d, aes(x, new, color = group)) +
    geom_point() +
    scale_color_manual(values = c("red", "black")) +
    theme(legend.position = "none")


text: Q: TXT to PDF in Java using Native lib I could not find anywhere an answer to that. Is it possible to create a PDF file from a String or txt file using only native libs in Java? If so, how can one do that?


text:
Q: Absolute error loss for a gamma random variable Let $X \sim \operatorname{Gamma}(2,1)$, I would like to minimize with respect to $a$
$$E|aX-1|=\int_0^{1/a}(1-ax)xe^{-x}dx+\int_{1/a}^\infty (ax-1)xe^{-x}dx$$
Is there some neat way to do this?
The only way I know is to use calculus on the RHS to find the minimum with respect to $a$.
By neat, I mean a way that use facts from probability or gamma function? Thanks.

A: Differentiate $\mathrm E(\,\mid aX-1\mid\, )$ with respect to $a$. The result is
$$
E(X\,;\,aX>1)-E(X\,;\,aX<1)=E(X)-2E(X\,;\,aX<1).
$$
If $X$ is Gamma$(2,1)$, this is zero when $t=1/a$ solves
$$
t^2+2t+2=\mathrm e^t,
$$
that is, for $a=0.374^-$.

A: (This is a not answer -see Didier's- rather a comment).
For $a>0$, $E( | a X  - 1 | ) = a E( | X - a^{-1}| )$  so the problem is equivalent to find $b>0 $  ($b= 1/a$) that minimizes $$ g(b) = \frac{E(|X-b|)}{b} = \frac{h(b)}{b} $$
All we know from  "facts from probability" is that the median of $X$ minimizes $h(b)$, but this does not lead to a solution of $g(b)$ (all that we can expect is that the minimum happens for some $b_0 > med(X) \approx 1.67$ ) but this is not very useful (the median of a gamma variable has not a closed form and the bound is not tight)


text:
Q: iOS 10.3.3 UIButton _intrinsicSizeWithinSize/_updateTitleView CoreFoundation crash I'm randomly getting this stack trace from some iOS 10.3.3 users:
-[_TtGCs26_SwiftDeferredNSDictionarySSP__ length]: unrecognized selector sent to instance 0x174421880

Fatal Exception: NSInvalidArgumentException
0  CoreFoundation                 0x183416fe0 __exceptionPreprocess
1  libobjc.A.dylib                0x181e78538 objc_exception_throw
2  CoreFoundation                 0x18341def4 __methodDescriptionForSelector
3  CoreFoundation                 0x18341af54 ___forwarding___
4  CoreFoundation                 0x183316d4c _CF_forwarding_prep_0
5  UIKit                          0x189a437d0 -[UIButton _updateTitleView]
6  UIKit                          0x1895bf828 -[UIButton tintColorDidChange]
7  UIKit                          0x189a5d9d8 -[_UITintColorVisitor _visitView:]
8  UIKit                          0x189a5e0bc _UIViewVisitorEntertainVisitors
9  UIKit                          0x189a5d1f0 _UIViewVisitorRecursivelyEntertainDescendingVisitors
10 UIKit                          0x189a5d2a0 _UIViewVisitorRecursivelyEntertainDescendingVisitors
11 UIKit                          0x189a5cb3c _UIViewVisitorEntertainDescendingTrackingVisitors
12 UIKit                          0x1895445a8 __45-[UIView(Hierarchy) _postMovedFromSuperview:]_block_invoke
13 Foundation                     0x183e51abc -[NSISEngine withBehaviors:performModifications:]
14 UIKit                          0x1895443b0 -[UIView(Hierarchy) _postMovedFromSuperview:]
15 UIKit                          0x1895502ac -[UIView(Internal) _addSubview:positioned:relativeTo:]
16 UIKit                          0x18954fbc8 -[UIView(Hierarchy) addSubview:]
17 UIKit                          0x18982d81c -[UIView _setTraitStorageSubviews:]
18 Foundation                     0x183e2c68c -[NSObject(NSKeyValueCoding) setValue:forKey:]
19 UIKit                          0x189846b78 -[UIView(CALayerDelegate) setValue:forKey:]
20 UIKit                          0x1899ccb50 -[_UIRelationshipTraitStorage applyRecordsMatchingTraitCollection:]
21 UIKit                          0x1899cb500 -[NSObject(_UITraitStorageAccessors) _applyTraitStorageRecordsForTraitCollection:]
22 UIKit                          0x189831364 -[UIView _traitCollectionDidChangeFromOldCollection:toNewCollection:scaleDidChange:]
23 UIKit                          0x189831488 -[UIView _wrappedProcessDidChangeRecursivelyFromOldTraits:toCurrentTraits:scaleDidChange:forceNotification:]
24 UIKit                          0x189ea84c8 -[UIView(AdditionalLayoutSupport) _withUnsatisfiableConstraintsLoggingSuspendedIfEngineDelegateExists:]
25 UIKit                          0x1898316ec -[UIView _processDidChangeRecursivelyFromOldTraits:toCurrentTraits:forceNotification:]
26 UIKit                          0x189545c50 -[UIView(CALayerDelegate) layoutSublayersOfLayer:]
27 QuartzCore                     0x186736274 -[CALayer layoutSublayers]
28 QuartzCore                     0x18672ade8 CA::Layer::layout_if_needed(CA::Transaction*)
29 QuartzCore                     0x18672aca8 CA::Layer::layout_and_display_if_needed(CA::Transaction*)
30 QuartzCore                     0x1866a634c CA::Context::commit_transaction(CA::Transaction*)
31 QuartzCore                     0x1866cd3ac CA::Transaction::commit()
32 QuartzCore                     0x1866cde78 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*)
33 CoreFoundation                 0x1833c49a8 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__
34 CoreFoundation                 0x1833c2630 __CFRunLoopDoObservers
35 CoreFoundation                 0x1833c2a7c __CFRunLoopRun
36 CoreFoundation                 0x1832f2da4 CFRunLoopRunSpecific
37 GraphicsServices               0x184d5d074 GSEventRunModal
38 UIKit                          0x1895adc9c UIApplicationMain
39 <myapp>                          0x10006bf9c main (main.m:14)
40 libdyld.dylib                  0x18230159c start

For some users
    -[UIButton _intrinsicSizeWithinSize:]
is substituted by
    -[UIButton _updateTitleView]
The app is using both Objective-C and Swift 3.
I'm not able to reproduce the crash on my devices/simulator.
Unfortunately I don't have any other information about the problem.
Did anybody face a similar problem?
TIA

A: I finally found out the source of the problem!
The crash is obtainable with the following code
NSArray *array = @[
    @{@"key": @1, @"name": @"Name1"},
    @{@"key": @2, @"name": @"Name2"},
    @{@"key": @3, @"name": @"Name3"}
];
NSString *title = array[1];
[button setTitle: title forState: UIControlStateNormal];

I was assigning the NSDictionary @{@"key": @2, @"name": @"Name2"} to title (with no warning), then I was passing the NSDictionary as a NSString to the [UIButton setTitle:forState:] method.
I fixed the issue redefining array as
NSArray<NSDictionary<NSString *, id> *> *array;

and changing the value I assigned to title from array[1] to array[1][@"name"].


text:
Q: Netsuite Data Information I am trying to integrate Netsuite and extract the data out of it. Need to establish a relation between Sales Orders, Items, and Invoices. Can anyone which objects store this information and how it's related?

A: Record types of Netsuite are the following:

*

*Entity - Customer, Employee, Partner, Vendor

*Item - Products (holds product related details)

*Transactions: SO, Invoice, Bill, Credit Memo, Return Auth, Rev Commit, Deposit, Cash Sales etc.

Relationship:
Customer -->SO <--- Item
SO --->Invoice -----> payment or refund
Please see the Netsuite schema browser for more detail
https://system.netsuite.com/help/helpcenter/en_US/srbrowser/Browser2016_1/schema/record/account.html