text:
Q: Adjusting Font-Size of ListItem in codebehind What i'm trying to achieve is to loop through a list and add items to a listbox with different types of styles in an ASP.NET application. so far I've got the following code in my aspx file:
in the header:
<style type="text/css">
        .list .Title
        {
            font-size: x-large;
        }
        .list .Title1
        {
            color:Red;
        }
        .list .Title2
        {
            color:Black;
        }
        .list .Title3
        {
            color:Green;
        }
         .list .Line
        {
            background-color:Black;
        }

    </style>

Somewhere In the body:
 <asp:ListBox ID="CurrentListBox" runat="server" Width="100%" Height="400" CssClass="list">
                                </asp:ListBox>

In the code Behind i do this whilst looping through the list items depending on a few factors it goes through one of these:
(I work in VB.NET but an answer in CSharp will do just aswell, i'll translate it)
item.Attributes.Add("class", "Title")

or
item.Attributes.Add("class", "Title1")

or
etc. etc. etc.
PROBLEM:
It does the colours and it changes it just fine. but the fontsize never changes only the colour gets through.
Maybe some extra information: it loops through this code at pageload.

A: Try
 CurrentListBox.Items[0].Attributes.Add("style", "font-size:x-large;");

Thanks


text:
Q: Storing integers from text file to an array I have a task to assign integers from a text file to an array in python.
I tried reading by lines and splitting, but none worked.
The task goes like this: we have an array
1 4 5 7 3 2 8 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 4 0 0 0 0 0

0 0 0 0 0 0 0 0 0 3 0 0 0 0

0 0 0 0 0 0 0 5 0 0 6 0 0 0

0 0 0 0 0 0 0 0 0 0 1 0 0 0

0 0 0 0 0 0 0 0 0 0 0 2 9 0

0 0 0 0 0 0 0 0 0 0 10 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 11

0 0 0 0 0 0 0 0 0 0 0 0 0 1

0 0 0 0 0 0 0 0 0 0 0 0 0 8

0 0 0 0 0 0 0 0 0 0 0 0 0 9

0 0 0 0 0 0 0 0 0 0 0 0 0 14

0 0 0 0 0 0 0 0 0 0 0 0 0 5

0 0 0 0 0 0 0 0 0 0 0 0 0 0

and this needs to be assigned to an array x in order to use it in further functions.

A: Do something like:
with open('my_raw_file.txt', 'r') as file:
    all_file = file.read().strip()  # Read and remove any extra new line
    all_file_list = all_file.split('\n')  # make a list of lines
    final_data = [[int(each_int) for each_int in line.split()] for line in all_file_list]  # make list of list and convert to int
    print(final_data)

A: if you don't mind numpy arrays and pandas:
import pandas as pd
integers = pd.read_csv('test.txt', sep=" ", header=None)

redpajama_set_name: RedPajamaStackExchange


text:
Q: transform:translate property not working properly with intersection observer API I was recently learning the intersection observer API to make some scroll animations and had a couple of issues.

*

*transform:translate property didn't work properly. I was trying to achieve a left to center slide while i scroll to that div, but that didn't happen. However if I apply transform:scale property or even opacity they work well.

*If I bypass a section with  'on scroll opacity transition' too quickly its behavior changes 180. I mean that if by default if I have set the opacity to increase from 0 to 1 on up to down scroll and I do this once and then scroll up fast the animations don't happen and as a result if I again scroll down things start to disappear(opacity:0) instead of appear(opacity:1), opposite to what I have set.

*** I have tried brave and chrome to see if it may work but no positivity****
code>>>>>>>>
Uploaded on codepen>>>link>>> https://codepen.io/Muneebthelearner/pen/PoRRgOE

// CARD ANIMATION ************

const card1 = document.querySelector(".firstcard");

const options = {
  root: null,
  threshold: 0.25
};

let observer = new IntersectionObserver(callback, options);
function callback(entries, observer) {
  entries.forEach((entry) => {
    if (!entry.intersectionRatio) {
      return;
    } else {
      entry.target.classList.toggle("after");
    }
    console.log(entry.target);
  });
}
observer.observe(card1);

// IMAGE ANIMATION ***********************

const building = document.querySelector(".building");
let imageobserver = new IntersectionObserver(imagecallback, options);
function imagecallback(entries, imageobserver) {
  entries.forEach((entry) => {
    if (!entry.intersectionRatio) {
      return;
    } else {
      entry.target.classList.toggle("show");
    }
    console.log(entry.target);
  });
}
imageobserver.observe(building);
@import url("https://fonts.googleapis.com/css2?family=Montserrat:wght@500&family=Roboto:wght@300;400&display=swap");
*,
*::before,
*::after {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f5e8c7;
  padding: 0.5rem 1rem;
}
.logo {
  max-width: 50px;
}
ul {
  display: flex;
  justify-content: space-between;
  list-style: none;
}
ul > * {
  padding: 0.5rem 1rem;
}
a {
  text-decoration: none;
  font-size: 1.1rem;
  font-family: "Roboto", sans-serif;
  color: black;
  font-weight: 300;
}

/* wolf-section */
.main {
  background: linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.7)),
    url("https://i.postimg.cc/d1McYFh7/wolves-2864647-1920.jpg");
  color: white;
  max-width: 100%;
  min-height: 100vh;
  background-position: center bottom;
  background-size: cover;
  display: grid;
  place-items: center;
  text-align: center;
}
.main-text {
  max-width: 600px;
}
.heading {
  font-size: 3rem;
  font-family: "Montserrat", sans-serif;
  line-height: 60px;
}
.about {
  font-family: "Roboto", sans-serif;
  font-weight: 300;
  line-height: 20px;
}
.one {
  padding: 0.5rem 1.5rem;
  margin: 1rem 0rem;
}
/*  Cards section */
.cards {
  padding: 2rem 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}
.firstcard,
.secondcard,
.thirdcard {
  width: clamp(200px, 250px, 100%);
  background-color: rgba(0, 0, 0, 0.7);
  padding: 0rem;
  margin:1rem 0rem;
  text-align: center;
}
.firstcard {
    /*transform: translateX(-150%);
    position: relative;
     left: -500px; */
  /* transform: scale(1.2); */
  opacity: 0;
}
.firstcard.after {
  /*  transform: translateX(0%);
     transform: scale(1); */
    /* left: 0px; */
  opacity: 1;
  transition: all 1s ease-in;
}
.title {
  text-align: center;
  font-size: 1.2rem;
  font-family: "Roboto", sans-serif;
  font-weight: 400;
  padding: 0.5rem 0rem;
  color: black;
  background-color: #afb4ff;
}
.about_animal {
  text-align: justify;
  padding: 0.5rem;
  font-family: "Roboto", sans-serif;
  font-weight: 300;
  color: white;
}
.donate {
  padding: 0.5rem 1.5rem;
  margin: 1rem 0rem 0.5rem;
}

/* TOO text section; */
.too_text {
  padding: 1rem;
  font-family: "Roboto", sans-serif;
  font-weight: 300;
}
.theory {
  font-size: 2rem;
  font-family: "Montserrat", sans-serif;
  text-align: center;
  padding: 1rem 0rem;
}
.building {
  max-width: 100%;
  opacity: 0;
  transition:  all 1.5s ease;
  transform: scale(1.1);
}
.building.show
{
    opacity: 1;
    transform: scale(1);
}

Home

Contact

About

Login

      WildLife is Looking for your love

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi sit beatae quidem, nemo quae excepturi nesciunt alias facilis deserunt nostrum!

    <button class="one">Login</button>
    <button class="one">Donate</button>

Animal X

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Et molestias iure fugiat quisquam vero voluptates qui corporis quod itaque porro?

    <button class="donate">Donate</button>

Animal Y

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Et molestias iure fugiat quisquam vero voluptates qui corporis quod itaque porro?

    <button class="donate">Donate</button>

Animal Z

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Et molestias iure fugiat quisquam vero voluptates qui corporis quod itaque porro?

    <button class="donate">Donate</button>

About Us

      Lorem, ipsum dolor sit amet consectetur adipisicing elit. Temporibus ullam quod dignissimos mollitia voluptates consectetur provident, enim quas sed. Labore aut, sequi commodi ex delectus expedita aperiam consequuntur maiores, eos adipisci quod similique suscipit rem illum quisquam ratione hic facilis dolorum minima pariatur? Sit, commodi quo consequuntur excepturi nesciunt perferendis deleniti nobis accusantium cupiditate, rerum architecto similique asperiores perspiciatis? Quo mollitia fugit esse ducimus est nisi enim exercitationem modi! Libero dolorum illo est, provident accusantium aut harum doloremque numquam, perspiciatis vitae, vel quaerat error dolor eveniet dicta dolores ex nobis suscipit impedit eligendi quis ut delectus! Quam maxime laudantium illo sequi sint soluta recusandae consequatur nam blanditiis eum ipsa tenetur vel iure aliquam, quae optio nemo ab aut! Recusandae consectetur id soluta eum temporibus aliquam neque, doloremque voluptatem consequatur assumenda quae eos facere dolorem necessitatibus nobis repudiandae beatae repellat minima similique voluptates, itaque expedita! Corporis at dolor cum eius tempora excepturi fugit, reiciendis aut debitis saepe eaque! Voluptatum, asperiores unde eveniet officiis officia ullam nam quasi debitis explicabo consequatur adipisci tenetur corrupti itaque possimus sequi dicta dolorum hic voluptate perspiciatis, repellat vel excepturi pariatur recusandae quis! Labore, incidunt, iusto accusantium sint dolore cupiditate voluptatem at consequuntur iure quasi obcaecati neque.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ullam totam ab, dolor doloribus facilis possimus quas veniam quidem. A quam quis eligendi dicta eaque dignissimos placeat molestiae nisi eum sint nostrum facere, deserunt provident illum, modi praesentium nulla similique. Voluptates vel nisi, et mollitia delectus obcaecati omnis modi unde? Quaerat maiores labore tempora quod voluptate! Optio, perspiciatis voluptatum dolores non atque corporis consequatur consectetur mollitia sapiente animi, rem rerum. Similique eaque neque quam debitis a autem? Atque illum autem quibusdam excepturi officiis adipisci debitis repellat quos inventore magni minima, obcaecati iure dignissimos, sed placeat
   Optio, perspiciatis voluptatum dolores non atque corporis consequatur consectetur mollitia sapiente animi, rem rerum. Similique eaque neque quam debitis a autem? Atque illum autem quibusdam excepturi officiis adipisci debitis repellat quos inventore magni minima, obcaecati iure dignissimos, sed placeat

Concerned classes:
1.firstcard
2.building


text:
Q: Shading the area bounded by graphs in TikZ Thanks to Torbjørn T.'s answer at Best way to generate a nice function plots in LaTeX?, there is an easy way to show multiple graphs using TikZ's datavisualization. Is there a way to shade i.e. fill in the region bounded by these graphs?

A: Try:
\documentclass{standalone}
\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}
\begin{document}
\begin{tikzpicture}
  \begin{axis}
    \addplot[name path=f] {x^2 - x +4};
    \addplot[name path=g] {x^2 - x};
    \addplot [
        fill=blue,
        fill opacity=0.2
    ]
    fill between[
        of=f and g
    ];
  \end{axis}
