text:
Q: Why doesn't the ergodic hypothesis hold for most systems? Is there a physical (intuitive) explanation for why most systems are not ergodic? As my book states, it is a natural assumption that a system is at least quasi-ergodic; it then proceeds to state that this hypothesis is, in fact, false, and that we need a different basis for statistical mechanics. I don't understand why most systems aren't, and how we can prove this.

A: I'm not sure how to quantify "most" systems, but off the top of my head, there are many processes that we encounter in our daily lives that break ergodicity within the timeframe under which we consider them.

*

*Symmetry breaking in general breaks ergodicity. Take, for example, a magnet. Ergodicity would imply that a magnet's magnetization would point in all directions (as every direction of magnetization occupies the same volume of phase space) with equal probability if sampled over a sufficiently long time. However, human timeframes is manifestly not anywhere near "sufficiently long".

*Disordered materials (like wood and glass) also break ergodicity. A block of wood has equal energy in many different configurations, but it only explores a tiny portion of that phase space volume. (i.e. if your block is a cube, it doesn't spontaneously move into a position rotated 90 degrees about one of its axes, again within human timeframes.)

Since statistical mechanics also aims to (and does) explain the behavior of these types of materials as well, it shouldn't need to depend on ergodicity to do so.


text:
Q: send parameters of form via URL I have a form like this:
<form rel="search" action="/archives">

 <input name="keyword" type="text" value="search..." />

 <input type="submit" value=submit" name="submit" />

</form>

When a User click on submit...I want sent parameters by URL...
exact this URL:  http://examole.com/archives/keyword
Or any alternative way...
.
Is it possible?

Edit
I try change above code to this:
<form rel="search" action="/archives" method="get">

 <input name="keyword" type="text" value="search..." />

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

</form>

The result:
http://127.0.0.1/archives?keyword=search...

How can I change The URL to this:
   http://127.0.0.1/archives/search...

A: Yes, you can. Just use method="get"
<form method="get" rel="search" action="/archives">
   <input name="keyword" type="text" value="search..." />
   <input type="submit" value=submit" name="submit" />
</form>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does sleep() affect pthread execution? I am confused about this example:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void *thread_func()
{
    sleep(1); // removing this changes the result
    printf("\n");
    return NULL;
}

int main()
{
    int i;

    for (i = 0; i < 10000; i++)
    {
        pthread_t tid;
        pthread_create(&tid, NULL, thread_func, NULL);
    }

    pthread_exit(NULL);
    return 0;
}

if i run this with the sleep(1), i count 2047 lines, without it 10000, as expected. What is going on here?
EDIT: Corrected number of expected lines to 10000.

A: Since your program does not wait for its threads before it exits, what is happening is that it has a vaguely defined time to run before exiting the program destroys all of the threads.
Update: pthread_exit does wait for threads. For threads that are running. What I suspect is happening is that the threads created by pthread_create are not fully constructed before pthread_exit and then the program exits. Part of thread construction happens in the new thread, so if it never gets scheduled to run then that thread may as well not exist.
Creating 10,000 threads takes time. So does destroying them. In the meantime apparently 3,000 threads manage to reach the printf statement.
The amount of time and the number of prints is dependent on so many different factors that it may as well be random.

A: Putting aside that the code shown tries to created 10000 threads which, if created successfully, would print 10000 lines not 3000, the core question is:
Why are less threads printing if each thread waits 1s compared to not waiting?
Possible reasoning:
Each thread eats up resources. Due to this the maximum number of threads existing concurrently is limited.
If each thread waits for 1s before ending it can be assumed that the available resources are eaten up faster then if the thread exited immediately. So if resources are exhausted the thread's creation simply fails, which the code ignores, but just tries to create the next one.
To see what is really going on the code should log the case of failed creation like this:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>

void *thread_func(void)
{
    sleep(1); /* Removing this probably lowers the number of failed creations. */
    printf("\n");
    return NULL;
}

int main(void)
{
    int i;

    for (i = 0; i < 10000; i++)
    {
        pthread_t tid;
        if (errno = pthread_create(&tid, NULL, thread_func, NULL))
        {
          perror("pthread_create() failed");
        }
    }

    pthread_exit(NULL);

    /* Never arriving here. */
    return 0;
}

The number of lines printed by the above code is expected to be 10000 in total, with some lines being empty going to stdout, and some listing the creation failure going to stderr.


text:
Q: Why am I getting an error running this code? JSON DOM manipulation Trying to populate a website given a local json file. How can I go about getting the information on the json to show up on the html website? I don't see any changes on the html and inspect on shows an error that id is not defined.
const baseUrl = 'http://localhost:3000/films';
let film = [];

document.addEventListener('DOMContentLoaded', () => {
  const getFirstFilm = () => {
    fetch(baseUrl + id)
      .then(response => response.json())
      .then(data => "{renderFirstFilm(data)}")
  }

  getFirstFilm();
})

const renderFirstFilm = (film) => {
  const poster = document.getElementById('poster')
  poster.src = film.poster
}

renderFirstFilm();
fetch('http://localhost:3000/films', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  })
  .then((response) => response.json())
  .then((data) => {
    console.log('Success:', data);
  })
  .catch((error) => {
    console.error('Error:', error);
  })


text:
Q: any NPM packages to convert rich text to plain text with newlines? I'm currently working on a react project in which I use Quill editor to generate rich text, that I store in a Postgresql database, but sometimes I need a plain text version of the rich text to conduct a comparison. the problem is that I found npm packages that transform rich-text into plain text but I end up with text without newlines which is a necessity for me.
I know that quill can also provide the plain text with newlines but in order to do so when I get the stored text from the database, I need to create an instance of quill editor and mount it on the DOM the call the getText() function.
here is a clarification example:
entry:
illustration of the entry
generated HTML string:
"
Lorem Ipsum is simply dummy text of the

printing
"

plain text after conversion:

"Lorem Ipsum is simply dummy text of theprinting"

plain text I would want to get:

"Lorem Ipsum is simply dummy text of the \nprinting\n"

is there an npm package that can do the job or I should write a function to do so.
sorry for the long boring details, Thank you.

A: You can use the html-to-formatted-text package.


text:
Q: trace the data flow when the executable is running I am practicing reversing skill using OLLdbg under windows.
there is an interactive window asking you input, let's say "serial number". My question is when user operate on the window, it is hard to locate related data flow within the debugger window. For example, if I click "F9", we can view the instruction flow; but When inputing on the window, I can't know which instructions have been executed.
My target is to find some jump instruction and change it, so that I can bypass the correct input requirement. I think the instruction should be quite close to instruction related to arg#, and related to TEST command.
Looking for hint or trick. Thanks.

A: One thing you could do is type something in the text field and then use an application such as Cheat Engine to find out where in the memory these characters are stored. Then you can put a memory (on access) breakpoint on the address of the first character in ollydbg. Then press the button that verifies the serial. When an instructions accesses this part of the memory it will break. You're inside a part of the code that verifies your string. Now from here you have to try to understand what the code is doing to find the instruction you want to alter.
Depending on how secure the application is, this will work. With a more secure application this most likely won't work. When your just starting reverse engineering I suggest you find some easy applications made for cracking and work your way to the more secure applications. A site where you can find many of these "crackmes" is crackmes.de. Also i can suggest lene151's tutorials here. Some of the best tutorials I've seen on reverse engineering.


text:
Q: Transcript a C bitwise operation to JS I'm trying to transcript the following C code to JavaScript, but I'm not getting it.
#include <stdio.h>
#include <stdlib.h>

long long seed;
int next(int bits) {
 seed=(seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
 return (int)(seed >> (48 - bits));
}

void main (void) {
    seed = 0;
    for (int i=0;i<20;i++) {
        printf ("%d\n", next(31));
    }
}

This was my try but I got different results from the C code:
let seed;
function next(bits) {
 seed = (seed * 0x5DEECE66D + 0xB) & ((1 << 48) - 1);
 return (seed >> (48 - bits));
}

seed = 0;
for ( let i=0; i<20; i++ ) {
    console.log( next(31) );
}

How can I do this?

A: You can use BigInt in javascript with BigInt() and n appended to the number literals:
let seed = 0n;

function next(bits) {
  seed = (seed * BigInt(0x5deece66d) + BigInt(0xb)) & ((1n << 48n) - 1n);
  return seed >> (48n - bits);
}

for (let i = 0; i < 20; i++) {
  console.log(next(31n));
}

Output:
0n
2116118n
89401895n
379337186n
782977366n
196130996n
198207689n
1046291021n
1131187612n
975888346n
500746873n
1785185521n
2000878121n
1219898729n
1194203485n
109160704n
1647229822n
40619231n
541938462n
640373553n


text:
Q: DataGridColumn Sorting in ActionScript3 Can somebody let me know whther we can sort this type of data in FLEX
DATA --
1ST QUARTER 2007
2ND QUARTER 2006
2ND QUARTER 2007
2ND QUARTER 2006  When i sort i need something like this ..
1ST QUARTER 2006
2ND QUARTER 2006
1ST QUARTER 2007
2ND QUARTER 2007
This is part of DataGridColumn Sorting when i apply default sort iam getting like
1st quarter 2006
1st quarter 2007
2nd quarter 2006
2nd quarter 2007
Can some body let me know whether you have logic or You have done something like this earlier .
Thanks,
Kumar

A: Are they strings...? You can define your own sorting function like this: sortCompareFunction
dataGridColumn.sortCompareFunction = compareQuarters;

private function compareQuarters(lhs:Object, rhs:Object):int
{
    var lhsArray:Array = lhs.split(" ");
    var rhsArray:Array = rhs.split(" ");
    if(lhsArray[2] > rhsArray[2])
    {
        return -1;
    }
    if(lhsArray[2] < rhsArray[2])
    {
        return 1;
    }
    if(lhsArray[0] > rhsArray[0])
    {
        return -1;
    }
    if(lhsArray[0] < rhsArray[0])
    {
        return 1;
    }
    return 0;
}

A: You'll want to use a custom sort function, ie:
<mx:DataGridColumn dataField="quarter" headerText="Quarter" width="100"
 sortCompareFunction="sortQuarter"/>

public function sortQuarter(obj1:Object, obj2:Object):int{
   //where obj1 and obj2 are your data objects containing the quarter strings, you'll need to parse them to compare to see which one is greater.
   if(obj1 < obj2){
      return -1;
   }

   if(obj1 == obj2){
      return 0;
   }

   if(obj1 > obj2){
      return 1;
   }
}

I'd suggest just breaking off the last 4 chars of the quarter strings to compare the years, and then if they're the same, compare the first chars of each string.


text:
Q: $r$ power of positive increasing sequence Let $(c_j, j\in\mathbb{N})$ be a positive increasing sequences convergent to $\infty$, ie.
$c_1\le c_2\le\cdots\le c_j$ and $\lim_{j\to\infty}c_j=\infty$.
Let $r\in [1,\infty).$
Does $(c_j^r,j\in\mathbb{N})$ converge? Why?

A: If for each $M>0$ there exists $N$ such that $n\geqslant N$ implies $a_n>M$, we say that $\lim_{n\to\infty}a_n=\infty$.
So if $\lim_{n\to\infty} c_n=\infty$, given $M>0$ there exists $N$ such that $n\geqslant N$ implies $c_n>M^{-r}$. Hence $n\geqslant N$ implies $c_n^r>M$, so that $\lim_{n\to\infty} c_n^r=\infty$.
Alternatively, we may note that the map $x\mapsto x^r$ is continuous and nondecreasing for $r>0$, so it follows immediately that $c_n^r$ is convergent.


text:
Q: C++ define macro /D with output of a shell command WINDOWS I am trying to define a macro that gets the output of a shell command, just like in Linux when using gcc and passing arguments like:
gcc ... -DSEED=$(date +%s)
This is what I tried just for testing purposes:
/DTEST=$(echo 5)
Is it even possible to do something like this in vs2017 ?

A: Yes/No/Maybe/I don't know.
int main() { return RET; }

is a valid program compiled with
/DRET=0

Live demo
Now you need to invoke your compiler in a way such that 0 is replaced by whatever value you want, but this is well outside the scope of C++.
What about bash for windows + CMake?


text:
Q: What is it relation between fetch and post? I dont have any problem about executing program. I have question about two parameters been in different place in file and about their relation. I have a html file:
<!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">
<title>Document</title>

Registration

<form id="reg-form">
<input type="text" id="username" autocomplete="off"
placeholder="Username">
<input type="password" id="password" autocomplete="off"
placeholder="Password">
<input type="submit" value="Submit Form">
</form>

and i have a js file:
const express = require('express')
const path = require('path')
const mongoose = require('mongoose')
const User = require('./model/user')
const bcrypt = require('bcrypt')

mongoose.connect('mongodb://localhost:27017/login-app-db',{
   useNewUrlParser:true,
   useUnifiedTopology:true
})
 const app = express()

 app.use('/', express.static(path.join(__dirname, 'static')))
 app.use(express.json())

 app.post('/api/register', async(req,res)=>{
 console.log(req.body)
 res.json({status:'ok'})

})
app.listen(9999,()=>{
 console.log('Server up at 9999')
})

I have a button when I click that it shows me the values been in username and password input in a terminal with console.log.
But the place that I didn't understand is
 const result = await fetch('/api/register')

and
 app.post('/api/register', async(req,res)=>

which one is processing first and what is that "/api/register". Is it a made-up path for providing communication between Html and js when I click the button if it is like that how is working in behind exactly?

A: In your Node.js code, you create an Express server and set up request handlers, app.post('/api/register' ...) being one of them.
In your client code, when you're calling fetch('/api/register', ..., the browser makes a request to http://<your-domain>/api/register and processes the response (if any).
Express is a web-server framework that is built on top of Node.js http module and provides a good amount of utility in terms of routing. Whenever an incoming request is received on the right port by the server, it gets filtered matched against all the handlers you have by comparing its method and path with the ones in the handlers. If a matching handler is found, it gets executed called with the request object passed as the argument. In your case, any POST request made to http://<your-domain>/api/register will be processed by that handler. (you can read more about Express routing here)
/api/register is indeed just a made-up path that provides a structure to your web application API and enforces an interfacing convention - it could've been just as well called /signup or /api/user/registration. People would usually follow REST architecture style when making those up though, where the path would define a resource in the system and method would define the kind of operation applied to the resource. That said, you're free to design your APIs in any way that makes the most sense to you, as long as the convention is enforced in all parts of the system (i.e. client code and server code).


text:
Q: Examples of non-trivial Kazhdan-Lusztig polynomials
I'm looking for examples of non-trivial Kazhdan-Lusztig polynomials, specifically in the case where the Coxeter system is a Weyl group.

For example, the simplest polynomial with non-trivial $q$-coefficient is $p_{tsut,e}(q) = 1 + q$ in type $A3.$ Where can we find the first non-trivial coefficient of $q^2$, and $q^3...$ etc.

A: Already in the case of finite symmetric groups, one can find any polynomial with non-negative integral coefficients and constant term 1 as KL polynomial for some pair of group elements.     See the paper by Patrick Polo here.    But specific examples take a little more work.    Check the old tables for Weyl groups (and affine Weyl groups) on Mark Goresky's webpage at IAS here.


text:
Q: How to get closest n rows for specific row in table? I have a table foo with its primary key id and some other columns.
My goal is to find for instance rows with id=3 and id=4 and rows with id=6 and id=7 for row with id=5 - in case I would like to find 2 closest previous and next rows.
In case there is only one or no such rows (e.g. for id=2 there is only previous row) I would like to get only possible ones.
The problem is there can be some rows missing.
Is there a common practice to make such queries?

A: I would try the following:
SELECT * FROM table WHERE id > ? ORDER BY id ASC LIMIT 2

followed by
SELECT * FROM table WHERE id <= ? ORDER BY id DESC LIMIT 2

You may be able to combine the above into the following:
SELECT * FROM table WHERE id > ? ORDER BY id ASC LIMIT 2
UNION
SELECT * FROM table WHERE id <= ? ORDER BY id DESC LIMIT 2

A: This is a possible solution by numbering all the records and fetching those where row number is 2 rows greater or lower than the selected ID.

create table foo(id int);
insert into foo values (1),(2),(4),(6),(7),(8),(11),(12);

-- using ID = 6

with rnum as
(
    select id, row_number() over (order by id) rn
    from foo
)
select *
from   rnum
where  rn >= (select rn from rnum where id = 6) - 2
and    rn <= (select rn from rnum where id = 6) + 2;

id | rn
-: | -:
 2 |  2
 4 |  3
 6 |  4
 7 |  5
 8 |  6

-- using ID = 2

with rnum as
(
    select id, row_number() over (order by id) rn
    from foo
)
select *
from   rnum
where  rn >= (select rn from rnum where id = 2) - 2
and    rn <= (select rn from rnum where id = 2) + 2;

id | rn
-: | -:
 1 |  1
 2 |  2
 4 |  3
 6 |  4

dbfiddle here

A: I think this would fit your description.
Select * from table where id between @n-2 and @n+2 and id <> @n

A: One way is this:
with your_table(id) as(
    select 1 union all
    select 2 union all
    select 4 union all
    select 5 union all
    select 10 union all
    select 11 union all
    select 12 union all
    select 13 union all
    select 14
)

select * from (
    (select * from your_table where id <= 10 order by id desc limit 3+1)
    union all
    (select * from your_table where id > 10 order by id limit 3)
) t
order by id

(Here 10 is start point and 3 is n rows you want)


text:
Q: Oracle Error (exceeded simultaneous SESSIONS_PER_USER limit) I have a .Net application with Oracle database. I received the below error while trying to run a report in my application. Request anyone to check and advice if there is a fix for this problem.
Also note that I have spoken to my DBA and he says that there is something in the .Net code that is not ending the sessions.
The error message is :
ORA-2391: exceeded simultaneous SESSIONS_PER_USER limit
Let me know if you need any more info


text:
Q: Xpath targeting starting from CSS I'd like to target in XPath (to be used in xmlImport for Google Spreadsheets) the element that in CSS would be .forum-table tr:nth-of-type(1) .forum-number-topics:

            Forum
            Topics
            Posts
            Last post

             No new

 Settimana 1

20

            171
            n/a

             No new

 Settimana 2

21

            143
            n/a

             No new

 Settimana 3

20

            91
            n/a

I specified tr:nth-of-type(1) because I need the same syntax in Xpath (with numeric entity).

A: As a literal translation, I would try
//*[contains(@class, 'forum-table')]//tr[1]//*[contains(@class, 'forum-number-topics')]

Note that this will select both  and
 elements, e.g. where you have

in the input. Also note that this assumes you don't have "ornery" classes that contain forum-table but not as a whole class name, e.g. if your first table element had class="forum-table-forums" without forum-table in there. If you need to be more rigorous about matching class names, you can do
//*[contains(concat(' ', @class, ' '), ' forum-table ')]//tr[1]//
  *[contains(concat(' ', @class, ' '), ' forum-number-topics ')]

(line broken for clarity).


text:
Q: Is Major Nelson gay in I Dream of Jeannie Based on this comment: What are the minimal limits of Jeannie's power in I Dream of Jeannie?
Jeannie is always trying to get Major Nelson to marry her. As I remember, he plays some lip-service to the idea but I don't remember this happening. (granted, I probably never saw the ending of the series)
Are there are allusions or subtle suggestions through the show that would suggest that Major Nelson is gay?

A: While well-enough researched and presented, for the most part, these comments miss the point. It's not 'literal' gayness we're talking about here. The character Hagman portrays in 'Jeannie' is desperate not to be 'outed', and let's face it - that's pretty gay. Almost every episode revolves around anxiety that his secret will be revealed. That secret is Jeannie's presence in his life, not being gay, but she can be seen as a stand-in. Today most of us in the gay community see the closet receding rapidly in our rear view mirrors, and good riddance. But during the time this show was originally conceived and aired, people's lives could be ruined if the truth about their sexuality came out. The situations the show's characters get into are over the top and implausible, but the fundamental similarity remains that gay men sometimes went to absurd lengths to deflect suspicion and hide evidence - and inconvenient people - that could jeopardize their assumption of a straight identity.

A: In the first episode of the I Dream of Jeannie, Major Nelson has a fiancée, Melissa.  She is the  daughter of General Stone, Nelson's commanding officer.  As a gay man in the 1960's this could be considered useful camouflage, but as an astronaut routinely being sent on dangerous missions, Nelson didn't need the camouflage or the entanglements that came with it.  He certainly didn't need his CO's daughter complaining to her father that he was indifferent to her or couldn't perform in the sack.  So Major Nelson being affianced to his commanding officer's daughter ultimately does not seem indicative of homosexuality.
Nelson's amazing restraint in not taking advantage of a willing slave woman despite years of provocation must be attributed to the sensibilities of the 1960's TV audience, I think.  I'm amazed that the premise of the show made it past the television censors of the day.  Nelson and Jeannie's relationship had to remain chaste else the carefully constructed innocent hilarity of the situation would immediately collapse into depravity.

A: No, as far as we (the viewer) can tell, Major Nelson is not depicted as gay.  I think his reluctance to marry Jeannie (even after he split from his first fiancée) stems from the fact that he's a stand up guy who doesn't want to take advantage of her.  He does eventually fall for Jeannie, and they were married in the season five episode "The Wedding".

Major Nelson and Jeannie finally get married, with Major Healey as best man — but not without problems: Jeannie's image can't be photographed so Jeannie substitutes a mechanical mannequin for herself.

The series ended in 1970, but there were two TV movies, one in 1985 and one in 1991, so apparently the marriage lasted for quite some time.  The first TV movie reveals that Tony and Jeannie have a teenage son.

A: I've been watching this show on itunes and came to a much different conclusion, though I think I may have liked it if the Tony stood for a gay character. Many of the episodes revolve around Jeannie's jealousy of the other women Tony dates. Rather than showing lots of restraint, I find that Tony doesn't have that much, though he does follow a strict kind of an honor code. He and Roger oggle every young woman that walks past them, and although I understand that Jeannie inserted herself into his life against his wishes, they are often seen making out and dating - he is apparently attracted to her and cares for her. Yet he coldly continues to remind her that she may not keep him from dating other women, and ironically seems OK with attempting to keep her in her bottle for days or weeks at a time. Yeah, I get it that it's coming from the Master/Jeannie situation comedy, to paint her as the impulsive trouble maker to his straight-laced career aspirations, but I bring it up to conclude that yes, the "secret" of having a Jeannie in a bottle is symbolic, but it is symbolic of the secret of living with a woman he's not married to, which was not as socially acceptable then. If I understand correctly they get married in the last season, which most likely released the most significant tension and lead to the end of the show.

A: The show is an allegory of what it was like to be gay in the 60s, particularly if you were in the military. In an allegory everything is symbolic. So don't take Jeannie literally. She doesn't even exist. She is just a symbol of Tony and Roger's homosexuality. They need to hide Jeannie from the base psychologist so they can continue being Air Force officers and also astronauts. Their goal is to eventually walk on the moon. This will never happen if Dr. Bellows discovers that they have a genie. The same thing would happen if Dr. Bellows discovered that they were gay. They would be out of the military, and their dream of walking on the moon would be over. Just look at the fear the two men suffer anytime Dr.. Bellows is close to discovering Jeannie's  existence. This is the same fear any gay man in the military would have if the base  psychologist was close to realizing that they were gay.   One of the first things that Jeannie ever says to Tony when she's in his house in Cocoa Beach is, "What you need is a beard." The expression "a beard" can mean the woman a gay man dates so no one will suspect that he is gay.


text:
Q: writeStream() is printing null values in batches data even i supply proper json data in kafka through writeStream() I am trying to convert json using schema and printing values to console, but writeStream() is printing null values in all columns even i gave proper data.
data i am giving to kafka topic ..
{"stock":"SEE","buy":12,"sell":15,"profit":3,quantity:27,"loss":0,"gender":"M"}
{"stock":"SEE","buy":12,"sell":15,"profit":3,quantity:27,"loss":0,"gender":"M"}
{"stock":"SEE","buy":12,"sell":15,"profit":3,quantity:27,"loss":0,"gender":"M"}

Below is my scala code..
 val readStreamDFInd = sparkSession.readStream.format("kafka").option("kafka.bootstrap.servers", "localhost:9092")
  .option("subscribe", "IndiaStocks")
  .option("startingOffsets", "earliest")
  .load()

//readStreamDFInd.printSchema()
val readStreamDFUS = sparkSession.readStream.format("kafka").option("kafka.bootstrap.servers", "localhost:9092")
  .option("subscribe", "USStocks")
  .option("startingOffsets", "earliest")
  .load()

val schema = new StructType()
  .add("stock", StringType)
  .add("buy", IntegerType)
  .add("sell", IntegerType)
  .add("profit", IntegerType)
  .add("quantity", IntegerType)
  .add("loss", IntegerType)
  .add("gender", StringType)

val stocksIndia = readStreamDFInd.selectExpr("CAST(value as STRING) as json").select(from_json($"json", schema).as("data")).select("data.*")
val stocksUSA = readStreamDFUS.selectExpr("CAST(value as STRING) as json").select(from_json($"json", schema).as("data")).select("data.*")
stocksIndia.printSchema() stocksUSA.writeStream
  .format("console")
  .outputMode("append").trigger(Trigger.ProcessingTime("5 seconds"))
  .start()
  .awaitTermination()

A: The code works fine as you can also see in the book.
Looking at the documentation of the from_json function the null values are created because the string is unparseable.
=> You are missing the quotations around the quantity field in your json string.

A: Problem is in your kafka data, quantity column should be in quotes. Please check below.
{"stock":"SEE","buy":12,"sell":15,"profit":3,"quantity":27,"loss":0,"gender":"M"}
{"stock":"SEE","buy":12,"sell":15,"profit":3,"quantity":27,"loss":0,"gender":"M"}
{"stock":"SEE","buy":12,"sell":15,"profit":3,"quantity":27,"loss":0,"gender":"M"}


text:
Q: Django how to sort Datefield by order of Day-month to show birthday list I want to accept users birthday and have a page which shows everyone's birthday ignoring which year they were born in Heres my models.py for CustomUser:
from datetime import datetime, date

from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    # First/last name is not a global-friendly pattern
    name = models.CharField(blank=True, max_length=255)
    birth_date = models.DateField(("Birth Date"), default=date.today)

    def __str__(self):
        return self.email

Here is my views.py logic:
def birthdaylist(request):
    if(request.user.is_authenticated):

        users=CustomUser.objects.order_by('birth_date')[:]
    # ignore the line below
    #   users= CustomUser.objects.extra(select={'birthmonth':'birth_date'},order_by=['birthmonth'])
        context={
            'users':users
        }
        return render(request,'dashboard/birthdaylist.html',context=context)
    else:
        return redirect('login')

Here is my forms.py:
import datetime

from bootstrap_datepicker_plus import DatePickerInput
from django import forms

from django.contrib.auth.forms import UserCreationForm, UserChangeForm

from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        now = datetime.datetime.now()
        fields = ('username', 'email', 'gender', 'security_question', 'answer', 'birth_date', 'resume')
        widgets={
            'birth_date' :DatePickerInput(
                options={
                    'maxDate':str(datetime.datetime.now()),
                    #this needs width positioning
                }
            )
        }

I am using bootstrap datepicker plus widget to pick the date. Can someone help me on how do I get the desired result in my views .py? I feel something needs to be added in my order.py if u need me to add anything then comment. PS: I am using Django 2.0.6 version

A: Try
users=CustomUser.objects.extra(
      select={
      'month': 'extract (month from birth_date)',
      'day': 'extract (day from birth_date)'},
       order_by=['month','day']
)

How about this one?
from django.db.models.functions import Extract

users=CustomUser.objects.annotate(
     month=Extract('birth_date','month'),
     day=Extract('birth_date','day')
  ).order_by('month','day')


text:
Q: How can I fix the vertical position of a JComboBox PopUp with separators on MacOS? I'm using the "Add a JSeparator together with the ComboBoxItem-to-render on a JPanel"-ListCellRenderer approach to display separators in a JComboBox.
I noticed that the algorithm on MacOS to vertically center the selected item on the PopUp gets confused by the changed height of the JSeparator-ComboBoxItems.
Is there a way to fix the wrong position of the PopUps seen on the right-hand side of this screenshot? If the "Spain"-Item is selected it is painted slightly too high; the "Cars"-Item much too high.

The sourcecode:
import java.awt.BorderLayout;
import java.awt.Component;
import java.util.Arrays;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.ListCellRenderer;

public class JComboBoxSeparatorMacOs {

    public static void main(String[] args) {
    JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(new JComboBox<String>("A,Normal,Combo Box,without Separators".split(",")), BorderLayout.WEST);

        JComboBox<String> comboBox = new JComboBox<String>("Spain,Italy,Car,Peru".split(","));
        ListCellRenderer<String> renderer = new SeparatorListCellRenderer<String>(comboBox.getRenderer(), 0);
        comboBox.setRenderer(renderer);
        frame.add(comboBox);

        frame.pack();
        frame.setVisible(true);
    }
}

class SeparatorListCellRenderer<E> implements ListCellRenderer<E> {
    private final ListCellRenderer<? super E> delegate;
    private final int[] indexes;
    private final JPanel panel = new JPanel(new BorderLayout());

    public SeparatorListCellRenderer(ListCellRenderer<? super E> delegate, int... indexes) {
        Arrays.sort(indexes);
        this.delegate = delegate;
        this.indexes = indexes;
        panel.setOpaque(false);  //for rendering of selected item on MSWindows
    }

    @Override
    public Component getListCellRendererComponent(JList list, E value, int index, boolean isSelected, boolean cellHasFocus) {
        panel.removeAll();
        panel.add(delegate.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus));
        if (Arrays.binarySearch(indexes, index) >= 0)
            panel.add(new JSeparator(), BorderLayout.PAGE_END);

        return panel;
    }
}

A: This looks like a feature of com.apple.laf.AquaComboBoxUI that tries to expose more of the list surrounding the current selection. It just doesn't expect the list to include a a JSeparator having a com.apple.laf.AquaPopupMenuSeparatorUI.
As an alternative, consider one of these approaches:

*

*Use HTML to decorate the entry, e.g.
new JComboBox("Spain,Italy,Car,Peru"…

*Alter the Font in the renderer, as shown here.

A: *

*I think that this issue has nothing with Platoform / Native OS / Look and Feel

*JComboBox, JPopup could / couldn't be restricted, changed, overrode some of methods in some Swing GUI Builders

*for JComboBoxes JPopup to use Combo Box Popup by @camickr

*maybe JSeparator in Renderer could be little bit different
a) for possible output from ActionListener or ItemListener
b) notice this couldn't works for proper KeyListener added to the derived JList (maybe not important)
images