\end{tikzpicture}
\end{document}

Output:


text:
Q: Delphi: Alternative to JEDI Desktop Alert (balloon) Is there a good analogue/equivalent to JEDI Desktop Alert (a kind of a balloon in the right bottom corner of a desktop)?
Balloon hint cannot be showed like a stack (a new hint is on the top of others), but JEDI Desktop Alert can do it.
May be some one knows, why does a show event of that component fire twice instead of once? :)

Thank your for suggestions!

A: This might be a bit late, but below is a basic example of showing 5 stacked alert windows on top of each other in bottom right corner, using Jedi Desktop Alert.

unit Unit1;

interface

uses
  Winapi.Windows,
  Winapi.Messages,
  System.SysUtils,
  System.Variants,
  System.Classes,
  Vcl.Graphics,
  Vcl.Controls,
  Vcl.Forms,
  Vcl.Dialogs,
  Vcl.StdCtrls,
  JvDesktopAlert;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    procedure AddAlert(title, text: String; stack: TjvDesktopAlertStack);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.AddAlert(title, text: String; stack: TjvDesktopAlertStack);
Begin
  with TJvDesktopAlert.Create(self) do
  Begin
    AutoFree   := true;
    AlertStack := stack;
    HeaderText := title;
    MessageText := text;
    Execute(self.Handle);
  End;
End;

procedure TForm1.Button1Click(Sender: TObject);
var
  stack: TjvDesktopAlertStack;
begin
  stack := TJvDesktopAlertStack.Create(self);
  try
    AddAlert('title1', 'message1', stack);
    AddAlert('title2', 'message2', stack);
    AddAlert('title3', 'message3', stack);
    AddAlert('title4', 'message4', stack);
    AddAlert('title5', 'message5', stack);
  finally
    stack.Free;
  end;
end;

end.

A: TMS Software has TAdvAlertWindow, an "Outlook 2003, 2007 style alert window".

It's a commercial component, available separately or as part of the TMS Component Pack.
Update: The above image was taken from TMS website. As Andreas has pointed the font is not antialiased (it's a bitmapped font, probably MS Sans Serif). I've tested the trial version of the component and setting the font to Tahoma works as expected:


text:
Q: Is bundling (webpack/browserify) faster than going through a CDN? I was just curious if anyone had done any research into this matter.
At my place of work we have React, Bluebird, jQuery, and Lodash in every single one of our projects/bundles.
We use webpack to bundle all of these dependencies, but I'm not sure if it is actually worth it... I would think that a lot of these scripts would be cached on the user's browser.
Using the CDN and moving these packages out of the webpack bundle would decrease build times and simplify our build process a lot. We have to support IE8 so we have to run React through envify and ES3ify.
Has anyone done any research into how much the browser can leverage caching for common libraries?

A: Bundling reduces the number of TCP connections needed to download external content (JavaScript/CSS).  If your bundler also minifies the content, it additionally reduces the number of bytes the client needs to fetch.
Using a CDN places your content... whether or not you bundle it... closer to the web browser that is trying to download it.
For best results, use both.
Bundling is free, using a CDN is generally quite cheap.  If free is your only option, by all means bundle.  If you can budget a CDN as well, place your bundled content on the CDN.
UPDATE
Based on your comment - Do not self-host common dependencies that are hosted by high-traffic, public CDN's such as Google.  There is an excellent chance that a user already has what you need in cache.  See for example 3 reasons why you should let Google host jQuery for you.


text:
Q: pg_connect takes longer than 5 seconds? I have just setup a OpenBSD little personal development server running PHP with an almost-default(enabled debugging messages) php.ini and installed PostgreSQL with the default configuration.
Well, running this very simple code
$starttimer=time()+microtime();

$dbconn = pg_connect("host=localhost port=5432 dbname=earlzblog_001 user=xxx password=xxx")
    or die("Couldn't Connect".pg_last_error());
pg_close($dbconn);
$stoptimer = time()+microtime();
echo "Generated in ".round($stoptimer-$starttimer,4)." s";

the result is "generated in 6.xxs. Why is it taking 6 seconds to simply make a database connection? Using PgAdmin3, the connections don't take any time at all.
Am I suppose to be using persistent connections here? Or unix-sockets or something?

A: Does this also happen if you
a) use 127.0.0.1 instead of localhost
  b) use a unix socket
to connect to the postgresql server?
Is your OpenBSD, DNS, Postgresql server and/or php configured to use ipv6?

A: Try, from the same machine, telnet localhost 5432 to see if the problem is PostgreSQL-specific or not.


text:
Q: MySQL won't start in Debian I'm very new to the Linux world. I have been trying to connect to MySQL but kept getting various errors.  Below are the three commands I started in that order.
Running the second command was a result of me researching about the error generated in the first command and etc.
Can someone take a look at the below and provide me with some help/suggestion?
Also I can't find the "mysqld.sock" anywhere on the system.
Thank you

------------------ root@MYSQL011:/tmp# mysql -u root -p Enter password: ERROR 2002 (HY000): Can't connect to local MySQL server
  through socket '/var/run/mysqld/mysqld.sock' (2) root@MYSQL011:/tmp#
------------------ root@MYSQL011:/tmp# service mysql status
? mysql.service - LSB: Start and stop the mysql database server daemon
  Loaded: loaded (/etc/init.d/mysql)    Active: failed (Result:
  exit-code) since Tue 2017-04-18 11:00:41 EDT; 23min ago   Process:
  5360 ExecStart=/etc/init.d/mysql start (code=exited, status=1/FAILURE)
Apr 18 11:00:41 MYSQL011 mysql[5360]: Starting MySQL database server:
  mysqld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  failed! Apr 18 11:00:41 MYSQL011 systemd[1]: mysql.service: control
  process exited, code=exited status=1 Apr 18 11:00:41 MYSQL011
  systemd[1]: Failed to start LSB: Start and stop the mysql database
  server daemon. Apr 18 11:00:41 MYSQL011 systemd[1]: Unit mysql.service
  entered failed state.
------------------ root@MYSQL011:/tmp# journalctl -xn
-- Logs begin at Wed 2017-04-12 11:02:35 EDT, end at Tue 2017-04-18 11:20:22 EDT. -- Apr 18 11:00:41 MYSQL011 mysql[5360]: Starting MySQL
  database server: mysqld . . . . . . . . . . . . . . . . . . . . . . .
  . . . . . . . failed! Apr 18 11:00:41 MYSQL011 systemd[1]:
  mysql.service: control process exited, code=exited status=1 Apr 18
  11:00:41 MYSQL011 systemd[1]: Failed to start LSB: Start and stop the
  mysql database server daemon.
  -- Subject: Unit mysql.service has failed
  -- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
-- Unit mysql.service has failed.
-- The result is failed. Apr 18 11:00:41 MYSQL011 systemd[1]: Unit mysql.service entered failed state. Apr 18 11:06:23 MYSQL011
  sshd[5175]: pam_unix(sshd:session): session closed for user xyz Apr 18
  11:17:01 MYSQL011 CRON[6116]: pam_unix(cron:session): session opened
  for user root by (uid=0) Apr 18 11:17:01 MYSQL011 CRON[6117]: (root)
  CMD (   cd / && run-parts --report /etc/cron.hourly) Apr 18 11:17:01
  MYSQL011 CRON[6116]: pam_unix(cron:session): session closed for user
  root Apr 18 11:20:22 MYSQL011 systemd[1]: Starting Cleanup of
  Temporary Directories...
  -- Subject: Unit systemd-tmpfiles-clean.service has begun with start-up
  -- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
-- Unit systemd-tmpfiles-clean.service has begun starting up. Apr 18 11:20:22 MYSQL011 systemd[1]: Started Cleanup of Temporary
  Directories.
  -- Subject: Unit systemd-tmpfiles-clean.service has finished start-up
  -- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
-- Unit systemd-tmpfiles-clean.service has finished starting up.
-- The start-up result is done. root@MYSQL011:/tmp#


text:
Q: Split a string on different substrings, but conserve those substrings I'm trying to split the following string:
Hello how are you
Foo bar hello

Into
"Hello", " how", " are", " you", "
", " Foo", " bar", " Hello"

Is this possible?

A: Don't make things harder than you have to. Use preg_split() with the PREG_SPLIT_DELIM_CAPTURE flag, and capture the
:
$str = 'Hello how are you
Foo bar hello';
$array = preg_split( '/\s+|(
)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r( $array);

Output:
Array
(
    [0] => Hello
    [1] => how
    [2] => are
    [3] => you
    [4] =>

    [5] => Foo
    [6] => bar
    [7] => hello
)

Edit: To include the space in the following token, you can use an assertion:
$array = preg_split( '/(?:\s*(?=\s))|(
)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);

So, the goal of preg_split() is to find a spot in the string to split. The regex we use consists of two parts, OR'd together with |:

*

*(?:\s*(?=\s)). This starts off with a non-capturing group (?:), because when we match this part of the regex, we do not want it returned to us. Inside the non-capturing group, is \s*(?=\s), which says "match zero or more whitespace characters, but assert that the next character is a whitespace character". Looking at our input string, this makes sense:
Hello how are you
Foo bar hello
     ^   ^

The regex will start from left to right, find "Hello{space}how", and decide how to split the string. It tries to match \s* with the restriction that if it consumes any space, there needs to be one space left. So, it breaks up the string at just "Hello". When it continues, it has " how are youFoo bar hello" left. It starts the match again, trying to match from where it left off, and sees " how are", and does the same split as above. It continues until there are no matches left.

*Capture
, with (
). It is captured because when we match this, we want to keep it in the output, so capturing it along with the PREG_SPLIT_DELIM_CAPTURE causes it to be returned to us when it is matched (instead of being completely consumed).
This results in:
array(8)
{
    [0]=> string(5) "Hello"
    [1]=> string(4) " how"
    [2]=> string(4) " are"
    [3]=> string(4) " you"
    [4]=> string(4) "
"
    [5]=> string(3) "Foo"
    [6]=> string(4) " bar"
    [7]=> string(6) " hello"
}