code
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class ComboBoxWithSeparator extends JFrame {

    private static final long serialVersionUID = 1L;
    final String SEPARATOR = "SEPARATOR";

    public ComboBoxWithSeparator() {
        super("Block ComboBox Example");
        String[][] str = {{"A", "B", "C"}, {"1", "2", "3"}, {"abc", "def", "ghi"}};
        JComboBox combo = new JComboBox(makeVectorData(str));
        combo.setRenderer(new ComboBoxRenderer());
        combo.addActionListener(new BlockComboListener(combo));
        combo.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXX");
        setLayout(new FlowLayout());
        JComboBox combo1 = new JComboBox(makeVectorData(str));
        combo1.setRenderer(new ComboBoxRenderer());
        combo1.addActionListener(new BlockComboListener(combo));
        combo1.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXX");
        BoundsPopupMenuListener listener = new BoundsPopupMenuListener(true, true);
        combo1.addPopupMenuListener(listener);
        combo1.setPrototypeDisplayValue("ItemWWW");
        add(combo);
        add(combo1);
        pack();
        setVisible(true);
    }

    private Vector<String> makeVectorData(String[][] str) {
        boolean needSeparator = false;
        Vector<String> data = new Vector<String>();
        for (int i = 0; i < str.length; i++) {
            if (needSeparator) {
                data.addElement(SEPARATOR);
            }
            for (int j = 0; j < str[i].length; j++) {
                data.addElement(str[i][j]);
                needSeparator = true;
            }
        }
        return data;
    }

    public static void main(String args[]) {
        try {
            for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(laf.getName())) {
                    UIManager.setLookAndFeel(laf.getClassName());
                    //UIManager.getLookAndFeelDefaults().put("Panel.background", Color.white);
                    //UIManager.getLookAndFeelDefaults().put("Button.contentMargins", new InsetsUIResource(0,0,0,0));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ComboBoxWithSeparator frame = new ComboBoxWithSeparator();
        frame.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    private class ComboBoxRenderer extends JLabel implements ListCellRenderer {

        private static final long serialVersionUID = 1L;
        private JSeparator separator;

        public ComboBoxRenderer() {
            setOpaque(true);
            setBorder(new EmptyBorder(1, 1, 1, 1));
            separator = new JSeparator(JSeparator.HORIZONTAL);
        }

        @Override
        public Component getListCellRendererComponent(JList list, Object value,
                int index, boolean isSelected, boolean cellHasFocus) {
            String str = (value == null) ? "" : value.toString();
            if (SEPARATOR.equals(str)) {
                return separator;
            }
            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            setFont(list.getFont());
            setText(str);
            return this;
        }
    }

    private class BlockComboListener implements ActionListener {

        private JComboBox combo;
        private Object currentItem;

        BlockComboListener(JComboBox combo) {
            this.combo = combo;
            combo.setSelectedIndex(0);
            currentItem = combo.getSelectedItem();
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String tempItem = (String) combo.getSelectedItem();
            if (SEPARATOR.equals(tempItem)) {
                combo.setSelectedItem(currentItem);
            } else {
                currentItem = tempItem;
            }
        }
    }
}


text:
Q: Explanation on the proof for $\bar{S} = \mathrm{cl } S $. Let $S$ be a set and let $\mathcal{A} = \{\mathcal{A_{\alpha}} \, : \, S \subseteq \mathcal{A}_{\alpha} \, \, \mathrm{and} \, \, \mathcal{A}_{\alpha} \, \, \mathrm{is} \, \, \mathrm{closed}\}$ where $\alpha \in A$ and $A$ is a nonempty indexing set.
Let $\bar{S} = \bigcap_{\alpha \in A} \, A_{\alpha}$, which denotes the intersection of all the closed sets containing $S$.
Here is a picture of the problem with the teacher's solution:

My question is with regards to the two sentences preceding the last sentence of the teacher's proof. From the assumption that $x \in S'\setminus S$ and that every neighborhood of $x$ has a nonempty intersection with $S$, she quickly concludes that $x \in \mathcal{A}_{\alpha}$ for every $\alpha$. But I do not see how this immediately follows.

A: $x$ is a limit point of $S$.  (that's what every neighborhood of $x$ having a nonempty intersection with $S$ implies.)  So for every $A_{\alpha}$, $S \subset A_{\alpha}$ so every neighborhood of $x$ has a nonempty intersection with $A_{\alpha}$.  So $x$ is a limit point of $A_{\alpha}$.  As $A_{\alpha}$ is closed, $x \in A_{\alpha}$.
===
I think your professor simply forgot to point out $x$ is a limit point of $A_{\alpha}$.  The funny thing is when I typed my answer, I left it out too.  Even though I was thinking that was the essential point.
=====
I think a much easier way to put this would be
Lemma 1)  $cl(S) S \cup S'$ is closed.
Lemma 2) If $S \subset A$ and $A$ is closed.  Then $cl(S) \subset A$.
Pf: If $x \in S$ then $x \in A$.  If $x \in S'$ then $x$ is a limit point of $S$ so every neighborhood of $x$ intersects $S$ so every neighborhood of $x$ intersects $A$ as $A$ is a superset of $S$.  So $x$ is a limit point of $A$ so as $A$ is closed, $x \in A$.  So $x \in cl(S) \implies x \in A$ so $cl(S) \subset A$.
Theorem:  As stated.
Proof is now trivial.  $S \subset cl(S)$ closed.  So $cl(S) \in \mathcal A$ so $\overline S = \cap \mathcal A_{\alpha} \subset cl(S)$.
As $cl (S) \subset A_{\alpha}$ for all $\alpha$, $cl (S) \subset \cap \mathcal A_{\alpha}= \overline S$


text:
Q: Vim yank span given column start and end position I'm wondering in vim, when given a start and end column position, is there a way to yank corresponding content starts from the start position to end.
for example, given a line in vim
aaaabbbbcccc

*

*start = 4

*end = 8

I want the yanked content is bbbb
The visual mode does finish it, but I think there may a vim command for it

A:
I think there may a vim command for it

The v to enter visual mode, the motions to extend the area, and the y to yank are all "vim commands".
Assuming the cursor is somewhere on the line, you can do this with visual mode:
5|
v8|
y

In command-line mode, it would look like this:
:call feedkeys('5|v8|y')

In a script, assuming the start and end are variable, it would look like this:
call feedkeys(start .. '|v' .. end .. '|y')

See :help | and :help feedkeys().
Of note, yanking is exclusive in operator-pending mode so, if you want to yank up to and including column 8, you need to involve visual mode somehow, where yanking is inclusive. Explicitly, as above, or implicitly, with 5|yv8|. It doesn't really change anything to the problem at hand but it is a feature I don't often see mentioned. See :help forced-motion.

A: We can use yank with motion 5|y9| for this without v.

*

*5| go to column 5.

*y9| yank until column 9.

                                                        *y* *yank*
["x]y{motion}           Yank {motion} text [into register x].  When no
                        characters are to be yanked (e.g., "y0" in column 1),
                        this is an error when 'cpoptions' includes the 'E'
                        flag.


text:
Q: Testing with Thread.sleep What are the recommended approaches to using Thread.sleep() to speed up tests.
I am testing a network library with a retry functionality when connections are dropped or timeout errors occur, etc.  The library however, uses a Thread.sleep() between the retries (so it won't connect thousands times while the server is restarting).  The call is slowing the unit tests significantly, and I wonder what the options are to override it.
Note, I'm open to actually changing the code, or using a mocking framework to mock Thread.sleep(), but would like to hear your opinions/recommendation first.

A: I just faced a similar issue and I created a Sleeper interface to abstract this away:
public interface Sleeper
{
    void sleep( long millis ) throws InterruptedException;
}

The default implementation uses Thread.sleep():
public class ThreadSleeper implements Sleeper
{
    @Override
    public void sleep( long millis ) throws InterruptedException
    {
        Thread.sleep( millis );
    }
}

In my unit tests, I inject a FixedDateTimeAdvanceSleeper:
public class FixedDateTimeAdvanceSleeper implements Sleeper
{
    @Override
    public void sleep( long millis ) throws InterruptedException
    {
        DateTimeUtils.setCurrentMillisFixed( DateTime.now().getMillis() + millis );
    }
}

This allows me to query the time in a unit test:
assertThat( new DateTime( DateTimeUtils.currentTimeMillis() ) ).isEqualTo( new DateTime( "2014-03-27T00:00:30" ) );

Note that you need to fix the time first using DateTimeUtils.setCurrentMillisFixed( new DateTime( "2014-03-26T09:37:13" ).getMillis() ); at the start of your test and restore the time again after the test using DateTimeUtils.setCurrentMillisSystem();

A: Make the sleeping time configurable through a setter, and provide a default value. So in your unit tests, call the setter with a small argument (1 for example), and then execute the method that would call Thread.sleep().
Another similar approach is to make if configurable via a boolean, so that Thread.sleep() isn't called at all if the boolean is set to false.

A: Create some retry delay type that represents the policy for retry delays. Invoke some method on the policy type for the delay. Mock it as you like. No conditional logic, or true/false flags. Just inject the type that you want.
In ConnectRetryPolicy.java
public interface ConnectRetryPolicy {
    void doRetryDelay();
}

In SleepConnectRetryPolicy.java
public class final SleepConnectRetryPolicy implements ConnectRetryPolicy {
    private final int delay;
    public SleepConnectRetryPolicy(final int delay) {
        this.delay = delay;
    }

    @Override
    public void doRetryDelay() {
        try {
            Thread.sleep(delay);
        } catch (InterruptedException ie) {
            log.error("connection delay sleep interrupted", ie);
        }
    }
}

In MockConnectRetryPolicy.java
public final class MockConnectRetryPolicy implements ConnectRetryPolicy {
    @Override
    public void doRetryDelay() {
        // no delay
    }
}

A: I would argue why are you trying to test Thread.sleep. It seems to be me you're trying to test the behaviour as a consequence of some event.
i.e. what happens if:

*

*connection timeout

*connection dropped

If you model code based on events then you can test what should happen should a particular event occurred rather than having to come up with a construct that masks the concurrent API calls. Else what are you really testing? Are you testing how your application reacts to different stimuli or simply testing the JVM is working correctly?
I agree with the other readers that sometimes it's useful to put an abstraction around any code time or thread related i.e. Virtual clock http://c2.com/cgi/wiki?VirtualClock so you can mock out any timing/concurrent behaviour and concentrate on the behaviour of the unit itself.
It also sounds like you should adopt a state pattern so you object has specific behaviour depending on what state it's in. i.e AwaitingConnectionState, ConnectionDroppedState. Transition to different states would be via the different events i.e. timeout, dropped connection etc. Not sure if this overkill for your needs but it certainly removes a lot of conditional logic which can make the code more complicated and unclear.
If you approach this way, then you can still test behaviour at the unit level whilst still testing in situ with an integration test or acceptance test later.

A: It is usually a good idea to delegate time-related functionality to a separate component. That include getting the current time, as well as delays like Thread.sleep(). This way it is easy to substitute this component with mock during testing, as well as switch to a different implementation.

A: Eugene is right, make your own component to wrap the system that is out of your control Just done this myself thought I'd share, this is known as 'SelfShunt' check this out:
Generator is a class that when you call getId() it returns the current system time.
public class GeneratorTests implements SystemTime {

    private Generator cut;
    private long currentSystemTime;

    @Before
    public void setup(){
        cut = Generator.getInstance(this);
    }

    @Test
    public void testGetId_returnedUniqueId(){
        currentSystemTime = 123;

        String id = cut.getId();

        assertTrue(id.equals("123"));
    }

    @Override
    public long currentTimeMillis() {
        return currentSystemTime;
    }
}

We make the test class 'SelfShunt' and become the SystemTime component that way we have full control of what the time is.
public class BlundellSystemTime implements SystemTime {

    @Override
    public long currentTimeMillis(){
        return System.currentTimeMillis();
    }
}

We wrap the component that isn't under our control.
public interface SystemTime {

    long currentTimeMillis();

}

Then make an interface so our test can 'SelfShunt'


text:
Q: Wifi is hard locked I just got a new laptop and installed Ubuntu on it. Wi-fi worked fine on Windows 8, but now it says that it's disabled by a hardware switch. rfkill unblock all did nothing. Many people have suggested installing something, but there's no ethernet port. Tried using a USB dongle, that's blocked too.
Do I have to go spend $25 on an ethernet to USB adapter I'll only use once, or is there another way?
Here's the output of rfkill list all:
0: ideapad_wlan: Wireless LAN
        Soft blocked: no
        Hard blocked: yes
1: ideapad_bluetooth: Bluetooth
        Soft blocked: no
        Hard blocked: yes
2: phy0: Wireless LAN
        Soft blocked: no
        Hard blocked: no
7: hci0: Bluetooth
        Soft blocked: no
        Hard blocked: no

A: This has been fixed for Yoga in kernel 3.16.
For Ubuntu 14.04 just upgrade your kernel to 3.16 by
sudo apt-get install linux-generic-lts-utopic

or to 3.19 by
sudo apt-get install linux-generic-lts-vivid

A: "hard lock" actually means what it says: you have a switch on your machine itself, in the bios or on your keyboard to lock wifi.
Look around your laptop.

A: I had the same problem. After trying many different suggestions, I found out that my wifi have been turned off by the "Radio on/off" key on my keyboard (usually having an antenna or radio tower symbol on it; on Dell laptop, Fn+F2 key-combination).
I see that "MUY Belgium" has suggested that, too; I would up-vote his answer, if I had enough reputation score.


text:
Q: Is there a way to monitor what processes or programs might be editing the web.config? I have an issue on one of my servers where we are having recycling happening that is not planned. Further inspection results in the following errors:

Event: Application End
Process ID: 8716

Shut Down Message: HostingEnvironment initiated shutdown
HostingEnvironment caused shutdown

Shut Down Stack:    at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
   at System.Environment.get_StackTrace()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownWithoutDemand()
   at System.Web.Hosting.PipelineRuntime.StopProcessing()

Shut Down Message: CONFIG change
HostingEnvironment initiated shutdown
CONFIG change
HostingEnvironment caused shutdown
Change in C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\appserver\347d6bd9\aed72866\hash\hash.web

Shut Down Stack:    at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
   at System.Environment.get_StackTrace()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownWithoutDemand()
   at System.Web.HttpRuntime.ShutdownAppDomain(String stackTrace)
   at System.Web.Configuration.HttpConfigurationSystem.OnConfigurationChanged(Object sender, InternalConfigEventArgs e)
   at System.Configuration.Internal.InternalConfigRoot.OnConfigChanged(InternalConfigEventArgs e)
   at System.Configuration.BaseConfigurationRecord.OnStreamChanged(String streamname)
   at System.Web.Configuration.WebConfigurationHostFileChange.OnFileChanged(Object sender, FileChangeEvent e)
   at System.Web.DirectoryMonitor.FireNotifications()
   at System.Web.Util.WorkItem.CallCallbackWithAssert(WorkItemCallback callback)
   at System.Web.Util.WorkItem.OnQueueUserWorkItemCompletion(Object state)
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

Shut Down Message: CONFIG change
HostingEnvironment initiated shutdown
CONFIG change
HostingEnvironment caused shutdown
Change in C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\appserver\347d6bd9\aed72866\hash\hash.web

Shut Down Stack:    at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
   at System.Environment.get_StackTrace()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownWithoutDemand()
   at System.Web.HttpRuntime.ShutdownAppDomain(String stackTrace)
   at System.Web.Configuration.HttpConfigurationSystem.OnConfigurationChanged(Object sender, InternalConfigEventArgs e)
   at System.Configuration.Internal.InternalConfigRoot.OnConfigChanged(InternalConfigEventArgs e)
   at System.Configuration.BaseConfigurationRecord.OnStreamChanged(String streamname)
   at System.Web.Configuration.WebConfigurationHostFileChange.OnFileChanged(Object sender, FileChangeEvent e)
   at System.Web.DirectoryMonitor.FireNotifications()
   at System.Web.Util.WorkItem.CallCallbackWithAssert(WorkItemCallback callback)
   at System.Web.Util.WorkItem.OnQueueUserWorkItemCompletion(Object state)
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

The issue we are seeing appears to be that something is editing the web.config file and prompting the recycling to occur. Is there a good way to monitor the config file and see what process or piece of software or potentially user is editing that file?
Thanks,
ThatOneGuy


text:
Q: Disabling Column in Entity Framework Code First I'm using Entity Framework to insert data into 2 different databases. There are a few columns that are present in one of the databases but not the other. Their data types are not nullable (int and float).
I don't use these columns (when they are present) in my code. Meaning I only insert 0 as the data for them but I can't send null obviously.
Is there a way for me to insert data with ease without creating 2 different versions of my app for these? Ideally I'd like to just have one model with something like an attribute that says insert 0 in this column if it's available.

A: If your application runs only against one database, then you can just use an IF statement in your OnModelCreating that uses the Fluent API to .Ignore() the missing properties.
public class MyDbContextWithMissingColumns: MyDbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        if (myConfig.UseDatabaseWithoutSomeProperties)
        {
          modelBuilder.Entity<Foo>().Ignore(f => f.SomeProperty);
        }
        base.OnModelCreating(modelBuilder);
    }
}

If a single instance of your application connects to both databases, then you have to use separate DbContext subtype, as OnModelCreating only runs for the first instance of a DbContext type in an AppDomain.
EG:
public class MyDbContextWithMissingColumns: MyDbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Foo>().Ignore(f => f.SomeProperty);
        base.OnModelCreating(modelBuilder);
    }
}

A: In the repository for the database with the restricted fields create the entity:
public class MyClass
{
   int MyCommonClassID {get; set;}
   string Name {get; set;}
   [NotMapped]
   string PhoneNumber {get; set;}
}

Where the attribute [NotMapped]. is used that field will not appear in the database but you can use it everywhere else. That wat you determine what gets written at the lowest level and your application doesn't care.


text:
Q: tensor products as a quotient - construction A tensor product $N\otimes_R M$ of $R$-modules $N,M$ is defined as $F(N,M)/B(N,M)$, where $B(N,M)$ is defined as the $R$-module generated by the elements $((n_1+n_2)\otimes m)-(n_1\otimes m)-(n_2\otimes m)$ and $(n\otimes (m_1+m_2))-(n\otimes m_1)-(n\otimes m_2)$ and $(rn\otimes m)-r(n\times m)$ and $(n\otimes rm)-r(n\times m)$. Furthermore, $F(N,M)$ is defined as $\bigoplus_{n\in N,m\in M} R\cdot n\otimes m$. What would be an example for $B(N,M)$ given $N,M$?
Is $B(N,M)$ in some cases zero (a zero set) and in other cases $B(N,M)$ contains non-zero elements? I am slightly confused. Can you give an example for $B(N,M)$, which illustrates the relevance of this construction using $B(N,M)$?