A: Not pretty, but simple enough:
$data = 'Hello how are you
Foo bar hello';
$split = array();
foreach (explode('
', $data) as $line) {
  $split[] = array_merge($split, explode(' ', $line));
  $split[] = '
';
}
array_pop($split);

print_r($split);

Or version 2:
$data = 'Hello how are you
Foo bar hello';
$data = preg_replace('#\s|(
)#', '**$1**', $data);
$split = array_filter(explode('**', $data));
print_r($split);

A: This is how I'd do it:

*

*Explode the string with space as a delimiter

*Loop through the parts

*Use strpos and check if part contains the given tag --
 in this case

*If it does, explode the string again with the tag as the delimiter

*Push all the three items into the result array

*If it doesn't, then push it into the result array

Code:
$str = 'Hello how are you
Foo bar hello';
$parts = explode(' ', $str);
$result = array();

foreach ($parts as $part) {
    if(strpos($part, '
') !== FALSE) {
        $arr = explode('
', $part);
        $result = array_merge($result, $arr);
        $result[] = "
";
    }
    else {
        $result[] = $part;
    }
}
print_r($result);

Output:
Array
(
    [0] => Hello
    [1] => how
    [2] => are
    [3] => you
    [4] => Foo
    [5] =>

    [6] => bar
    [7] => hello
)

Demo!

A: Here is a brief solution. Replace
 by (space
 space) and split using space:
<?php
   $newStr=str_replace("
","
 ","Hello how are you
Foo bar hello");
   $str= explode(' ',$newStr);
?>

Output of print_r($str):
(
    [0] => Hello
    [1] => how
    [2] => are
    [3] => you
    [4] =>

    [5] => Foo
    [6] => bar
    [7] => hello
)

A: Borrowing the preg_split pattern from @nickb's answer:
<?php
$string = 'Hello how are you
Foo bar hello';

$array = preg_split('/\s/',$string);

foreach($array as $key => $value) {
    $a = preg_split( '/\s+|(
)/', $value, -1, PREG_SPLIT_DELIM_CAPTURE);
    if(is_array($a)) {
        foreach($a as $key2 => $value2) {
            $result[] = $value2;
        }
    }
}

print_r($result);
?>

Output:
Array
(
    [0] => Hello
    [1] => how
    [2] => are
    [3] => you
    [4] =>

    [5] => Foo
    [6] => bar
    [7] => hello
)


text:
Q: What's the meaning of Neo4j's 'Variable length relationships'? In the page
Neo4j Cypher 3.3.1 MATCH
The section 'Variable length relationships' puzzled me.
The example:
MATCH (martin { name: 'Charlie Sheen' })-[:ACTED_IN*1..3]-(movie:Movie)
RETURN movie.title
Return 3 rows with a repetition of 'The American President'.
And if i change 3 to 2, return only one row of 'Wall Street'. Why is that? And what's the meaning of minHops and maxHops in the section?

A: This has to do with the number of relationships allowed to be traversed in the pattern.
As an example, for a social network graph, this would represent matching to all your friends:
MATCH (me:Person{id:123})-[:FRIEND]-(friend)

This represents friend-of-a-friend:
MATCH (me:Person{id:123})-[:FRIEND]-()-[:FRIEND]-(friendOfFriend)

This is the same thing but with variable-length relationships, showing that you want to traverse a :FRIEND relationship twice.
MATCH (me:Person{id:123})-[:FRIEND*2]-(friendOfFriend)

We can set a minimum and a maximum number of hops:
MATCH (me:Person{id:123})-[:FRIEND*1..3]-(friend)

This will return all nodes that can be reached by traversing at least one :FRIEND relationship, and at most 3 :FRIEND relationships.
If we set 0 as a lower bound, then the starting node me will also be included in the results for friend
MATCH (me:Person{id:123})-[:FRIEND*0..3]-(friend)

As for the example in the documentation, if we changed that query to return the paths rather than just the end nodes:
MATCH path = (charlie:Person { name: 'Charlie Sheen' })-[:ACTED_IN*1..3]-(movie:Movie)
RETURN path

you would see that there is one path of length 1 that ends on the node for Wall Street, and there are two distinct paths of length 3 that end on The American President.

A: it's the number of path, not the number of nodes.
1..3 means that 1 or 2 or 3 steps to another node that match (movie:Movie).


text:
Q: mobile device managment My requirement is i need to propose Mobile Device management(MDM) tool to the customer which will have all required features(Device Registration,Permissions to the device, Push mobile apps to the device etc )
FYI : The MDM tool should support IPHONE, ANDROID, BlACKBERRY, SYMBIAN & WINDOWSPHONE
Is there any MDM tool in the market which i can download and install freely.
Thanks
RVS

A: Free MDM solutions may exist : http://www.spiceworks.com/free-mobile-device-management-mdm-software/
Yet I am not sure that this may be a viable solution for your Clients.
For a non-exhaustive list of MDM solution providers:  http://www.enterpriseios.com/wiki/Comparison_MDM_Providers
Note : MobileIron also offers an On-Premise solution where the Virtual Smartphone Platform and eventual Integrated Sentries are installed in the client's network infrastructure (note : on-premise). Also, if the client does opt for the Connected Cloud solution, the VSP only is hosted on the Cloud.
In other words, there is the possibility to implement a Standalone Sentry (which can NOT be hosted on the Cloud) in the client's infrastructure to encrypt all data outgoing to the VSP, this is known as a Hybrid solution. The possibility of implementing a Standalone Sentry hosted on the Cloud is 'scheduled' for late 2014.

A: I think we have tools like ZENPRISE which supports all the major Device vendors.
It seems the above tool is bit costlier, they are charging $35 per user.
we have another solutions like MAAS360 & MOBILEIRON but they are Cloud based (all employee details will be stored remotely). Most of the customers prefer local installation as they do not want disclose their company information.
My Question is, are there any tools like zenprise which are much freely/cheaper than this tool ?
Thanks
RVS

A: I was searching through the web, looking for free MDM solutions to compile a list. I landed on this page and it helped me with sorting out Spiceworks, so I thought it would be good to do my bit by submitting the list that I compiled.
There are 5 free MDM software that I was able to find out that actually provide free service, although some have restricted functionality.

*

*Miradore

*Spiceworks

*Desktop Central

*Relution

*AppTec EMM
Well, I couldn't write about them all here; already took a lot of time to compile and write about the features made available for free. Here is a link where I go into much greater detail.: 5 Free Mobile Device Management Software


text:
Q: PyCharm: JavaScript files under src directory locked I'm working on a Django 1.4.x project in PyCharm 3.0 on OS X Mountain Lion.  My project is in its own virtualenv.
For some reason, I can't edit any JavaScript files in any Django app found in the src directory (under External Libraries in the project browser).  It doesn't seem to matter what the permissions are or whether the file was created by PyCharm or something else.  Other editors are able to make changes to the files without issue
I've tried locking/unlocking the file in the lower right corner.  Also, the JS icon on the tab at the top does have a lock on it, but I can't interact with it.
My coworker has the same problem.
I've been using PyCharm for 2 years but only recently updated from 2.x to 3.
Apps in my src directory:
beanstalkd
coffin
django-account
django-amc-ldap
django-cache-machine
django-cachecow
django-categories
django-chosen
django-ckeditor
django-contact-form
django-cropduster
django-curated
django-dart
django-fatpages
django-forms-builder
django-gcm
django-google-auth
django-grappelli
django-haystack
django-ios-notifications
django-locking
django-omniture
django-partner-feeds
django-push-notifications
django-sentry
django-taggit
django-twitter-feed-cache
ge-admin-login-captcha
ge-contact
ge-content-utils
ge-events
ge-feeds
ge-gbc
ge-migration
ge-newsletters
ge-newsml
ge-organizations
ge-tsp-ticker
genericadmin
pip-delete-this-directory.txt
pybeanstalk
redis
revision
south

A: We updated to PyCharm 3.0.2, and it works now.  Somewhere in the last two patches this was resolved.
(Note: we had tried to patch before, but the automated updated didn't actually patch it for some reason.  I had to download the new version from the website and reinstall.)


text:
Q: Wildcard SSL Certificate on Wildcard Subdomain in Plesk - wrong certificate served to browser I have a new Plesk 12 installation. I have configured a domain (example.com) with hosting that also requires wildcard subdomains.
To achieve this I had to create a vhost.conf file with
ServerAlias *.example.com

This works and I can go to anything.example.com with no issue.
I purchased a wildcard SSL certificate for *.example.com and successfully installed it.
If I go to https://example.com, it works perfectly and shows the correct certificate, however if I go to https://anything.example.com it tells me the connection is untrusted, when I view the certificate, it shows the Parallels Plesk self certified certificate and not my purchased certificate.
I created a vhost_ssl.conf with
ServerAlias *.example.com
ServerAlias *.example.com:443

If I add an exception, then I am taken to the correct place, albeit with the incorrect certificate.
Of course I have executed httpdmng --reconfigure-domain example.com and also tried a full reboot.
In summary:
http://example.com - works
http://anything.example.com - works
https://example.com works with my certificate
https://anything.example.com has Parallels certificate but routes to correct page

A: How about create same directive for nginx?
cat /var/www/vhosts/system/domain.tld/conf/vhost_nginx.conf
server_name  *.domain.tld;
Actually all this can be done from Plesk GUI:


text:
Q: TestNG - Is it possible to use AnnotationTransformer with dataProvider? I am writing functional tests using TestNG, and I have a few dozens of similar tests with different data. I would like to use DataProvider to reduce repeating code.
But some of those tests pass, some fail (due to a known defect). I want to disable failing tests until they are fixed, so they don't spoil whole picture of test run.
I see that AnnotationTransformer can change test annotations dynamically. Can AnnotationTransformer disable test only with some of the data sets? Or will it disable test with all provided data and it is better not to change anything?
Thanks in advance.

A: Why not simply put these failing tests in a group, say "broken", and exclude that test from your runs? Much simpler than using an annotation transformer, and the reports will show you which groups were excluded, so there is no risk to miss any when comes the time to ship.


text:
Q: How do I use clearInterval method let timer = setInterval(function() {
  const startDate = new Date();
  const endtDate = new Date("June 11 ,2021 10:12:00");
  let timeDiffernceObj = getTimeDiffernce(startDate, endtDate);
  timerDayEl.textContent = timeDiffernceObj.rDays;
  timerHourEl.textContent = timeDiffernceObj.rHours;
  timerMinEl.textContent = timeDiffernceObj.rMin;
  timerSecEl.textContent = timeDiffernceObj.rSec;

}, 1000);

clearInterval(timeDiffernceObj);

A: welcome to SO. You can use the following to clear the set interval.
clearInterval(timer);


text:
Q: How do you find out how much data has been transferred over Wifi, 3G or EDGE on Android? I'm trying to write an Android widget that shows how much data has been transferred over 3G/WIFI/EDGE but I can't seem to find the API call, even though other widgets do this.  Does anyone know what the API calls are to get the data usage?

A: Ah, found it, android.net.TrafficStats.


text:
Q: Change Countdown Download button to text display button I want to create a countdown button that will show hidden text after a certain time.
Here is the code about downloading files after 5 seconds.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="style.css">
  <title>Download Button With Timer</title>

      Download Now

Now I want to change it to a button, which will show a text after 5 minutes and can be put in WordPress post, but I don't know how to do it.
Please help me.

A: Here is the code to put in wordpress, it will display text after click and wait for a few seconds. But I don't know why it doesn't work.
This code is used for the button

 BUTTON CHỈ HIỆN MẬT KHẨU KHI TÌM TỪ KHÓA "SHARE COOKIES NETFLIX" TRÊN GOOGLE

This code is put in the body of wordress


text:
Q: Unbounded memory growth after Rack::Timeout in a puma Rails app We're using Ruby 2.3.3 with a Rails 5.0 app, running on puma 3.8.2, and rack-timeout 0.4.2.
We get semi frequent Rack::Timeout exceptions that have no ill effect.  Occasionally though, something bad will happen that causes a slew of timeouts, and after that point, the puma worker process seems to just keep generating more and more live objects.  GC appears to still be running - at least, NewRelic is still reporting time spent in GC - but it doesn't seem to be having much effect:

The worker process keeps serving requests, but gets slower & slower as the heap size goes up, before eventually dying with out-of-memory errors.
I know this is quite a vague question, but I wondered if anyone had run into anything similar.  Any tips for diagnosing it further?


text:
Q: DropDownlist returning first item always aspx page has a UC. in aspx.cs
if(!isPostBack){
    UC.DataBind();
 }

this UC also has a usercontrol UC1. In UC.ascx.cs
 public void DataBind(){
   UC1.DataBind();
 }

in UC1
public void  DataBind(){
   List<Registeration> list = ... VAlues from database;
   dropdownlist1.DataSource = list;
   DropDownList1.DataTextField = 'username';
   DropDownList1.DataValueField = 'username';
   DropDownList1.databind();
}

public void button1_click(){
    string selectedValue = DropDownList1.SelectedItem.Text;
 }

Problem : the value of string selectedValue is always coming out of the first item....
Comments: DropDownList is in updatePanel

A: Try populating the DropDownLost1.DataValueField in addition to the DataTextField.  Because it's not assigned, it might be empty for all items in the rendered DropDown.  To check this, you could look at the rendered HTML in FireBug to see what is showing up.

A: It seems you are doing everything right, but you need to also add the isPostBack() on your usercontrol.


text:
Q: count letter from txt file in python Files contain below letter.
A A- C F C C B- B A A A- B B+ B+ B+ C C- B- A A A F. I need to read the file and get the below output.
6 students got A
2 students got A-
3 students got B+

and so on, so far i am able to go through the file but i am not able to count it from the sting, can some one please guide me.
infile = open('grades.txt')
content = infile.read()
for char in content:
    print (char, end=' ')

i get the output as below
A   A -   C   F   C   C   B -   B   A   A   A -   B   B +   B +   B +   C   C -   B -   A   A   A   F
Can someone please guide me how i can count the occurance.
thanks.

A: Since it looks like a homework problem I'll just give a hint.
c=Counter("A A- C F C C B- B A A A- B B+ B+ B+ C C- B- A A A F".split())
c.most_common()
[('A', 6), ('C', 4), ('B+', 3), ('B', 2), ('F', 2), ('B-', 2), ('A-', 2), ('C-', 1)]


text:
Q: How to create an interceptor for errors to make another call? I'm getting a 401, because token has expired, so I need to renew the token with another call and then do the call again, is there an easy way instead of doing :
disposable = loginService.login(
                UserToLoginRequest(
                    input_email_login.text.toString(),
                    input_password_login.text.toString(),
                    generateRandomDeviceInfo()
                )
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    { result ->
                        //It works
                    },
                    { error -> if(error.code == 401) renewAccessToken() }
                )

The thing is that I want to do something like this guy : Refreshing Oath token, but if it's possible to call again the same endpoint with the same parameters.
Example
getApple(1) <-- return info of apple id 1
The result is 401 <-- can't do the call without refreshing the accessToken    refreshAccessToken()
Automatically call getApple(1) without disturbing the user

A: class Inceptor : Interceptor {
    internal var token: String?=null
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {

        var request=chain.request()
        request=request.newBuilder().build()

        val response=chain.proceed(request)

                if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    // get a new token (I use a synchronous Retrofit call)

                        val requestBody=FormBody.Builder()
                                .add("UserName", "abcd")
                                .add("Password", "*****")

                                .build()
                        val newRequest=request.newBuilder()
                                .url("Put your url")
                                .post(requestBody)
                                .build()
                        val tokenRefreshResponse=chain.proceed(newRequest)
                        val newRetryHttpUrl=request.url()
                        if (tokenRefreshResponse.code() == HttpURLConnection.HTTP_OK) {
                            val retryOriginaResponseBody: RequestBody

                            val builder=FormBody.Builder()
                            retryOriginaResponseBody=builder.build()
                            val retryRequest: Request
                            if (request.method() == "POST") {
                                retryRequest=request.newBuilder()
                                        .url(request.url())
                                        .post(retryOriginaResponseBody)

                                        .build()
                            } else {
                                retryRequest=request.newBuilder()
                                        .url(newRetryHttpUrl)

                                        .build()
                            }
                            val retryResponse=chain.proceed(retryRequest)
                            return retryResponse
                        } else {
                            return tokenRefreshResponse
                        }

                    }

        }
        return response
    }
}


text:
Q: Sheaf of sections vanishing at a point is $\Gamma(E) \otimes I_p$ Notation:

*

*$E$ is a vector bundle with sheaf of sections $\Gamma(E)$.

*$I_p$ is the sheaf of regular functions on the base space vanishing at a point $p$.

*$\Gamma_p(E)$ is the sheaf of sections of $E$ which vanish at a point $p$.

Is it true that $\Gamma_p(E) \simeq \Gamma(E) \otimes I_p$?
How about in the case where the base space is an algebraic curve?

I tried to define a map $I_p\otimes \Gamma(E) \rightarrow \Gamma_p(E)$ by $f\otimes s \mapsto fs$ but it's not clear to me that it's an isomorphism.
I also tried seeing $\Gamma_p(E)$ as the kernel of the evaluation map $\Gamma(E) \rightarrow E$. The resulting quotient is a skyscraper sheaf supported at $p$, right? Does that mean anything?

Context: I'm looking through a proof of Grothendieck's Splitting Theorem, in C. Okonek's book Vector Bundles on Complex Projective Spaces. The base space is $\mathbb{P}^1$, and he has a global section $s$ with $s(p)=0$. He  claims that $s$ "is" in $H^0(\Gamma(E)\otimes I_p)$. Note that in this case, $I_p \simeq \mathcal{O}(-1)$, which maybe makes a difference.

A: Yes, it is true, and the above defined morphism is indeed an isomorphism.
A morphism of sheaves is an isomorphism if and only if it induces an isomorphism at each stalk, thus one can reduce the discussion to an open covering $\{U_\alpha\}$ such that for each $\alpha$, $\Gamma(E)|_{U_\alpha}$ is a free $\mathcal{O}_x|_{U_\alpha}$ module. But for a free module it is not hard to verify that the defined map is an isomorphism, and we are done.


text:
Q: HTML POST method not displaying result I am trying to get the result to displayed in web but only get the param specified in the html code and not the actual entry that was made with the form.
The form takes in a string and then should be displayed as a result, but I only get the output below.
I am new to this so any guidance please.
@app.route('/dibble2', methods=["GET", "POST"])
def dibble2():
    if request.method == "POST":
        input1 = None
        input1 = str(request.form["input1"])
        if input1 is not None:
            result = is_create_ds(string1)
            return render_template("outco.html", result = result)

    return render_template("inco.html")

Output I get displayed once you submit the entered string is:

Result Check: {result}

It should output something like the following:

Result Check: Alright

Here is the html code it calls:

Result Check: {result}

Try Again

A: Just saw somewhere now that I needed double braces in the HTML file.
Now it works.

Result Check: {{result}}

Try Again


text:
Q: How should I handle two crons that update the database? I'm working on a Bitcoin-clone block explorer (specifically Mincoin) which has a block timer of about 1 minute. For those unfamiliar with Bitcoin, basically a new data structure called a block is propagated to the network about every minute. A block itself holds a lot of information, but three things are the most important:

*

*The previous block before it

*The next block in the chain

*A data structure containing transactions on the network

So sometimes in Bitcoin there is a "reorganization" which means the network finds that some of the most recent blocks are not valid and it switches over to another miner's branch.
At the moment every 1 minute I get all of the new blocks from the network and I store them into my database. However when a reorganization happens I was previously unable to delete and re-do the block structure of my database.
Now that I've written that functionality in, I'm encountering a new problem. I've got a function that looks in the past 100 blocks and checks if the hash of the block is the same as what my Mincoin client reports. If there was a reorganization, then some blocks will be different. I find the first block that is different and I delete from the database the block before it (so that block can point to the correct new one that will be found), the block itself, and all records of all blocks and transactions that happen after it, then rebuild from there.
The problem is the process of finding and deleting each transaction within the deleted blocks takes more than one minute because of the large amount of data, even though the fields I'm searching on are indexed. So I'm worried that the 1 minute cron I've put on the program will cause a problem where it starts to write again from the database at the same time the process of deleting from the rebuilding function is happening.
I'm using PHP and PDO so I have a PDO transaction for the rebuilding function, but this just adds more confusion. If the PDO transaction starts deleting records, then during that process a new cron finds some new blocks and writes them to the database, then the PDO transaction ends, which data will be stored? Will it cause an error? How is the best way to handle this -- should I write some field into the database that controls the regular cron (simply put a switch 0 or 1 for on and off) and keep the switch disabled while the rebuilding function is doing its thing?
I'm not sure how to structure the flow of this program to ensure I am not causing my database to have inaccurate data in it.

A: Here is one possible solution: instead of putting your jobs directly into the cron list, create a queueing mechanism which starts jobs sequentially and does not start a new job before the previous one has not ended. The advantage is that you don't to change anything in your database and don't need to provide any locking fields. There are several solutions possible to implement such a queue, for example, you could use cron to trigger the queue management, or to add the same job every minute to queue (whilst other jobs are added just once or in different time intervals).


text:
Q: grouper with a chunk size sequence in python? I have a generator that I want to iterate through at two levels. The first level is unevenly spaced, then I want to chunk the next level into groups of 5, say. I need it to be memory efficient and work on generator inputs, so I'm doing something like the following. I have to think there may be a better way? In particular, I don't want the trailing Nones in the uneven length results.
import itertools

def dynamic_grouper(iterable, intervals):
    for i in intervals:
        inner_iter = list(itertools.islice(iterable, i)) # this is a "group"
        yield inner_iter

iterable = iter(xrange(100))
chunk_sizes = [22,30,38,10]

for i,group in enumerate(dynamic_grouper(iterable, chunk_sizes)):
    args = [iter(group)] * 5
    for item in itertools.izip_longest(fillvalue=None, *args):
        print "Group %i" % i
        print "Items %s" % list(item)

A: To avoid the Nones, you could use chunks:
def chunks(seq, n):
    # https://stackoverflow.com/a/312464/190597 (Ned Batchelder)
    """ Yield successive n-sized chunks from seq."""
    for i in xrange(0, len(seq), n):
        yield seq[i:i + n]

for i,group in enumerate(dynamic_grouper(iterable, chunk_sizes)):
    for item in chunks(group, 5):
        print "Group %i" % i
        print "Items %s" % list(item)


text:
Q: Dynamic Dual List Box with django I'm try to realize a dual Dynamic Dual List Box with django. I try to adapt this jquery plugin:
https://www.jqueryscript.net/form/Dual-List-Box-Multi-Selection.html
but it doesn't work: button it seems doesn't be cliccable.
This my code:
forms.py
from django import forms
from station.models import Station

station_all=Station.objects.all()

class VdlForm(forms.Form):
    vdl_name = forms.CharField(label='nome virtual data logger', max_length=20,
                                 widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'nome vdl'}))
    stations = forms.ModelMultipleChoiceField(queryset=station_all)
    selected_stations = forms.ModelMultipleChoiceField(queryset=Station.objects.none())

views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import VdlForm

def new_vdl(request):
    template_name = 'vdl.html'
    heading_message = 'Add a new vdl'

    if request.method == 'POST':
        form = VdlForm(request.POST or None)
        if form.is_valid():
            vdl_name = form.cleaned_data.get("vdl_name")
            stations = form.cleaned_data.get("stations")

        return HttpResponseRedirect('new_vdl')

    else:
        form = VdlForm()

    return render(request, template_name, {'form': form, 'heading': heading_message, })

vdl.html
{% extends 'base.html' %}

{% block content %}

<form method="post" novalidate>
  {% csrf_token %}

            {{ form.vdl_name }}

            {{ form.stations }}

            <button type="button" class="btn-move-all-right btn-primary"></button>
            <button type="button" class="btn-move-selected-right"></button>
            <button type="button" class="btn-move-all-left"></button>
            <button type="button" class="btn-move-selected-left"></button>

            {{ form.selected_stations }}

            <button type="button" class="btn-delete"></button>
            <button type="button" class="btn-up"></button>
            <button type="button" class="btn-down"></button>

  <button type="submit">Submit</button>
</form>

{% endblock %}

in my base.html I import the js file mentioned in the plugin:
<link rel="stylesheet"href="{% static '/js/jquery-multi-selection.css' %}">

This is my actual result:

What it is wrong?


text:
Q: Data mining outlook e-mail bodies A while ago I went through and starting using the script guys get-outlookInbox which worked great with Data mining Subjects, however, I'm now trying to basically do the same thing but by trying to do this with bodies.
Originally I was importing the custom script from the script guys: https://blogs.technet.microsoft.com/heyscriptingguy/2011/05/26/use-powershell-to-data-mine-your-outlook-inbox/
Using the line
$inbox | Where-Object { $_.subject -match 'x'} | Where-Object { ($_.ReceivedTime -gt "06 11 2017") -and ($_.ReceivedTime -lt "10 10 2018") } | Group-Object -Property senderName -NoElement | Sort-Object count

I've tried changing $_.subject to $_.body however it seems that the original script doesn't pull body contents, i'm somewhat stuck here and was hoping someone might be able to point me in the right direction

A: The reason why it is not available is because the original script does not select the body. In order to get the body of the message you will need to change the original script to include the body.
Change:

Get-OutlookInbox.ps1

Change the line from:
$folder.items | Select-Object -Property Subject, ReceivedTime, Importance, SenderName

To:
$folder.items | Select-Object -Property Subject, ReceivedTime, Importance, SenderName, body


text:
Q: How can a high-voltage transistor be in such small packaging? For example:

*

*STN0214 - Very high voltage NPN power transistor
It is said to accept more than 1 kV between its collector and emitter. It comes in a SOT-223 package (3 pins plus a tab). With a dielectric strength of 1 kV/mm for humid air, cannot an arc appear between the electrodes?
Or do you have to enclose the package in glue or other material with higher dielectric strength than air?

A: It is not clear what the actual minimum distance between the collector and the other pins is but it seems to be a little bit more than 1 mm. Probably in a sealed housing with dry air that would just be sufficient (assuming anyone would use it near the maximum rating !). Another possibility is to apply a conformal coating.
BUT, the fact that the transistor can handle this voltage does not mean you HAVE to operate it up to that voltage. If you operate it at for example 600 V then you would have a considerable margin before the transistor breaks down. In some situations that could be nice to have.

A: Hmm, it does seem tight.  The pin pitch is 2.3 mm, and the maximum pin width is .85 mm, leaving 1.45 mm minimum space between pins.  The transistor is specified for 1.4 kV C-E, which are on adjacent pins, so that's just about 1 kV/mm.  As I said, that seems tight, and you'd have to be careful in designing the PCB footprint to not make this worse.
Usually I make PCB pads a little wider than the pins, but in this case I wouldn't.  Even if you make the pads the same width as the pins, then any alignment error cuts into the spacing.
Overall, I'd prefer a larger package with more space between pins to get somewhat below 1 kV/mm.

A: Yes, you would typically apply a compound to seal the pins after mounting.  Even for much larger spacing this is typically done since the leads often have sharp corners (more prone to corona and breakdown).  We routinely add something like Corona Dope to even rather large components (HV relays, etc) when the voltage gets up and over 1kV.  This provides protection on the order of ~145kV/mm and suppresses both arcs and corona discharge.   Surely Corona Dope is not the most suitable compound for this part, of course - it's just to provide the example. In any case, some sort of conformal insulating coating would be required in a system that operated the device to its maximum 1.4kV rating.
What would be of greater concern would be the PCB itself and the traces/pads - the chip is too tight for standard low-voltage PCB materials and design standards (ie: a board made with IPC specified materials).  For example, IPC2221A specifications indicate minimum spacing for permanently coated external conductors (ie: chip leads - assuming coated as above) as :

*

*0.8mm @ 500V + 0.00305mm/V additionally

*--> for 1.4kV this is 0.8 + 900*0.00305 = 3.545mm

Even the internal board traces would have to be spaced further apart (2.5mm, by a similar calculation) than the chip allows.  Other considerations for medium or high voltage PCBs is the shape of the pads and traces - these must often be rounded, eliminating sharp corners where traces change direction and using rounded rectangle pads instead of sharp-cornered squares.
So, in addition to needing to coat the component leads with an insulating compound after mounting, a standard PCB designed for low voltage circuits would not be appropriate for this component at its maximum rating.  You would therefore need to mount it on a board that was specifically designed for medium voltage (generally ~600-3000V) applications.

A: High voltage primary considerations are clearance and creepage at the physical layer.
Clearance is the shortest path between the points of interest and the standard usually used is IPC-2221A.
Creepage is the shortest electrical path on the PCB
If either of these distances is less than found in the above reference then as you surmise, a compound with better insulating properties is required.
The above reference gives values for conformally coated and uncoated boards for surface layers.
There are a number of solutions to this issue.
This is a simple answer to your specific question.
High voltage has many more issues to be taken into account.


text:
Q: How come colspan breaks in Firefox? I have my table for a simple login page. I'm not stuck on this because I know I could just break my table apart and get the styling another way, but it seems like colspan is broken in Firefox.
HTML

            E-mail:

                <input type="textbox" name="email">

            Password:

                <input type="password" name="password">

                <input type="submit" value="Login">

            Forgot your password?
            Reset It

            Don't Have an Account?
            Make One

CSS
table {
    width: 250px;
}
td:last-child {
    text-align: right;
}

Here is a jsFiddle for my table. Viewing this table in Chrome or IE you can see what I'm trying to do which is to get the input boxes for the email and password to overlap the words "Forgot your Password" and "Don't have an Account". So the colspan should make those overlap which it does in chrome and IE, but not in Firefox. How come it fails in Firefox?

A: In my opinion, Firefox is displaying it correctly. The text overflows in IE and Chrome. You need to actually have 3 columns for your colspans to work:

...


text:
Q: how to add styles to dynamically created component - angular 5 Requirement
I need to put dynamically created components in a container having rows and columns. Number of rows and columns depends on user input. Each component created at first takes 1x1, means 1 rows and 1 columns then it can be resized based on user requirement. Newly created component, first fill the row, if row is filled then it can be placed in the next row on leftmost column. so the story goes on until it fills the container as shown in the image:

Problem
The problem is that I cannot insert these components in the right alignment as expected to do that. What happens? If I add a first component and resize to 2x2, then adds another component of 1x1 and then 3rd of 1x1. This 3rd component assumed to be inserted below the 2nd component of 1x1 but it is being inserted below the first component of 2x2:

I hope now you are much more clear about what I want to do.
This problem can be solved if I wrap the newly created component in a new column. In a nut-shell, one column for one component. but don't know how to create column with each newly created component.

A: Get the Component's Reference i.e. ComponentRef and then get the HTMLElement <HTMLElement>componentRef.location.nativeElement. Now you are ready to change the styles...**
constructor(private CFR: ComponentFactoryResolver) {
}

private addComponent() {
    let componentFactory = this.CFR.resolveComponentFactory(MyComponent);

    // getting the component's reference
    let componentRef: ComponentRef<MyComponent> = this.location.container.createComponent(componentFactory);

    // getting the component's HTML
    let element: HTMLElement = <HTMLElement>componentRef.location.nativeElement;

    // adding styles
    element.classList.add('col-8 float-left');
    element.style.height = "100px";
    element.style.width= "50px";
}

after adding all this, in browser developer tool when you run the app, you'll see something like this
<my-component class="col-8 float-left"></my-component>


text:
Q: Coding specifications for Facebook fan page iframes I designed my fan page for Facebook which is 520 px wide and 800 px tall. Now the most interesting part comes up - slicing and coding to fit Facebook iframe.
Is there any coding specifications for making HTML/CSS for my Facebook fan page? I guess I must be careful with Java script.
Any help appreciated.

A: Applications running in Facebook Page tabs are simply Web Pages/Applications working in iframe tag. There is no coding standards or specifications for this and you may use any technology (that allows development of Web Pages/Applications). You're not limited by HTML/CSS/JavaScript here...
You should read Apps on Facebook.com and Page Tab Tutorial.


text:
Q: Быстрая загрузка статического контента на сайт Доброго времени суток.
Подскажите пожалуйста, стоит ли использовать облачные сервисы для хранения и получения картинок для сайта.
Есть ли преимущества использовать облачные сервисы вместо своего сервера???
Если есть преимущества, то подскажите какие хорошие сервисы существуют.
Какие есть варианты чтобы оптимизировать загрузку изображений

A:
Подскажите пожалуйста, стоит ли использовать облачные сервисы для
  хранения и получения картинок для сайта

*

*Если вы хотите, чтобы у пользователей была нормальная скорость загрузки, то да.

*Если вы хотите чтоб в случае проблем с вашим сервером картинок люди всё равно смогли их получать, то да.

Есть ли преимущества использовать облачные сервисы вместо своего
  сервера???

Можно настроить CDN (content delivery network), который будет забирать контент с вашего сервера и кешировать у себя. Пользователь уже будет получать картинки с этого CDN, что намного быстрее. То есть, при первом запросе на конкретную картинку CDN качает её с вашего сервера, кеширует у себя на время, которое вы в настройках укажите. Больше он в течении этого времени не будет обращаться к вашему серваку.
Шанс, что сломается CDN куда меньше, чем вашего сервера. К тому же, ваш сервер находится в конкретной зоне, следовательно загрузка контента из каких-то частей света будет медленной. CDN имеют распределённую структуру, они реплицируют ваши данные по разным датацентрам, чтоб максимизировать скорость из всех регионов.
В случае с Amazon, можно CDN настроить так, чтоб он картинки брал из вашего Amazon S3 хранилища. Тогда вам вообще не нужен сервер собственный с картинками.

Если есть преимущества, то подскажите какие хорошие сервисы
  существуют.

Если мы говорим о CDN, то лично мы используем cloudfront и Azure CDN. Могу их посоветовать. Но это, естественно, платные сервисы. Ещё хорош fastly (он, вероятно, дешевле будет).


text:
Q: How to migrate Hibernate @Audited informarion from table field? I need to change my database structure that way: move one field from @Audited entity to another @Audited entity with no loss of audit information. How can I migrate it?

*

*By liquibase migration I create new field in table T1 and T1_aud

*Update T1 with values of old table field T2

*Somehow migrate audit to T1

*Drop column from T2 and T2_aud

A: Just adding the same values to AUD table solves the problem.


text:
Q: Is void *function() a pointer to function or a function returning a void*? I'm confused about the meaning of void *function().
Is it a pointer to function or a function returning void*? I've always used it on data structures as a recursive function returning a pointer, but when i saw a code in multithreading (pthread) there is a same function declaration. Now I'm confused what's the difference between them.

A: The function has the return type void *.
void *function();

So I always prefer in such cases to separate the symbol * from the function name like
void * function();

And as  Jarod42 pointed to in a comment you can rewrite the function declaration in C++ using the trailing return type like
auto function() -> void *;

If you want to declare a pointer to function then you should write
void ( *function )();

where the return type is void Or
void * ( *function )();

where the return type void *.
Or a pointer to function that returns pointer to function
void * ( *( *function )() )();

A: It is a function returning a pointer to void.
Think of your declaration this way:
void *(function());

This would be a function returning void (or nothing):
void (*function2)();

Think of the above declaration this way:
void ((*function2)());

A much easier way to write these is to use typedefs:
typedef void *function_returning_void_pointer();
typedef void function_returning_nothing();

function_returning_void_pointer function;
function_returning_nothing *function2;

This generally eliminates the confusion around function pointers and is much easier to read.

A: Whenever I'm unsure about C syntax issues, I like to use the cdecl utility (online version) to interpret for me.  It translates between C syntax and English.
For example, I input your example of void *foo() and it returned

declare foo as function returning pointer to void

To see what the other syntax would look like, I input declare foo as pointer to function returning void and it returned

void (*foo)()

This gets particularly useful when you have multiple levels of typecasts, stars, or brackets in a single expression.

A: Declarations in C/C++ are read from the identifier outwards following operator precedence.
A quick look at the C/C++ operator precedence table in wikipedia reveals that the function call operator () has a higher precedence than the indirection operator *. So, your function declarations reads like this:

*

*Start at the identifier: function is

*function() a function that takes no arguments

*void* function() and returns a void*.
This general principle also holds with array declarations ([] also has higher precedence than *) and combinations of the two. So
int *(*arr[42])();

is read as

*

*arr is

*arr[42] an array of 42 elements which are

**arr[42] pointers to

*(*arr[42])() functions that take no arguments and

*int *(*arr[42])() return an int*.

It takes a bit to get used to this, but once you've understood the principle, it's easy to read those declarations unambiguously.


text:
Q: Spacing of colons in math equations The standard notation for the semidirect of a group G by a group H is $G \rtimes H$ or $G\ltimes H$ depending on whether H is acting on G or G is acting on H. However, occasionally, people write the semidirect product using a colon. I've been typesetting this as $G:H$ but I find this produces too much space on either side of the colon. I alternatively tried typesetting this as $G\text:H$ but then the spacing is too tight. The spacing in superscripts/subscripts seems to more what I have in mind. For instance $\Phi^{G:H}$ seems to produce better spacing.
Is there an alternative option for using a colon in a math environment? Or is it possible to introduce my own colon and control the spacing myself?
I know there is \colon but this only reduces the spacing on one side and is more appropriate for function definitions, such as $f\colon G \to H$.

A: I take it there's no chance that readers of your document will become confused between three potential meanings of : (a) relational operator, (b) \colon (with asymmetric spacing), and (c) symbol for "semidirect of a group". (If there is such a chance, you better stick with \ltimes and/or \rtimes for "semidirect of a group", right?)
If there's no chance for such confusion, you may want to set up a custom macro called, say, \sd, as follows:
\newcommand\sd{\mkern1.5mu{:}\mkern1.5mu} % "semidirect"

1.5mu is half of a thin-space. If that's not tight enough for your taste, try replacing the two instances of 1.5mu with 1mu.
Here's a comparison of various possible spacing choices:

\documentclass{article}
\usepackage{array}
\newcommand\sd{\mkern1.5mu{:}\mkern1.5mu} % "semidirect"

\begin{document}
\begin{tabular}{>{$}l<{$} >{\ttfamily}l}
G\mathrel{:}H  & \textbackslash mathrel  (5mu) (default)\\
G\mathbin{:}H  & \textbackslash mathbin  (4mu) \\
G\,{:}\,H      & 3mu symmetric \\
G\colon H      & \textbackslash colon, 0mu/3mu asymmetric) \\
G\sd H         & 1.5mu symmetric, \textbackslash sd\\
G\mathord{:}H  & \textbackslash mathord (0mu)\\
\end{tabular}

\end{document}


text:
Q: scatter plot with fixed axis I have a slightly unusual question to ask. I have several datasets with coordinates of political parties and issues in their campaign, arranged in a two-dimensional space. These datasets are the results of multidimensional scaling, and I am using R to plot them as simple scatter plots with ggplot. I use the UK as an example to show what I mean.
Here is the dataset:
dat <- structure(list(horizontal = c(0.204471737146378, -0.444747358560562,
                                       -0.342559009790421, 0.83488667011261, 0.561371266841888, 0.885410964488983,
                                       -0.329168140888214, -0.676190733909607, -0.0879427865147591,
                                       -0.257560282945633, -0.487674087285995, -0.0497645996510983,
                                       0.542662084102631, -0.721681654453278, -0.0316252149641514, 0.332207173109055,
                                       -0.643045961856842, 0.506858110427856, -0.324039697647095, -0.86803138256073,
                                       0.837070941925049, 0.559091985225677), vertical = c(-0.14312070608139,
                                                                                0.55092453956604, -0.118618287146091, -0.066099539399147, -0.0786356627941132,
                                                                                0.476942390203476, -0.206086233258247, -0.338285326957703, 0.0132009144872427,
                                                                                -0.415686339139938, -0.0648649260401726, -0.205041542649269,
                                                                                0.118428349494934, 0.294788777828217, -0.375703752040863, 0.247018560767174,
                                                                                0.0151952970772982, -0.273895233869553, -0.278548806905746, 0.607526957988739,
                                                                                -0.100193984806538, 0.34084951877594), party_id = c(NA, NA, NA,
                                                                                NA, NA, NA, NA, NA, NA, NA, "cons", "lab_uk", "libdem", "cons",
                                                                                "lab_uk", "libdem", "cons", "lab_uk", "libdem", "ukip", "snp",
                                                                                "gr_uk"), issue = c("issue", "issue", "issue", "issue", "issue",
                                                                                "issue", "issue", "issue", "issue", "issue", "party", "party",
                                                                                "party", "party", "party", "party", "party", "party", "party",
                                                                                "party", "party", "party"), object_n = c("welfare", "ecolib",
                                                                                "ecoreform", "europe", "cultlib", "immig", "security", "defense",
                                                                                "edu", "infra", "cons_05", "lab_uk_05", "libdem_05", "cons_10",
                                                                                "lab_uk_10", "libdem_10", "cons_15", "lab_uk_15", "libdem_15",
                                                                                "ukip_15", "snp_15", "gr_uk_15")), .Names = c("horizontal", "vertical",
                                                                                "party_id", "issue", "object_n"), row.names = c(NA, -22L), class = c("tbl_df",
                                                                                "tbl", "data.frame"))