A: Informally spaking, this construction may relate different elements of $F(N,M)$, if the above relationships which span $B(N,M)$ allow for a simplification. For example, in $F(N,M)$, an element such as $((n_1+n_2)\otimes m)-(n_1\otimes m)-(n_2\otimes m)$ is non-zero, but in the tensor product $F(N,M)/B(N,M)$ the latter element is an element of $B(N,M)$, so constitutes a zero element in this quotient ring. Technically speaking, the set $F(N,M)$ is spanned by $\{n\otimes_R m|n\in N,m\in M\}$. By quotienting by $B(N,M)$, the above relationships between the elements of $F(N,M)$ are introduced. Consider $$r(n\otimes m)+s(n\otimes m)+B(N,M)$$ with $s\in R$. We see that this element is $(r+s)(n\otimes m)+B(N,M)$, since $r(n\otimes m)+s(n\otimes m)$ can be written as
$$r(n\otimes m)+s(n\otimes m)=r(n\otimes m)+s(n\otimes m)+\underbrace{((r+s)(n\otimes m)-r(n\otimes m)-s(n\otimes m))}_{\in B(N,M)},$$
by using a combination of the above relationships which generate $B(N,M)$.


text:
Q: Node js - function return with undefined instead of sql result Im trying to get values from function but getting undefined as return...
function get_data(id){
  var name;
  ibmdb.open(dbcon.con, function (err,conn) {
    conn.query("select name from users where id='"+id+"'", function (err, data) {
      name = data[0].NAME;
      console.log(name) // there is the name is correct
      conn.close(function () {});
    });
  });
  return name; // there getting undefined
};

router.get('/:id', function(req, res, next) {
    res.render('u', { name: get_data(req.params.id) });
});


text:
Q: fnCallback function not able to render Server Side data in DataTable I am not able to render Jquery DataTable with paging at server side.
My DataTable structure is as follows:

$("#MyTable").DataTable({
        "bServerSide": true,
        "sAjaxSource": $("#apiUrl").attr("value") + "/myclass/myMethod",
        "sAjaxDataProp": "",
        "bProcessing": true,
        "bVisible": true,
        "order": [
            [1, "asc"]
        ],
        scrollX: true,
        "bAutoWidth": false,
        scrollCollapse: true,
        "oColReorder": {
            "iFixedColumns": 1
        },
            "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
                oSettings.jqXHR = $.ajax( {
                    "dataType": 'json',
                    "type": "POST",
                    "url": sSource,
                    "data": aoData,
                    "success": function (msg) {
                        fnCallback(msg.aaData);
                        //$("#members").show();
                    }
                } );
            },
            "columns": [
                    { "data": "Id" },
                    { "data": "VIN" },
                    { "data": "ModelGroupId" },
                    { "data": "Mark" }
            ],
        "sPaginationType": "full_numbers",
        "bVisible": true
    });

Structure of JSON data from Ajax call is as follows that has three rows of data:
{"aaData":[{"Id":"1","VIN":"VIN345345354345345","ModelGroupId":"10","Mark":"NDE5234"},{"Id":"2","VIN":"VIN345343445345","ModelGroupId":"10","Mark":"NDE5234"},{"Id":"3","VIN":"VIN345343445345","ModelGroupId":"10","Mark":"NDE5234"}],"sEcho":1,"iTotalRecords":3,"iTotalDisplayRecords":3}
When I am passing my json data from AJAX success call to fnCallback method, DataTable is showing no result, code is as follows:
            "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
                oSettings.jqXHR = $.ajax( {
                    "dataType": 'json',
                    "type": "POST",
                    "url": sSource,
                    "data": aoData,
                    "success": function (msg) {
                        fnCallback(msg);
                        //$("#members").show();
                    }
                } );
            }

Here the problem is that when I am passing json result to fnCallback function as fnCallback(msg), then DataTable is showing no result. But when I am passing json data to fnCallback function as fnCallback(msg.aaData) then DataTable is able to render 3 records in the grid, however other information related to paging like Page information from Server is lost as >> sEcho, iTotalRecords, iTotalDisplayRecords are part of msg and not msg.aaData from JSON.
Please, can someone help on this?

A: I have solved the issue, I tried different approach :
$("#MyTable").DataTable({
    "bServerSide": true,
    "bProcessing": true,
    "ajax": {
        "url": $("#apiUrl").attr("value") + "/myClass/myMethod",     //to call web API
        "type": "POST",
        "data": function (d) {  //extra parameters to append with Post Data
            d.order_0_column = d.order[0].column;
            d.order_0_dir = d.order[0].dir;
            d.ModelGroup = searchOptionObject.ModelGroup;
            d.RegistrationMark = searchOptionObject.RegistrationMark;
            d.VIN = searchOptionObject.VIN;
            d.StartDate = searchOptionObject.StartDate;
            d.EndDate = searchOptionObject.EndDate;
            d.Source = searchOptionObject.Source;
            d.Status = searchOptionObject.Status;

            for (i = 0; i < d.columns.length; i++)   //binding search parameters to fetch filter data from each column
            {
                d[d.columns[i].data + "_searchValue"] = d.columns[i].search.value
            }
        }
    },
    "sPaginationType": "full_numbers",
    "bVisible": true,
    "order": [
        [1, "asc"]
    ],
    scrollX: true,
    "bAutoWidth": false,
    scrollCollapse: true,
    "oColReorder": {
        "iFixedColumns": 1
    },
    "columns": [
                    { "data": "Id" },
                    { "data": "VIN" },
                    { "data": "ModelGroupId" },
                    { "data": "Mark" }
    ],
    "sPaginationType": "full_numbers",
    "bVisible": true,
                "columnDefs": [
                    {
                        "targets": [0],
                        "visible": false,
                        "searchable": true
                    }]

});

My API class is as belows:
    [HttpPost]
    public parseJsonData SearchOption(SearchOption1 searchOption)
    {
        //write logic to fetch data from data source

        parseJsonData dto = new parseJsonData();
        dto.data = returnList;  // List of records
        dto.draw = draw;  //it should be same that you are getting from Client via Ajax call
        dto.recordsTotal = 24; // total records, should be from datasource
        dto.recordsFiltered = 24;  //filtered records, should be from data source
        return dto;
    }

Model Class:

public class SearchOption1
{
    public int draw { get; set; }
    public int start { get; set; }
    public int length { get; set; }
    public int order_0_column { get; set; }
    public string order_0_dir { get; set; }
    public int ModelGroup { get; set; }
    public string RegistrationMark { get; set; }
    public string VIN { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public int Source { get; set; }
    public int Status { get; set; }
    //You can add extra Parameters to map from Post data that you are getting from Ajax Call
}

public class parseJsonData
{
    public List<MyDataList> data { get; set; }
    public int draw { get; set; }
    public int recordsTotal { get; set; }
    public int recordsFiltered { get; set; }
}

Json structure that is sent to client : {"data":[{"Id":"1","VIN":"VIN345345354345345","ModelGroupId":"10","Mark":"NDE5234"},{"Id":"2","VIN":"VIN345343445345","ModelGroupId":"10","Mark":"NDE5234"},{"Id":"3","VIN":"VIN345343445345","ModelGroupId":"10","Mark":"NDE5234"}],"draw":1,"recordsTotal":24,"recordsFiltered":24}


text:
Q: readFromParcel() method in Parcelable interface I have a simple doubt in marshaling during service creation. When there is a writeToParcel() method declared in Parcelable interface which is invoked in stub generated (if aidl method parameters are declared as in), why there is no readFromParcel() declaration in Parcelable interface(for out parameters)?
I can create my own readFromParcel() but as per my understanding there should be a overridden readFromParcel() declaration in Parcelable interface if the generated stub wants to invoke it. But the documentation for Parcelable interface does not show any sign of readFromParcel() method. Why is it so? Was it included in previous API version and later got removed? Please explain !
And how different is createFromParcel() from readFromParcel() if both tries to read a parcelable object and populate member fields with the data out of it?

A: This is because you have declared a parameter of that type as "inout" in your AIDL.
When returned from the method, generated AIDL proxy will call readFromParcel() to update the parameter value (as defined by the "inout" qualifier).

A: createFromParcel is exactly what it sounds like.  A NEW Intance of the parcelable Object/Class that has been written to parcel : Parcelable.writeToParcel() is created.  This is a good thing, as it helps prevent memory leaks, as you are not holding on to a reference to the object from another class that may or may not have been destroyed

A: From the documentation of Parcelable interface :
 public class MyParcelable implements Parcelable {
 private int mData;

 public int describeContents() {
     return 0;
 }

 public void writeToParcel(Parcel out, int flags) {
     out.writeInt(mData);
 }

 public static final Parcelable.Creator<MyParcelable> CREATOR
         = new Parcelable.Creator<MyParcelable>() {
     public MyParcelable createFromParcel(Parcel in) {
         return new MyParcelable(in);
     }

     public MyParcelable[] newArray(int size) {
         return new MyParcelable[size];
     }
 };

 private MyParcelable(Parcel in) {
     mData = in.readInt();
 }
}

When an object of a class which implements the Parcelable interface is to be written to a Parcel, writeToParcel(...) is called.
When an object of this class is to be created using a Parcel, CREATOR.createFromParcel(Parcel in) is called. From there onwards, how the class creates its instance from the Parcel is upto the developer of the class. In the above example, a constructor private MyParcelable(Parcel in) is called from the createFromParcel(...) method.
Conventionally, many developers define a readFromParcel(Parcel in) method in their implementations and call it from the constructor:
 private MyParcelable(Parcel in) {
     readFromParcel(in);
 }