I tweak some of the theme parameters (which you don't neccessarily have to do, esp the font part) with:
theme_set(theme_classic(base_size = 16) +
            theme(axis.line=element_blank(),axis.text.x=element_blank(),
                  axis.text.y=element_blank(),axis.ticks=element_blank(),
                  axis.title.x=element_blank(),
                  axis.title.y=element_blank(),
                  text=element_text(family="Century Gothic", size=10)))

and use the following code to create the plot:
dat$ff <- ifelse(dat$issue == "issue", "bold", "plain")

ggplot(dat, aes(vertical, horizontal)) +
  geom_point(data=subset(dat, dat$issue=="issue"),
             color = 'black', size=5, shape=3, show.legend = F) +
  geom_point(data=subset(dat, dat$issue=="party"),
             aes(shape=party_id, colour=party_id, fill=party_id),
             size=2) +
  geom_text_repel(aes(label = object_n, size=issue, fontface=ff),
                  family = "Century Gothic", show.legend = F) +
  scale_colour_grey("Parties", start = 0, end = .6) +
  scale_fill_grey("Parties", start = 0, end = .6) +
  scale_size_manual("Parties", values = c(3.3, 2.8)) +
  scale_shape_manual("Parties", values=c(15, 21, 23, 24, 25, 11, 8,
                                         10,12,13,4,0,1,14,7,9))

which results in a plot similar to this:

In MDS analysis only the relative positions matter, the absolute coordinates are not important. Therefore, I would like to "rotate" the scatter plots in a way that the axis defined by the points "ecolib" and "welfare" always form the horizontal dimension, with "welfare" on the left and "ecolib" on the right. Everything else can freefloat around them.
I realize I need to adjust the raw coordinates and center them around the two points. However, I could not yet figure out how. Any help is much appreciated!

A: To put welfare and ecolib on the x axis, shift all the points so that the line between these two points goes through the origin and then rotate all the points by the angle that the line between the two points makes with the x axis.
library(tidyverse)
library(ggrepel)

# Extract the welfare and ecolib rows
n = dat %>% filter(grepl("ecolib|welfare", object_n))

# Get the slope and intercept of the line between them
slope = diff(n$vertical)/diff(n$horizontal)
intercept = n$vertical[2] - slope*n$horizontal[2]

# To check this, draw the line to show that we have the correct line
# Assuming you've saved your previous plot as object p and have switched
#  horizontal and vertical to be, respectively, on the x and y axes
p + geom_abline(slope=slope, intercept=intercept)

# Shift y-values by value of intercept so that line connecting welfare and ecolib
#  goes through the origin
dat$ynew = dat$vertical - intercept

# Get rotation angle to rotate welfare and ecolib to x-axis
angle = atan((n$vertical[1] - intercept)/n$horizontal[1])

# Rotate all points by the angle we just calculated and add the new x and y
#  values to the data frame
# %*% is the matrix multiplication operator and the second matrix is the
#  rotation matrix for the transformation
rot = as.matrix(dat[,c("horizontal", "ynew")]) %*% matrix(c(cos(angle), -sin(angle), sin(angle), cos(angle)), nrow=2, byrow=TRUE)
dat$xnew = rot[,1]
dat$ynew = rot[,2]

Now we're ready to plot the new shifted and rotated values:
ggplot(dat, aes(xnew, ynew)) +
  geom_point(data=subset(dat, dat$issue=="issue"),
             color = 'black', size=5, shape=3, show.legend = F) +
  geom_point(data=subset(dat, dat$issue=="party"),
             aes(shape=party_id, colour=party_id, fill=party_id),
             size=2) +
  geom_text_repel(aes(label = object_n, size=issue, fontface=ff),
            family = "Century Gothic", show.legend = F) +
  scale_colour_grey("Parties", start = 0, end = .6) +
  scale_fill_grey("Parties", start = 0, end = .6) +
  scale_size_manual("Parties", values = c(3.3, 2.8)) +
  scale_shape_manual("Parties", values=c(15, 21, 23, 24, 25, 11, 8,
                                         10,12,13,4,0,1,14,7,9))


text:
Q: How to Avoid update operation when user changed the Picklist value manually I have standard Picklist field currency on Lead object. I  have a trigger,  which checks when countrycode='86' then it will set the currency as 'CNY' otherwise set it to 'USD'.
Now my requirement is that when user try to manually change the picklist field value which dosn't match with countrycode then no update operation performed.
My code logic is:
 if(Trigger.isInsert || Trigger.isUpdate)
 {
       for (Lead lead :(List<Lead>)trigger.new)
               {
                  if(lead!=null &&  lead.Country_Code__c=='86')
                   {
                   Lead l=new Lead();
                   l.CurrencyIsoCode='CNY';

               }
                 else

                 {
                   Lead l=new Lead();
                   lead.CurrencyIsoCode='USD';
                 }
           }
      }
 }

A: A simple validation rule would be sufficient...
ISCHANGED(CurrencyIsoCode) &&
NOT(ISPICKVAL(CurrencyIsoCode, "CNY")) &&
Country_Code__c == "86"

This validation rule will check to see if the currency field is being changed to something other than "CNY" when the Country Code is 86 and allow you to error the update. You could also accomplish this in your trigger but a simple validation rule will be more maintainable in the future.


text:
Q: DotNetZip ExtractProgress events in PowerShell I'm extracting a ZIP file in PowerShell by using the DotNetZip library, and I want to display progress. I'm using the following code:
try {
    $zip = [Ionic.Zip.ZipFile]::Read($ZipFileName)

    Register-ObjectEvent `
            -InputObject $zip `
            -EventName ExtractProgress `
            -SourceIdentifier ExtractProgress `
            -Action {
                [Console]::Beep()
                Write-Host $Sender
                Write-Host $SourceEventArgs
            } | Out-Null

    $zip.ExtractAll($Destination, 'OverwriteSilently')
}
finally {
    Unregister-Event -SourceIdentifier ExtractProgress
    $zip.Dispose()
}

My problem is that I don't see the events (no beep, no Write-Host) until the very end. I'm expecting to see progress events during the process.
Initially, I thought it was because Register-ObjectEvent queued the events, but the PowerShell help says that -Action is invoked immediately, without the event being queued.
If I write the equivalent code in a C# console application, then I see the progress events as each file is extracted, as expected, which means that (as far as I can tell) DotNetZip is doing the right thing. Note that the events are raised on the same thread that called ExtractAll.
What am I doing wrong?
(Windows 7 x64, PowerShell 2.0, configured to use .NET 4.0)