 private void readFromParcel(Parcel in) {
     mData = in.readInt();
 }


text:
Q: Issue with building and signing an iOS app with a configurable bundle identifier to support multiple build configurations I am trying to build multiple concurrent builds of my app (one for mocking environment, one for development environment, one for testing environment, one for production release).
I have gotten very far in getting this working, but am having issues with the codesigning of an app with a auto-generated bundle identifier (one running off a variable).
WHAT I HAVE DONE SO FAR
I am using xCode 4.6.3 using an adhoc provisioning profile.
To attempt to get this to work, I am setting my bundle identifier in the info plist file to somewhat running off a variable - so the app can be signed in different ways.
E.g. my actual bundle identifiers are:

*

*UXXXXXX.au.com.blah.MOCK

*UXXXXXX.au.com.blah.DEV

*UXXXXXX.au.com.blah.TEST

*UXXXXXX.au.com.blah.PROD

Therefore my bundle identifier in my info plist has been configured as "UXXXXXX.au.com.blah.${BUNDLE_SUFFIX}"
Now to allow me to build the app differently for each build, I did the following:

*

*I have 4 different bundle identifiers with 4 different provisioning profiles assigned to those bundle identifiers

*To begin with i added a new configuration called "MOCK" (I will add the others in later)

*Then under the project build settings I added a BUNDLE_SUFFIX user defined variable to my project and set it to MOCK for the MOCK configuration (I will add the others in later). This is used to set the bundle identifier for a build that uses the MOCK configuration.

*Then under the project build settings, selected my MOCK provisioning profile for the MOCK configuration in build settings

*I notice if i go to the summary view on my app target it displays the bundle id as UXXXXXX.au.com.blah.MOCK with the 'MOCK' part being in grey font - so it has picked up the bundle suffix variable

*Then i created a new scheme called MOCK to use MOCK configuration for 'Profile' and 'Archive'. I left defaults for the rest (uses DEBUG).

So now I can run an xcodebuild and use scheme MOCK to do a MOCK specific build that will use the MOCK configuration to set the bundle identifier to .MOCK and set my provisoning profile to use _MOCK profile.
So i then run a jenkins build which does an xcodebuild and xcrun (which will call codesign).
This is my xcodebuild command:
/usr/bin/xcodebuild -scheme MOCK -sdk iphoneos -project MyApp.xcodeproj -configuration MOCK clean build "CONFIGURATION_BUILD_DIR=/Users/CI/Documents/workspace/build3" ONLY_ACTIVE_ARCH=NO DEPLOY_ENVIRONMENT=MOCK "CODE_SIGN_IDENTITY=iPhone Distribution: My Company" "PROVISIONING_PROFILE=XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"

This is my xcrun command:
/usr/bin/xcrun -sdk iphoneos PackageApplication -v "/Users/Shared/Jenkins/Home/jobs/MyApp.app" -o "/Users/Shared/Jenkins/Home/jobs/MyApp/workspace/build/MyApp-0.9.5.0.ipa" --embed "/Users/Shared/Jenkins/Home/Library/MobileDevice/Provisioning Profiles/20130816_Distribution_MOCK.mobileprovision" --sign "iPhone Distribution: My Company"

NOTE: I specifically sign the app with the MOCK provisioning profile, as I worked out that I cannot sign the app with a .* profile, as the app uses push notifications and if I build the app with a .* and then re-sign the app with the proper profile, my embedded.mobileprovision profile gets updated, but the actual executable within the .app file never gets updated. And this causes push notifications to never get to the device. So what i need to get working is the ability to build and sign an app from command line with the app having a bundle id that is populated dynamically using a variable. And I cannot seem to get this working.
THE RESULTS
The xcodebuild runs successfully and works perfectly. The app appears to be built and signed properly as .MOCK and using the _MOCK provisioning profile!
BUT! The generating of the IPA file has an issue, I have an issue with the codesign.
Notice, that I built the app without any code signing entitlements. codesign gives me this error:
warning: Application failed codesign verification.  The signature was invalid, contains disallowed entitlements, or it was not signed with an iPhone Distribution Certificate. (-19011)
Executable=/Users/CI/Documents/workspace/build3/MyApp.app/MyApp
codesign_wrapper-4.1: using Apple CA for profile evaluation
Illegal entitlement key/value pair: application-identifier, UXXXXXX.au.com.blah.
AssertMacros: filter_entitlements(entitlements_whitelist, entitlements_requested, allowable_entitlements),  file: codesign_wrapper.c, line: 932
 - (null
Notice that it has not picked up the bundle_suffix. Also when i view the MyApp.xcent file that codesign references, I notice it has UXXXXXX.au.com.blah. in it. It has not picked up the value of the bundle_suffix!
So then, what i tried is to create an entitlements.plist file for my MOCK build configuration and add a link to the file under 'code signing entitlements' for MOCK configuration under the build settings. But now i get a different error, and its rather disturbing:
/usr/bin/codesign --force --sign 5XXXXXXXXXXXXXXXXXXX2c --resource-rules=/Users/CI/Documents/workspace/build3/MyApp.app/ResourceRules.plist --entitlements /Users/CI/Library/Developer/Xcode/DerivedData/MyApp-fasiktlyysoxjpgalujkfjpyiyeo/Build/Intermediates/MyApp.build/MOCK-iphoneos/MyApp.build/MyApp.xcent /Users/CI/Documents/workspace/build3/MyApp.app

Validate /Users/CI/Documents/workspace/build3/MyApp.app
    cd /Users/Shared/Jenkins/Home/jobs/MyApp-MOCK-HourlyBuilds/workspace
    setenv PATH "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin"
    setenv PRODUCT_TYPE com.apple.product-type.application
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/Validation /Users/CI/Documents/workspace/build3/MyApp.app
warning: This bundle is invalid. The application-identifier entitlement is not formatted correctly; it should contain your 10-character App ID Seed, followed by a dot, followed by your bundle identifier: UXXXXXXXX.au.com.amp.blah.MOCK (-19054)
Unable to validate your application. - (null)
This time is has actually picked up the proper bundle identifier!! It says MOCK it it. But it is complaining that this bundle is invalid... but it looks perfectly valid to me!! Why is it not working?
This is my entitlements.plist file that I manually created and added to the project (and reference in 'code signing entitlements'):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>application-identifier</key>
    <string>UXXXXXXXXXXX.au.com.amp.blah.MOCK</string>
    <key>aps-environment</key>
    <string>production</string>
    <key>get-task-allow</key>
    <false/>
    <key>keychain-access-groups</key>
    <array>
            <string>UXXXXXXXXXXX.au.com.amp.blah.MOCK</string>
    </array>
</dict>
</plist>

Any help would be greatly appeciated, many thanks!
P.S. I know that a way to get around this issue would be to create a different Target for each of my builds. But i dont really want this, as it is a pain maintaining multiple Targets. I really wanted to try and get away with this without having multiple Targets if I can.
P.S.S. I know another way to get around this issue is to sign the app initially with a .* provisioning profile and then resign the app after with the proper profile, however this does not work for me. As the executable file within .app still keeps references to the .* provisioning profile. And thus push notifications can never be picked up by this device. I get the "no valid 'aps-environment' entitlement string found for application" error.

A: I am running a similar setup for my iOS builds via Jenkins, with the goal of allowing side-by-side installation of the app (production, staging, qa, dev) and ran into the same problem as you.
In the end, I stumbled upon this answer and modified it to include the .xcent file which is part of the xcodebuild (check build output for the path) for the --entitlements flag.  This means you do not have to manually create the entitlements file, but can use the exact one xcodebuild produces for you.
I too was using xcrun PackageApplication, but this does NOT support entitlements so re-signing using this tool would lose the entitlements.
So, after running xcodebuild I use plistbuddy to modify my info.plist file to update the settings bundle, etc. (this may not be required for you) and I unpack the ipa, copy the profile and info.plist into the unpacked payload, re-sign and re-pack:
pushd ${SCRIPT_DIR}
unzip "${PROJECT_NAME}.${CURRENT_ENV_NAME}.ipa"
rm -r "Payload/${PROJECT_NAME}.app/_CodeSignature" "Payload/${PROJECT_NAME}.app/CodeResources" 2> /dev/null | true
cp "${PROFILE}" "Payload/${PROJECT_NAME}.app/embedded.mobileprovision"
cp "${BUILD_DIR}/${BUILD_TARGET}-iphoneos/${PROJECT_NAME}.app/Info.plist" "Payload/Yappem.app/Info.plist"
/usr/bin/codesign -f -s "${CODE_SIGN_IDENTITY}" --resource-rules "Payload/${PROJECT_NAME}.app/ResourceRules.plist" --entitlements "${XCENT_FILE}" "Payload/${PROJECT_NAME}.app"
if [ $? != 0 ]; then
  echo Error Signing Project
  exit 1
fi
rm "${PROJECT_NAME}.${CURRENT_ENV_NAME}.ipa"
zip -qr "${PROJECT_NAME}.${CURRENT_ENV_NAME}.ipa" Payload
popd


text:
Q: Quadratic error for multi-class classification I'm trying to train a neural network to classify handwritten inputs into 10 categories, each for one digit (1,...,9,0). I represent the output of an example using a 10-dimensional vector. Digit 5, for example, is represented like:
$$\begin{bmatrix}
0.0\\
0.0\\
0.0\\
0.0\\
1.0\\
0.0\\
0.0\\
0.0\\
0.0\\
0.0
\end{bmatrix}$$
However, I'm not sure how should I compute the quadratic error of the output of my network. When working with single-class classification, I simply compute:
$$quaderror(o, t) = \frac{1}{2}(o - t)^2$$
Where $o$ is the output of my network and $t$ is the target output. What should the quadratic error be in the case of multi-class classification? Should it be the quadratic error for each term? Or the square of the norm of the difference? Or something else entirely? What is the derivative of the error with respect to $o$ in this case?

A: Error just describe how wrong is your solution. It would be zero value if it's right and 2 otherwise. The important thing that you will minimize value if it was wrong, but if your difference would be zero than you didn't get any update for right answer. Last one looks OK, but if you think about it, there are can be situation when your winner neuron can be extremely close to some other two and small updates in input data can change your network answer. For a good learning process for classification tasks the best way is to learn probabilities. For this issue you must put Softmax layer as final one and instead of competitive. In this case your error will show not only how your network guess the result, but also how confidence it in this result.
Also you can use cross entropy error function, but for it you must use Softmax layer as final one.


text:
Q: Build relationships in NEO4J I'm going to preface this that I am a total database pleb.  I have 0 experience with any form of databases so I know that I'm in way over my head.
Background:  I do Active Directory consulting for my company so I routinely look at client's group membership of their active directory accounts.  Currently, I have a PowerShell script that will run my analytics, however, I'm finding that it takes way too long in larger organizations.  I'm thinking "There has to be a better way" so I have jumped into looking at databases.  NEO4J seems to be a good possible solution as I should be able to to link a user account or group as a member of another group.  However, after browsing documentation and forums, I have no idea how to create those links.
I have two CSVs that I have successfully imported with the following information:
Users = DistinguishedName, SAMACCOUNTNAME, MemberOf
Groups = DistinguishedName, SAMACCOUNTNAME, MemberOf, Members
What I want to do is match a string from all users and groups (DistinguishedName) to a string in the group node's property of members.  Members is a concatenated string of all DistinguishedName's (whether user or group).  So if a node with a DistinguishedName matches part of a string in a group's "members" property, I want to build a one way relationship like so:
user -[memberof] - > group
The best I could rack my brain on this is the following code but I have no idea if I'm even close:
    Match(n)
    Match(u:user) WHERE n.Members CONTAINS u.DN
    Create (u)-[MS:Memberof]->((match)})

In PowerShell, I know how I would accomplish this (loosely translated to relate to the NEO4J world):
   $groups = (all-groups)
   $AllUsersAndGroups = (all-objs)
   foreach ($line in $groups) {
   $line.relationship = $line | where {$_.members -contains    $AllUsersAndGrups.DistinguishedName}
    }

So at last, I'm stuck right now.  I will continue to look into it but I figure I would ask the community as you guys have the experience and stuff.

A: Here is an example of how you should have imported your data (notice that the redundant Members column is not actually needed):

*

*Import (in batches of 5000, to avoid resource issues) each user, and create a unique relationship to its group:
USING PERIODIC COMMIT 5000
LOAD CSV WITH HEADERS FROM "file:///users.csv" AS u
MERGE (u:User {DistinguishedName: u.DistinguishedName, SAMACCOUNTNAME: u.SAMACCOUNTNAME})
MERGE (g:Group {DistinguishedName: u.MemberOf})
MERGE (u)-[:Memberof]->(g);

*Import each group, and create a unique relationship to its parent group, if any:
USING PERIODIC COMMIT 5000
LOAD CSV WITH HEADERS FROM "file:///groups.csv" AS g1
MERGE (:Group {DistinguishedName: g1.DistinguishedName, SAMACCOUNTNAME: g1.SAMACCOUNTNAME})
MERGE (g2:Group {DistinguishedName: g1.MemberOf})
MERGE (g1)-[:Memberof]->(g2);


text:
Q: Stuck adding formula to dynamically added columns I have a query that returns a dynamic number of columns. I need to dynamically add the same amount of custom columns. I have successfully gotten this far. I'm stuck creating the formulas for the custom columns. This is what I have so far. (This is not the actual query, this is simplified)

Here is the Code:
Test = List.Accumulate(MyList, Source,
       (state, current) => Table.AddColumn(
           state, "A Temp" & Number.ToText(current), each [A1])
       )

For now, I just added [A1] as a place holder for the formula. I need the formula to accumulate as follows:
A Temp1 = [A1] / [TOTAL]
A Temp2 = [A2] / [TOTAL]
A Temp3 = [A3] / [TOTAL]

Above is not actual code. Just what I need the formulas to do for each custom column.
Is this possible? I have tried everything I could think of. I'm using power query in excel BTW.

A: This isn't exactly what you asked for, but I think it will help.
Test = List.Accumulate(
           List.Select(Table.ColumnNames(Source), each _ <> "TOTAL"),
           Source,
           (state, current) => Table.AddColumn(state,
                                   "Temp " & current,
                                   each Record.Field(_, current) / [TOTAL]))

It's not exactly what you asked for as it gives column names like Temp A1 instead of A Temp1.


text:
Q: TRIAC motor control. Why is my resistor burning? I have designed a digital motor controller using the following circuit.  One of my resistors keeps overheating.

There is a zero-cross detector elsewhere in the circuit used to time the firing of the TRIAC, and the circuit does control the motor, but resistor R36 keeps burning up after being on for 2-3 minutes.
I took this circuit from the MOC3022 datasheet here: https://www.onsemi.com/pdf/datasheet/moc3023m-d.pdf
I am using is this TRIAC.
This is the motor I am controlling.
I question the following:

*

*Perhaps the 470 ohm resistor value is correct but I didn't give it the right power rating and that is why it keeps burning.

*Perhaps the resistor should be a higher value.

*I used the "typical application circuit" from the datasheet for the MOC3022. Perhaps I should have used the schematic examples for inductive loads which place the load above the TRIAC not below like here. Also for the inductive loads, R36 is a higher value. I ignored them because they say for sensitive gate TRIACs which I am not using, but now I am concerned that was a mistake.

Any input you can give on where I messed up and how to approach the proper design of this circuit would be much appreciated.

A: You can find a more detailed explanations and calculations on this  site:

Also you can see the respective power ratings if you compare the resistor sizes from a ready made SSR:

The resistor in question is the bigest one in Melf package its length is close to Triac width (6.6mm), probably it's 0207 size (5.8mm) @ 1W. Note how smaller the R1 and RGK are.
EDIT:
$$R_2>\dfrac{V_{line_{peak}}}{I_{MOC_{surge}}}>\dfrac{120V\cdot \sqrt{2}}{1A}>170 \Omega$$
$$V_{T_{ripple}}=(R_1+R_2)\cdot I_{GT} + (1+\dfrac{R_1+R_2}
{R_{GK}})\cdot V_{GT}$$
no RGK:
$$V_{T_{ripple}}=(R_1+R_2)\cdot I_{GT} + V_{GT}$$
$$R_1+R_2 = \dfrac{V_{T_{ripple}}-V_{GT}}{I_{GT}}$$
$$\dfrac{dV_{C_1}}{dt}(max)=\dfrac{V_{line_{peak}}}{R_1\cdot C_1}$$
dV/dt(max) for LiteON MOCxx is 1000V/us - link
It comes out that optima values of elements are R2=180..270 Ohm, R1=47..68 Ohm, C1=22..47 nF

A: Throwing a guess. Only condition to see what you describe, assuming everything else ok, is: Q3 turn on lags.
Q3 turn on lags, most likely from large current (heavy load). Motor inrush current is one that contributes to. Zero crossing may not help as hope, since the inrush condition lasts over many cycles. You can see it on oscilloscope.
Sensitive TRIAC will help.

Edited.
I just went through the datasheet. And, my first guess likely was incorrect, I guess again. However, the sensitive TRIAC theory will still work.
Here is what I suggest: Try lower resistor value. And, the design parameters and procedures:
Design parameters example, just for the trigger circuitry:

*

*Gate trigger current, Igt = 70mA (max of ++ & -- quadrant).

*On-state voltage Vt = 1.7V

*Gate trigger voltage, Vgt - 1V

*Latching current, IL = 30mA (max of ++ & -- quadrant)

*Holding current, IH = 15mA

*Gate trigger resistor wattage Pr = 0.25W

*Line voltage Vac = 120V

Procedure:

*

*Decide the peak wattage limit on the resistor: Prp <= Pr, Prp = 0.25W

*Peak voltage across the resistor: Vr = Prp / Ig = 0.25W / 70mA =  3.57V

*Resistance Rg = V/I = 51 ohms

*Calculate actual average wattage on the resistor:
W = {[asin(3.75V/120V * sqr(2)) / asin(1)] / [1/(60Hz * 4)]} * 0.5 * 0.25W =
...., where..
-. asin() part is to calculate the percentage time of the resistor takes current.
-. 0.5 is to approximate the sine curve to ramp.
I am not doing the work to prove my calculation is incorrect. The point is the actual average wattage on the drive resistor is significant smaller than the peak wattage and the resistor rating. I forgot how the peak wattage of the resistors are spec-ed, likely from mechanical aspects.

There are other design parameters you may want to verify, if you are interested.

The calculation says, you can use "R35 + R36 = 51ohm" resistor safely, for 1/4W resistor. If the resistance gets higher, the trigger voltage gets higher, the wattage gets larger, the load gets sharp current increase at every cycle of the line.. etc.
Try something much lower value than what you have now. I would start from a single resistor, about 82ohm 1W. I did not calculate what the resulting Vt & Ir will be.

Meantime, we can calculate how the resistors are burning, if you can offer an enough motivation.

Wait a moment.. there is a definition for Tgt, gate-controlled turn-ontime. But, nothing for rated impulse peak gate current. Wonder if it matters.


text:
Q: Mercurial: how to revert part of the working copy after deletion I deleted a project in my solution, committed many times and now found out that I still need that deleted project. Is there a way to restore it with keeping it's history?

A: Assuming what was deleted was actually tracked in the repository:
hg revert -r (last-revision-where-files-still-existed) path/to/files/that/were/deleted

By doing this, you are simply telling mercurial to bring back those files, as they were when you deleted them. No other files will be reverted, just take care to specify their previous locations correctly. You can find that just going through your history.
From the output of hg --help revert :

If a file has been deleted, it is
  restored. If the executable mode of a
  file was changed, it is reset.

And for reference (the options) [-r is what you want here]:
options:

 -a --all        revert all changes when no arguments given
 -d --date       tipmost revision matching date
 -r --rev        revision to revert to
    --no-backup  do not save backup copies of files
 -I --include    include names matching the given patterns
 -X --exclude    exclude names matching the given patterns
 -n --dry-run    do not perform actions, just print output

use "hg -v help revert" to show global options


text:
Q: Ways to send data between server and android client? Hy everybody,
I'm looking for a way to send data between a server- and a android (client) application. The target is to realise a little chat (just for fun) between multiple android devices.
I thought about those ways:

*

*I create a socket from the client and send the IP and ID to the server. The server knows now the clients IP adress. So if I like to send some data I can reopen the socket from the server to the client. Every time the client changes his IP it has to send the new IP to the server.

*I create a socket and let it the hole time open. I dont like this one, because I need to create for every client a thread on the server.
Is there another way? How would you do it?
Thanks for your answer =)


text:
Q: haproxy pgsql-check and eof message I am using haproxy 1.5.4 . in front of pgbouncer .
my configuration has pgsql-check enabled . Once the check is enabled i see these messages in pgbouncer log .
2015-10-01 05:02:46.203 27104 LOG C-0x6609d0: (nodb)/(nouser)@10.53.6.132:38711 closing because: client unexpected eof (age=8)
2015-10-01 05:02:58.205 27104 LOG C-0x6609d0: (nodb)/(nouser)@10.53.6.132:39111 closing because: client unexpected eof (age=8)
2015-10-01 05:03:10.207 27104 LOG C-0x6609d0: (nodb)/(nouser)@10.53.6.132:39707 closing because: client unexpected eof (age=9)
2015-10-01 05:03:22.208 27104 LOG C-0x6609d0: (nodb)/(nouser)@10.53.6.132:40281 closing because: client unexpected eof (age=8)

These were the same messages i was getting when the default check was there . I mean when there was no
option pgsql-check.
I have also tried providing a valid user in the pgsql-check and still i see the eof message like this .
option pgsql-check user pg
2015-10-01 04:58:27.057 27104 LOG C-0x6609d0: pg/pg@10.53.6.132:17813 login attempt: db=pg user=pg
2015-10-01 04:58:27.057 27104 LOG C-0x6609d0: pg/pg@10.53.6.132:17813 closing because: client unexpected eof (age=0)
2015-10-01 04:58:29.058 27104 LOG C-0x6609d0: pg/pg@10.53.6.132:17882 login attempt: db=pg user=pg
2015-10-01 04:58:29.058 27104 LOG C-0x6609d0: pg/pg@10.53.6.132:17882 closing because: client unexpected eof (age=0)

My question is how different is pgsql-check from the the default tcp check . I was under impression that it will close the connection properly and i will not be seeing these message in the log .
Are we seeing these messages even with pgsql-check ?

A: I have the same kind of messages when HAProxy is connecting directly to PostgreSQL (in my case postgres 9.4 and HAProxy 1.5).
Without giving any username I get:
LOG:  could not receive data from client: Connection reset by peer
LOG:  incomplete startup packet

With a valid username:
LOG:  could not receive data from client: Connection reset by peer

So, apparently, pgsql-check without username seems to be pretty close to the "standard" tcp check. With the username it does seem to send a valid startup sequence. But in both case, the connection is terminated abruptly and not properly close or it seems.
The solution might be to use the generic TCP check to open and close the connection properly but that kind of defy the whole pgsql-check purpose.

A: I made such a configuration with the generic TCP check.  I can actually confirm that it's also receiving the same error in the logs.
You can find a python script + example configuration in my github repo https://github.com/gplv2/haproxy-postgresql
Even though I do send a proper hex close, I still get this in the logs:

LOG:  could not receive data
  from client: Connection reset by peer

Afaik, I send a proper close, I've analysed this with wireshark multiple times to see what exactly a close sends to a PG database:
# write: terminate session
tcp-check send-binary 58                       # Termination packet
tcp-check send-binary 00000004                 # packet length: 4 (no body)

This is the hex dump of a quit (command line client test)

00000000  58 00 00 00 04                                   X....

Fact that the standard psql-check in haproxy as well as a custom made generic one seems to yield the same results is quite interesting.  When I find the solution I will share it.
EDIT: adding source of psql protocol information:  https://www.postgresql.org/docs/9.5/static/protocol-message-formats.html
afaik, I implemented the close exactly as documented to no avail.