text:
Q: WPF TreeView Group By I have class "Person" that look like this:
public class Person
{
        public string Name { get; set; }
        public int Age { get; set; }
        public string Country{ get; set; }
        public List<Person> Children { get; set; }
}

I want to create a TreeView in WPF that will present the Persons by Country.
For example:

*

*New york

*

*Bob

*

*New York

*

*Ethan

*Owen

*Canada

*

*Benjamin

*James

*Kevin

*

*Paris

*

*Louis

*William

*Finland

*

*Oliver

*

*Hungary

*

*Ben

*Paul

*Iceland

*

*Arthur

*

*Benjamin

*England

*

*Gabriel

*Victor

*Eino

*

*Paris

*

*Gabriel

*Adam

*Emma

My TreeView :
 <TreeView.Resources>
  <HierarchicalDataTemplate ItemsSource="{Binding People}" DataType="{x:Type Person}">
       <Label Content="{Binding Name}"></Label>
   </HierarchicalDataTemplate>

Is there someway to use "Group by" in tree view?

A: As far as i know, WPF TreeView doesnt support 'Sorting'.
What you could do is use Linq to sort your ItemsCollection.
That will do the same thing, but your collection will be modified.
Try playing around with linq.. :) you will find it definitely :)


text:
Q: How to have multiple publishers and subscribers in ZMQ/0MQ? How to create a network which allows for multiple publishers and multiple subscribers to those publishers?
Or is it absolutely necessary for a message broker to be used?
import time
import zmq
from multiprocessing import Process

def bind_pub(sleep_seconds, max_messages, pub_id):
    context = zmq.Context()
    socket = context.socket(zmq.PUB)
    socket.bind("tcp://*:5556")

    message = 0
    while True:
        socket.send_string("1 sending_func=bind_pub message_number=%s pub_id=%s" % (message, pub_id))
        message += 1
        if message >= max_messages:
            break
        time.sleep(sleep_seconds)

def bind_sub(sleep_seconds, max_messages, sub_id):
    context = zmq.Context()
    socket = context.socket(zmq.SUB)
    socket.bind("tcp://*:5556")
    socket.setsockopt_string(zmq.SUBSCRIBE, '1')

    message_n = 0
    while True:
        message = socket.recv_string()
        print(message + " receiving_func=bind_sub sub_id=%s" % sub_id)
        message_n += 1
        if message_n >= max_messages - 1:
            break
        time.sleep(sleep_seconds)

def conect_pub(sleep_seconds, max_messages, pub_id):
    context = zmq.Context()
    socket = context.socket(zmq.PUB)
    socket.connect("tcp://localhost:5556")

    message = 0
    while True:
        socket.send_string("1 sending_func=conect_pub message_number=%s pub_id=%s" % (message, pub_id))
        message += 1
        if message >= max_messages:
            break
        time.sleep(sleep_seconds)

def connect_sub(sleep_seconds, max_messages, sub_id):
    context = zmq.Context()
    socket = context.socket(zmq.SUB)
    socket.connect("tcp://localhost:5556")
    socket.setsockopt_string(zmq.SUBSCRIBE, '1')

    message_n = 0
    while True:
        message = socket.recv_string()
        print(message + " receiving_func=connect_sub sub_id=%s" % sub_id)
        message_n += 1
        if message_n >= max_messages - 1:
            break
        time.sleep(sleep_seconds)

When trying a bind_pub, connect_pub, connect_sub, connect_sub network architecture:
# bind_pub, connect_pub, connect_sub, connect_sub
n_messages = 4
p1 = Process(target=bind_pub, args=(1,n_messages,1))
p2 = Process(target=conect_pub, args=(1,n_messages,2))
p3 = Process(target=connect_sub, args=(0.1,n_messages,1))
p4 = Process(target=connect_sub, args=(0.1,n_messages,2))
p1.start()
p2.start()
p3.start()
p4.start()
p1.join()
p2.join()
p3.join()
p4.join()

Results in pub_id=2 messages going missing:
1 sending_func=bind_pub message_number=1 pub_id=1 receiving_func=connect_sub sub_id=2
1 sending_func=bind_pub message_number=1 pub_id=1 receiving_func=connect_sub sub_id=1
1 sending_func=bind_pub message_number=2 pub_id=1 receiving_func=connect_sub sub_id=2
1 sending_func=bind_pub message_number=2 pub_id=1 receiving_func=connect_sub sub_id=1
1 sending_func=bind_pub message_number=3 pub_id=1 receiving_func=connect_sub sub_id=1
1 sending_func=bind_pub message_number=3 pub_id=1 receiving_func=connect_sub sub_id=2

Similarly running a connect_pub, connect_pub, connect_sub, bind_sub architecture:
# connect_pub, connect_pub, connect_sub, bind_sub
n_messages = 4
p1 = Process(target=conect_pub, args=(1,n_messages,1))
p2 = Process(target=conect_pub, args=(1,n_messages,2))
p3 = Process(target=bind_sub, args=(0.1,n_messages,1))
p4 = Process(target=connect_sub, args=(0.1,n_messages,2))
p1.start()
p2.start()
p3.start()
p4.start()
p1.join()
p2.join()
p3.join()
p4.join()

Results in no messages being received by sub_id=2:
1 sending_func=conect_pub message_number=1 pub_id=1 receiving_func=bind_sub sub_id=1
1 sending_func=conect_pub message_number=1 pub_id=2 receiving_func=bind_sub sub_id=1
1 sending_func=conect_pub message_number=2 pub_id=1 receiving_func=bind_sub sub_id=1

A: Well,fair to mention that ZeroMQ is principally a Broker-less framework ,
this means the 2nd question is solved a priori - no, it is not only not absolutely necessary, it is also principally impossible ( if one does not implement a Broker-(semi-)persistence as a Zen-of-Zero standard ZeroMQ tools based layer an extra add-on ).

Next, ZeroMQ tools are by far not "socket"-s as you know 'em :
This is an often re-articulated misconception, so let me repeat it in bold.
Beware:
ZeroMQ Socket()-instance is not a tcp-socket-as-you-know-it. Best read about the main conceptual differences in  ZeroMQ hierarchy in less than a five seconds  or other posts and discussions here.

Yet,more important,there seems to be no expressed need which is not covered :
ZeroMQ can either serve all of :
many-PUB-s : many-SUB-s           -or-
 one-PUB   : many-SUB-s           -or- even
many-PUB-s :  one-SUB

where all or part of those "many" could still get .connect()-ed to a single or more AccessPoints, so the produced topologies could go indeed wild ( for details kindly check the above offered link to a "five seconds" read ) so, one's own imagination seems to be the only ceiling in doing this.
For performance and latency envelopes, feel free to seek and read more in other posts.

A: It is certainly not necessary to use a broker in order to implement a many-to-many network, but a broker does simplify configuration since each node only needs to know the broker's address, not all of its peers.
Another possibility is a hybrid approach -- using a broker to exchange address information among peers so they can connect to each other directly.  You can find an example here: https://github.com/nyfix/OZ/blob/master/doc/Naming-Service.md


text:
Q: How is native code handled by the JVM Consider an case that I have to call C++ code from my Java Program. The C++ code creates thousands of Objects. Where are these dynamic objects stored ? I suspect in the JVM heap because the native code will be a part of the same process as the JVM.
If yes, do the rules of Java Garbage collector thread apply on Objects of the C++ code ?

A: For the first question, C++ will allocate resources using its own runtime which has nothing to do with the JVM - the JVM is not aware of any activity in this memory allocator.
For the second question, the Java garbage collector will not GC the memory allocated by C++.  You will have to make sure that your Java wrapper initiates the memory release.  Before an object is GC'd by java, the runtime calls the finalize() method.  The default one is inherited from java.lang.Object and basically does nothing.  You can override this and use it as a hook to initiate deallocating your manually managed memory.


text:
Q: OpenCL:Why Pointer to a pointer cannot be passed as an argument to a kernel function? Hi,
                                                                                I just want some clarification on Why we can not pass the 2D array pointer as argument to the kernel .
Why it is not allowed .
What will happen if I use this as argument (Internally??as I know the code will give some error) .
Please do the needful .

A: Because in OpenCL 1.x the device has a separate address space. Kernels executing on the device wouldn't know what to do with a pointer that is only useful in host address space.
Note that in OpenCL 2.0 Shared Virtual Memory (SVM) removes this restriction and allows buffers containing pointers to be used on both host and device side.

A: To be a little more concrete, let's say I have a kernel with a pointer to a pointer as a parameter:
kernel void foo(global float * global *a){...}
The runtime in this case knows that it has a private pointer to an array of global pointers to global floats.
When I pass a buffer to the runtime:
clSetKernelArg(fooKernel, 0, sizeof(cl_mem), &aBuffer);
The runtime knows it expects a pointer. As this is OpenCL 1.x it knows then it must have had the arg set to a pointer. It knows the that the pointer it received is a pointer to a cl_mem. It can look at that cl_mem, find the address it has been allocated in device memory, pass that address into the device and launch the kernel. However, it does not know (in general) which buffer you are trying to point to for the pointers inside the buffer. Even if it did know that they pointed to the same buffer, it would have to go through the entire buffer updating every pointer field. If the pointers were nested it would have to have a lot more information. It just isn't feasible in the general case.
OpenCL 2.0 supports shared virtual memory, which means the addresses are fixed, and the same on the host and device (even if the memory isn't necessarily directly shared). There is no need to do the conversion and hence it becomes possible.


text:
Q: Is there a way to import a CSV comma delimited file into mysql? Hi there I am new to web development.
I am trying to import a CSV file into mysql workbench using 'Table Data Import Wizard'. However, I have read my file needs to be a CSV (MS-DOS), or I get the  following error: Can't analyze file. Please try to change encoding type. If that doesn't help, maybe the file is not: csv, or the file is empty.
I cannot use a CSV (MS-DOS) as my data contains a lot of different special characters including those from Nordic Europe. When I convert my CSV (comma delimited) to CSV (MS-DOS) the special characters are no longer the same.
Is there a way to import a CSV comma delimited file into mysql workbench? Or is there a better solution to getting my data into the table such as keeping the special characters the same in the MS-DOS file somehow?

A: You can import regular CSVs without an issue, just make sure the encoding matches.
Something like
LOAD DATA
    INFILE yourfile.csv
    INTO TABLE tablename
    FIELDS
        TERMINATED BY ','
        ENCLOSED BY '"'
    LINES
        TERMINATED BY '\n'
    IGNORE 1 LINES

should work. If your CSV doesn't have headers, remove the ignore 1 lines line from the code. If your formatting is different, change the enclosing and terminating characters accordingly.
You can look up the exact syntax in the manual.

A: Your CSV should work fine. You just need to Load Data Infile
You will likely need to define these settings though
LOAD DATA INFILE 'c:/tmp/discounts.csv'
INTO TABLE discounts
-- comma seperated? maybe pipes '|'?
FIELDS TERMINATED BY ','
-- what surrounds input and is it optional? then add OPTIONALLY before ENCLOSED
ENCLOSED BY '"'
-- what is at the end of files
LINES TERMINATED BY '\n'
-- how many header rows are there, if any?
IGNORE 1 ROWS;


text:
Q: Pattern Recognition - Visualizing Dense Data Points I have a sample of around 5000 data (2D) points that are generated through a simulation of a cryptocurrency's mining events of following form.
In column 2 one can see identical y-values with different x-values yet being "densely packed" and consequently becoming "invisible" among the large sample after plotting.
column 1:         column 2:
time in s*60      height of created "coins"
341.00000         1
345.02802         1
2621.00000        2
4180.00000        3
4183.87060        3
...
3016703.00000     3993
3016708.45441     3994
3019167.00000     3995
3019170.07885     3995

Question: I need to visualize the pattern of identical y-values with slight time difference but don't know if there's a method/tool to make this pattern clearly noticeable.
Note: The pattern mentioned before makes up about 20% of all events with a "sub-pattern" making up 6% of all events, with both patterns being almost uniformly distributed among all events.
I'd just like to make the pattern visible, be it by coloring or any other method, but I'm quite new to plotting tools like python's pylpot so I'm lacking seach terms that would help me.
What I have tried so far:
- multiplied the x value in the simulation script causing a "scissor" in the plot.
- thought of a density plot
Thanks in advance!

A: Heat maps are preferred for very large datasets; transparency is great, but works up to a point - a certain degree of juxtaposition cannot be visualized without the 3D component. In R smoothScatter () is great, several examples for Python here. Bubble charts may also work for some applications.


text:
Q: Using OpenCV TLD from Python According to the release docs for OpenCV 3.0.0, it includes an implementation of the Tracking-Detection-Learning algorithm. There's even some very basic docs for the C++ code.
I downloaded and compiled the 3.0.0-beta, including the Python wrapper, and it seems to have succeeded, and although I can run the Python samples, I can't find any way to access and TLD functionality through the Python wrapper. I can't even find references to it in the code.
Is it actually included in the 3.0.0 release, and if so, how do I access it?

A: From what I find so far there is no instruction, explicitly telling the user how to use TLD. But, you can access TLD tracking modules just by changing the parameter For instance: cv2.Tracker_create("TLD")
For a demo, you can try https://github.com/Itseez/opencv_contrib/blob/master/modules/tracking/samples/tracker.py and change the like cv2.Tracker_create("MIL") to cv2.Tracker_create("TLD")
Note: you must install opencv along with opencv_contrib to make this demo work.
Good Luck

A: the tld c++ code for opencv3.0 is in the opencv_contrib repo,
unfortunately, atm  python or java wrapping is not ready yet.


text:
Q: PHP Desktop Z-index I downloaded the PHP Desktop application from https://code.google.com/p/phpdesktop/wiki/DownloadMSIE, and paste www folder to the downloaded file. I am getting issue in z-index. Select Box appears first and Menu appears back. It is working fine in all the browsers but not in Desktop. The style for Menu,
 position: absolute;
 z-index: 10;

Please help me in fixing it.
Thanks..

A: the box which you want to display first give ithen
z-index:9999999;

A: PHP Desktop MSIE by default embeds IE 7.0. Maybe the old version of IE is cause of the issue. To use a newer version of IE embedded read this: https://code.google.com/p/phpdesktop/wiki/MSIEengine#How_to_use_a_newer_version_of_IE_engine


text:
Q: Magento remove 0 value attribute in Layer Navigation How to disable attribute in layer navigation if that attribute have 0 values
i used this
<?php if($_item->getCount() > 0):?>

        <?php $inputId = $_item->getFilter()->getRequestVar().'_'.$_item->getValue() ?>
        <input type="checkbox" id="<?php echo $inputId ?>" name="<?php echo $_item->getFilter()->getRequestVar(); ?>" value="<?php echo $this->urlEscape($_item->getUrl(true)) ?>" <?php if ($_item->isSelected()):?>checked="checked"<?php endif ?> />
        <label for="<?php echo $inputId ?>"><?php echo $_item->getLabel() ?>
            <?php if ($this->shouldDisplayProductCount()): ?>
            (<?php echo $_item->getCount() ?>)
            <?php endif ?>

    <?php endif;?>

it disable Values but Lable How to disable this Label

A: Try:
Catalog -> Attributes -> search the corresponding attribute.
In the Properties tab look for Frontend Properties. Change the value for Use In Layered Navigation from Filterable (no results) to Fileterable (with results). This should exclude any filterable attributes that would have zero results.


text:
Q: What are the irreps in this canonical action of $\operatorname{PGL}_2(F_q)$? Consider the permutation action of $\operatorname{PGL}_2(\mathbb F_q)$ on $\mathbb P^1(\mathbb F_q)$ by fractional linear transformations. We can consider the associated (complex) representation of dimension $q+1$.
What can we say about the irreducible representations occurring in this representation? This is probably doable because our representation is an induced representation. What I am really interested in is the following question:
What can we say about the invariant polynomials for this representation?


text:
Q: What is the fastest way in .Net 3.5 to call a method by string name? So the obvious way to do this is..
var handler = GetType().GetMethod(methodName, BindingFlags.NonPublic |
                                              BindingFlags.Instance);

handler.Invoke(this, new object[] {e});

And I can add caching to keep the methods around but I'm wondering if there is a completely different and faster way?

A: The fastest way would be to cache a typed delegate; if you know the signature is always:
void PersonInstance.MethodName(string s);

Then you could create an Action<Person,string> via Delegate.CreateDelegate:
var action = (Action<Person,string>)Delegate.CreateDelegate(
    typeof(Action<Person,string>), method);

This can then be cached against the name, and invoked as:
action(personInstance, value);

Note that the cache here is critical; the reflection to locate the method and prepare a typed-delegate is non-trivial.
It gets harder if the signature is unpredictable, as DynamicInvoke is relatively slow. The fastest way would be to use DynamicMethod and ILGenerator to write a shim method (on the fly) that takes an object[] for the parameters and unpacks and casts it to match the signature - then you can store an Action<object, object[]> or Func<object,object[],object>. That is, however, an advanced topic. I could provide an example if really needed. Essentially writing (at runtime):
void DummyMethod(object target, object[] args) {
    ((Person)target).MethodName((int)args[0],(string)args[1]);
}

Here's an example of doing that (note: it doesn't handle ref/out args at the moment, and possibly a few other scenarios - and I've left the "cache" side of things as an exercise for the reader):
using System;
using System.Reflection;
using System.Reflection.Emit;

class Program
{
    static void Main()
    {
        var method = typeof(Foo).GetMethod("Bar");
        var func = Wrap(method);
        object[] args = { 123, "abc"};
        var foo = new Foo();
        object result = func(foo, args);
    }

    static Func<object, object[], object> Wrap(MethodInfo method)
    {
        var dm = new DynamicMethod(method.Name, typeof(object), new Type[] {
            typeof(object), typeof(object[])
        }, method.DeclaringType, true);
        var il = dm.GetILGenerator();

        if (!method.IsStatic)
        {
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Unbox_Any, method.DeclaringType);
        }
        var parameters = method.GetParameters();
        for (int i = 0; i < parameters.Length; i++)
        {
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldc_I4, i);
            il.Emit(OpCodes.Ldelem_Ref);
            il.Emit(OpCodes.Unbox_Any, parameters[i].ParameterType);
        }
        il.EmitCall(method.IsStatic || method.DeclaringType.IsValueType ?
            OpCodes.Call : OpCodes.Callvirt, method, null);
        if (method.ReturnType == null || method.ReturnType == typeof(void))
        {
            il.Emit(OpCodes.Ldnull);
        }
        else if (method.ReturnType.IsValueType)
        {
            il.Emit(OpCodes.Box, method.ReturnType);
        }
        il.Emit(OpCodes.Ret);
        return (Func<object, object[], object>)dm.CreateDelegate(typeof(Func<object, object[], object>));
    }
}

public class Foo
{
    public string Bar(int x, string y)
    {
        return x + y;
    }
}


text:
Q: I have problems implementing the ++ increment operator I am trying to provide a c++ interface for a c library I just finished, and I want it to be possible to write
for (DBITable table = db.tables() ; table != NULL ; table++)

where db is a class with a tables() method that returns the DBITable associated with it.
On compilation I get the following error with clang++

error: cannot increment value of type 'DBITable'
for (DBITable table = db.tables() ; table != NULL ; table++)
                                                    ~~~~~^

This is how i have implemented the ++ operator overload method

DBITable
DBITable::operator++()
{
    return next();
}

and it's declared in the DBITable class as
public:
    DBITable operator++();

the table != NULL part worked as I expected by doing this
bool operator!=(void *)
{
    // evaluate and get the value
    return value;
}

A: operator++() is the prefix increment operator. Implement the postfix operator as operator++(int).
The canonical implementations are have the prefix operator return a reference and the postfix operator return by value. Also, you would typically implement the postfix operator in terms of the prefix operator in the interests of least surprise and easy maintenance. Example:
struct T
{
 T& operator++()
 {
  this->increment();
  return *this;
 }

 T operator++(int)
 {
   T ret = *this;
   this->operator++();
   return ret;
 }
};

(Increment/decrement operators at cppreference.)