text:
Q: Placing numbers around bombs in Minesweeper: why do I get "list index out of range"? I have a function that places 'z' amount of bombs randomly scattered across a 10x10 grid. It looks something like this ("b" represents where the bombs are located.) I need to place a number representing how many bombs there are next to the "0" (including diagonals), and I am not sure how to do that.
0 0 0 0 0 0 0 0 b 0
b 0 0 b 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 b 0 0 0
0 0 0 b 0 0 0 0 0 0
0 0 b 0 0 0 0 0 0 b
0 0 0 0 0 0 0 b 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 b 0 b 0 0 0 0
0 0 0 0 0 0 0 0 0 0

from random import*
mat1 = []
mat2 = []

def makemat(x):
    for y in range(x):
        list1 = []
        list2 = []
        for z in range(x):
            list1.append(0)
            list2.append("-")
        mat1.append(list1)
        mat2.append(list2)
makemat(5)

def printmat(mat):
    for a in range(len(mat)):
        for b in range(len(mat)):
            print(str(mat[a][b]) + "\t",end="")
        print("\t")

def addmines(z):
    count = 0
    while (count < z):
        x = randrange(0,len(mat1))
        y = randrange(0,len(mat1))
        if mat1[y][x] == "b":
            count -= 1
        else:
            mat1[y][x] = "b"
        count += 1
    printmat(mat1)
addmines(10)

This is the function I tried for placing the numbers:
def addscores():
    for x in range(len(mat1)):
        for y in range(len(mat1)):
            if mat1[y][x] != "b":
                if mat1[y+1][x] == "b":
                    mat1[y][x] = 1
                if mat1[y-1][x] == "b":
                    mat1[y][x] = 1                  #...ETC
            else:
                mat1[y][x] == "b"
addscores()

I keep getting the error list index out of range. How can I resolve this?

A: change
if mat1[y+1][x] == "b":

to
if safeEquals(mat1, y+1, x, "b"):

and define safeEquals as
def safeEquals(mat, y, x, value):
    try:
        return mat1[y][x] == "b"
    except IndexError as e:
        return False

This essentially allows you to provide a default behaviour if you index outside the map position.
PS the code executed after the condition:
mat1[y][x] = 1

should be
mat1[y][x] += 1

as presence of an adjacent bomb increments the bomb counter (otherwise how does a 3 ever appear on the map_

A: Let's say that (x, y) = (9, 9), you get the IndexError because you do:
if mat1[y+1][x] == "b":

which tries to access the index mat1[10], which doesn't exists because your list is only 10 elements long.
Also, let's say that (x, y) = (0, 0). Then when you do:
if mat1[y-1][x] == "b":

You access the index mat[-1], which is equivalent to mat[9]. I'm pretty sure this is not what you intend.
There are 2 easy ways to correct this:
1) Include an additional set of if statements to ensure that you don't attempt to access list elements outside the bounds of the list:
Change:
            if mat1[y+1][x] == "b":
                mat1[y][x] = 1
            if mat1[y-1][x] == "b":
                mat1[y][x] = 1

To:
            #parentheses in if statements added for clarity
            if (y < len(mat1) - 1) and (mat1[y+1][x] == "b"):
                mat1[y][x] = 1
            if (y > 0) and (mat1[y-1][x] == "b"):
                mat1[y][x] = 1

2) This is the method I prefer. Add a layer of "padding" around the array. When you first create your array, do:
WIDTH = 10
HEIGHT = 10

myMap = [[0 for i in range(WIDTH + 2)] for j in range(HEIGHT + 2)]

Then, when you access elements in your array, just make sure that you are indexing from 1, not 0:
#do this
firstElement = myMap[1][1]

#not this
firstElement = mayMap[0][0]

#do this
for i in range(1, len(myMap) - 1): pass

#not this
for i in range(len(myMap)): pass

A: An easy way to avoid the index errors is to use defaultdict to hold mat1 and mat2. As a bonus the code is shorter :)
from random import randrange
from collections import defaultdict
mat1 = defaultdict(int)
mat2 = defaultdict(lambda:"-")
size = 5

def printmat(mat):
    for a in range(size):
        print("\t".join(str(mat[a, b]) for b in range(size)))

def addmines(count):
    while (count):
        x = randrange(0,size)
        y = randrange(0,size)
        if mat1[y, x] != "b":
            mat1[y, x] = "b"
            count -= 1
    printmat(mat1)
addmines(10)

def addscores():
    for x in range(size):
        for y in range(size):
            if mat1[y, x] != "b":
                if mat1[y+1, x] == "b":
                    mat1[y, x] = 1                  # should be +=
                if mat1[y-1, x] == "b":
                    mat1[y, x] = 1                  #...ETC
            else:
                mat1[y, x] == "b"
addscores()

A: if y is in range(len(mat1)) then y+1 is not...


text:
Q: Special characters are shown as question marks when downloading the data from SQL Server using pyodbc I'm new to the Microsoft SQL database. I'm using pyodbc module in python to insert and download the data from the SQL Server database table. I've observed the special characters are stored as "?" (question marks).
String I'm loading to DB: 'TV 40″'.
String in the downloaded data from DB: 'TV 40?'
Please find the code to insert the data
def insert_record(table_name, op_rec):
    #import pdb;pdb.set_trace()
    #try:
    cursor, cnxn = create_conn()
    op_rec = remove_none(op_rec)
    if check_table_exists(cursor, table_name):
        pass
    else:
        fields = tuple(list(op_rec.keys()))
        create_table(cursor, table_name, fields)
        #print("Table created: " + table_name)

    row = list(op_rec.values())
    query = """INSERT INTO %s VALUES (""" % table_name
    query_data = add_parameters(query, tuple(row))
    query_data += ")"
    cursor.execute(query_data)
    cursor.commit()
    cursor.close()

op_rec in the above code is a dictionary.
I've tried changing the character sets of the database using the following methods. But none worked for me.

*

*pyodbc doesn't correctly deal with unicode data

*PYODBC corrupts utf8 data (reading from MYSQL information_schema DB)

*

*When I tried the above solution I got Incorrect syntax near '='. (102)

Can you please help with this issue?
Thank you in advance

A:
I'm storing a string, not Unicode characters so I'm not using nvarchar.

In Python_3, all strings are Unicode.
varchar columns use the single-byte character set (SBCS) defined for the database (or the table, if one is declared specifically for that table). If the (Unicode) character does not exist in the SBCS for that database/table then it is replaced with a question mark.
import pyodbc

cnxn = pyodbc.connect("DSN=mssql_199;UID=scott;PWD=tiger^5HHH")
crsr = cnxn.cursor()

print(
    crsr.execute(
        "SELECT collation_name FROM sys.databases WHERE name='test'"
    ).fetchval()
)
# SQL_Latin1_General_CP1_CI_AS

print(crsr.execute("SELECT CAST('TV 40″' AS varchar(2000))").fetchval())
# TV 40?

TL;DR - You can't store a character in a varchar column if the character set does not support it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Render specific header for specific page I'm new to RoR and using layouts/partials/rendering, all that good stuff, to make an app.  At the beginning of my app I thought I would use the same header for the entire app, and thus wrote:
render 'layouts/header'

in my application.html.erb file.  Now, I realized that for certain pages (i.e. sign up page and blog) I want to use a simplified header called simple_header.  Do I write something like
<%= if @simple_header
        render 'layouts/simple_header'
    else
        render 'layouts/header'
%>

and then test if @simple_header is true or something in a controller, or is there a better way to do this.  Thanks.

A: In rails, you can create different layouts and choose which one to use for a particular action or a controller.
Watch this railscast http://railscasts.com/episodes/7-all-about-layouts
That should help you solve your problem.
For example.,
Create a new layout in app/views/layouts, say, simple_header.html.erb and in your controller, tell it to use that layout.
class BlogController < ApplicationController
 layout :simple_header

 def index
 end

end

A: Also (if you have simple logic) consider using

current_page?

method like this:
<% if current_page?(controller: 'sites', action: 'index') %>
...
<% else %>
...
<% end%>


text:
Q: Initializing KafkaProducer object once and use the same object by all the samplers in a Jmeter script I am trying to implement a scenario as mentioned below :
I have to create a load test-script my async APIs that are publishing and consuming events from Kafka topics.
In this script there are multiple samplers that are publishing messages on different topics and currently they are creating a producer client in each of the samplers and then closing it there.
To improve the overall performance of this script and also bring the script closer to real-life scenario , we want to initialize KafkaProducer only once at the start of the test and close it towards the end.
So I have implemented a solution like this :
TestPlan
  ThreadGroup
    1.JSR223Sampler to initialize the Kafka Producer
    2.Another JSR223 Sampler to publish a message on a topic

using same Kafka Producer initialized above
But the problem is , when I save the Kafka Producer object in Sampler1 using vars.putObject() function and get this object in Sampler2 using vars.getObject function , it returns me an object of java.lang.String class in Sampler2.
And if I try to cast it now in Sampler2 , it doesn't work and it throws ClassCastException
Sampler1 script :
import org.apache.kafka.clients.producer.KafkaProducer;

 Properties props = new Properties();
 props.put("bootstrap.servers", vars.get('bootstrapServer'));
 props.put("transactional.id", "my-transactional-id");
 Producer<String, String> producer = new KafkaProducer<>(props, new StringSerializer(), new StringSerializer());
 vars.putObject("producer",producer);

Sampler2 script :
`KafkaProducer producer1 =  vars.getObject("producer") as KafkaProducer;
ProducerRecord<String, String> record  = new ProducerRecord<String, String>('REPO-Asset-Partner-QueryRequest', '', "{\"data\":\"{\\\"assetSearchCriteria\\\":[{\\\"attribute\\\":\\\"category\\\",\\\"operator\\\":\\\"EQ\\\",\\\"value\\\":\\\"SYSTEM\\\"}]}\"}")
record.headers().add(new RecordHeader('authorization', bear.getBytes()))
record.headers().add(new RecordHeader('ce_id', vars.get('searchIndex').getBytes()))
record.headers().add(new RecordHeader('ce_type', 'com.fico.repo.ms.asset.events.message.partner.query.AssetSearch'.getBytes()))
record.headers().add(new RecordHeader('ce_time', vars.get('time').getBytes()))
record.headers().add(new RecordHeader('requestId', vars.get('searchCorelation').getBytes()))
producer1.send(record)
producer1.close()`

Exception:
Response message:javax.script.ScriptException: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '' with class 'java.lang.String' to class 'org.apache.kafka.clients.producer.KafkaProducer'

I am still facing ClassCastException .

A: It looks like your producer variable is an empty string so I would recommend checking the element where you're declaring it.
If you're showing the full code you're missing at least an import statement for the StringSerializer
So check jmeter.log file for any suspicious entries and use Debug Sampler to inspect the JMeter Variables which are defined for this thread (virtual user)

A: You can try with available DI-Kafkameter plugin which is available in Plugins manager.

That should ideally create the connection only once and makes the life easier for you.


text:
Q: Have background change color on refresh in sequence? I'm having a bit of trouble stringing together something that would change the color of the background every time you refresh the page, but in a sequence. I'm savvy with a lot of basic HTML, but not too much with java/css. I'm trying to have my background change along with some pictures for a page I'm working on, and I've figured out a code for the pictures to change on refresh, but I'm extremely confused on getting similar results with the background. Here's the code I have for the pictures:

Is there something similar I can do to make the background change on refresh as well? I figured I could make the background just a picture of the color I want, but I can't apply the img id to the head. If this is something like super simple please forgive me, a lot of this stuff is like a foreign language to me.
EDIT: Here's my current coding with a background color changer that halts the sequence entirely.

A: You can use the HTML5 localStorage (or use sessionStorage if you want to keep the session) to save the index:

A: The same script working with backgroundColor now:


text:
Q: Windows machine excessively flickers for a few seconds when connecting >= 2 displays One of my desktops flickers excessively when it has more than one display connected:

When I connect one display, there's a brief sub-second flicker that's bearable, but any more than that and I get the excessive, multi-second flickering. It doesn't matter which display I connect second, and happens with additional displays (e.g. several VR headsets) if used in lieu of or in addition to the second monitor.
Device 1 (with flicker):

*

*Windows 11 22000.795 (21H2)

*NVIDIA RTX 2080 TI (driver version 516.59)

*Monitors @ 1440p, 144Hz

*Detailed DxDiag Information
However, when I use the same exact monitors at the same exact refresh rate/resolution with the same cables on a different device, the flickering does not happen. (I had to use a HDMI->DP adapter on Device 2 since it only has a single DP port, but even if I use HDMI+the adapter on Device 1 there is no change)
Device 2 (never flickers):

*

*Windows 10

*NVIDIA RTX 2060

*Monitors @ 1440p, 144Hz

*Detailed DxDiag Information
The GPUs are the same generation, so I would be surprised if there were a major discrepancy between the 2060 and 2080 TI that led to the issue. I don't think it's an issue with the GPU's driver either because this has been happening for some time, spanning many driver versions. The biggest suspect I have is Windows 11, but my KVM manufacturer (who I originally thought was at fault before removing the KVM from the equation and finding it still happens) says they test/develop on Windows 11 and don't see this issue. Past that, I'd suspect maybe the VR devices I've used exclusively on Device 1 (which were completely disconnected for the video above) have installed some bad driver or something, but it's weird that it'd interfere without them connected.
I've seen similar questions where a program overlay was causing issues, but this happens even when I close as many open applications, overlay or not, that I can. There are also a lot of questions where this flickering persists permanently, but that's not what's happening here -- rather than some bad cable, device, or similar that's distorting the signal, it seems in this case that the display is disconnecting/reconnecting rapidly, and does not have any distortion while connected.
Any ideas on what could be causing this?

A: flickering is part of the DP continuity test for the link.
Has to do with the Monitor, the Port or the cable.


text:
Q: D3.js : Adding 2nd class as an attribute for 2nd interactivity First I'll describe the interactivity tool I'm currently using. Then I'll adress my request : Basically I want to duplicate this tool whith another variable.
My current project with dummy data is available at : fiddle link
So, I have a Legend that allows me, on hover, to highlight bubbles in the map. On the following picture I'm hovering the red legend button and it displays the red bubble on map. Everything works perfectly fine with this method.
For this purpose, I used an attr.("class",...) on line 171 of the fiddle, where I draw the bubbles.
 .attr("class", function(d) { return "bubbles " + d[attribute] }) // Feature for Highlight

I also have lines 133-150 to create Highlighting variables
// ---------------------------//
//       HIGHLIGHT GROUP      //
// ---------------------------//

// What to do when one group is hovered
var highlight = function(d) {
  // reduce opacity of all groups
  d3.selectAll(".bubbles").style("opacity", 0.30)
  // expect the one that is hovered
  d3.selectAll("." + d).style("opacity", 1)
}

// And when it is not hovered anymore
var noHighlight = function(d) {
  d3.selectAll(".bubbles").style("opacity", 1)
}

Finally, I have lines 354-372. Thats where I draw the legend and add the ability to hover-highlight.
   // Drawing legend

      svg_chorop.selectAll("mydots")
        .data(allgroups)
        .enter()
        .append("rect")
        .attr("x", 0)
        .attr("y", function(d, i) {
          return 60 + i * (size + 10)
        }) // 60 is where the first dot appears. 10 is the distance between dots
        .attr("width", size)
        .attr("height", size)
        .style("fill", function(d) {
          return mycolor(d)
        })
        .style("stroke", "#DCDCDC")
        .on("mouseover", highlight)
        .on("mouseleave", noHighlight)

My goal is to add a 2nd hover tool, that will highlight a different aspect of my data (economic sector). Thats my black boxes below.

The problem : I need to modifiy the class attributes on line 171, where I create my bubbles.
.attr("class", function(d) { return "bubbles " + d[attribute] }) //Important feature for Highlight
  //.attr('class', (d) => `label item${d.itemNr}`); // possible way of adding 2nd class item, found an previous stack overflow post.

I found previous stackoverflow post that is a little bit similar to my request, but to general for me : Adding multiple class name to an element D3
To sum up my request :
I want to duplicate the legend and interactivty that I've just describe. This duplicate can be found on line 347 and forward (fiddle js :fiddle link). The problem is that I have to modify the .atrr("class",...) (line 171) in order to add the variable category that contains my 2nd filter variable (economic sector), as mentionned below in csv document.

So if you have any idea on how to add this 2nd class, your help would be appreciated
Thank you for your time

A: Every HTML element has a classList property containing a list of the classes for that element. This is a read-only property, however you can still modify the list of classes by calling the add() or remove() methods on that list.
In your case, if you were trying to add a class of category to your d element, you could use: d.classList.add("category")


text:
Q: Change score analysis vs multiple regression I have a pre-treatment (T1) and post-treatment (T2) DV measure, and 4 IVs.
I am interested in how (and which) IVs predict change in DV from pre- to post-treatment, or predict post-treatment outcome (I'm happy to answer either).
I'm currently doing a stepwise multiple linear regression of the 4 IVs and pre-treatment measurement, with post-treatment measurement as the DV.
However, I've received feedback from my supervisor that this is confusing as I've mentioned 'change' in my hypothesis, yet I am using an outcome rating at T2, in which case my regression is looking for predictors of outcomes at T2. He recommended there should be a "separate section for predicting CHANGE scores (T2-T1 scores)", and that I need to do "change score analyses".
My questions are:

*

*Should I just remove the word "change" entirely and keep to only this current regression i.e. "predictors of outcome measure"?

*Or should I do BOTH this regression and the suggested additional section of predicting change scores? Does it make sense to do both, and would that add huge value to my thesis?

*What is a change score analysis? How do I go about doing it? I did a repeated measures t-tests showing that change from pre- to post-test is significant, but apparently that's not what he was referring to.

Thank you SO very much for your help! I'm absolutely clueless and this has been giving me a massive headache. Any reply would be much appreciated!


text:
Q: Spivak, Chapter 20, Problem 11: Using Taylor's Theorem Instead of L'Hôpital´s Rule to compute limit. The following is a problem from Chapter 20 of Spivak's Calculus

*Calculations of this sort may be used to evaluate limits that we might otherwise try to find through laborious use of l'Hopital's Rule.
Find the following

(a) $\lim\limits_{x\to 0}
 \frac{e^x-1-x-\frac{1}{2}x^2}{x-\sin{x}}=\lim\limits_{x\to 0}
 \frac{N(x)}{D(x)}$
Hint: First find $P_{3,0,N}(x)$ and $P_{3,0,D}(x)$ for the numerator
and denominator $N(x)$ and $D(x)$.

"Calculations of this sort" refers to the previous problem $10$ in which we compute Taylor polynomials of functions $f+g$, $f\cdot g$, and $f\circ g$, using formulas derived in problem $9$.
Here is the solution manual solution

$$\lim\limits_{x\to 0} \frac{N(x)}{D(x)}=\lim\limits_{x\to
 0}\frac{\frac{1}{6}x^3+R_{3,0,N}(x)}{\frac{1}{6}x^3+R_{3,0,D}(x)}=\lim\limits_{x\to
 0}\frac{\frac{1}{6}+\frac{R_{3,0,N}(x)}{x^3}}{\frac{1}{6}+\frac{R_{3,0,D}(x)}{x^3}}=1$$
since the limits involving $R$ terms are $0$

My question is about the intermediate steps in this proof. Here is my attempt at writing them out.
Using Taylor's Theorem, we can easily see that
$$N(x)=P_{3,0,N}(x)+R_{3,0,N}(x)$$
$$=\frac{x^3}{3!}+\frac{e^t}{4!}x^4, t\in (0,x)$$
$$D(x)=P_{3,0,D}(x)+R_{3,0,N}(x)$$
$$=\frac{x^3}{3!}+\frac{(-\sin{u})}{4!}x^4,u\in (0,x)$$
Therefore, we have
$$\lim\limits_{x\to 0}
 \frac{e^x-1-x-\frac{1}{2}x^2}{x-\sin{x}}=\lim\limits_{x\to 0}
 \frac{N(x)}{D(x)}$$
$$=\lim\limits_{x\to 0} \frac{\frac{x^3}{3!}+\frac{e^t}{4!}x^4}{\frac{x^3}{3!}+\frac{(-\sin{u})}{4!}x^4}$$
$$=\lim\limits_{x\to 0} \frac{\frac{1}{6}+\frac{e^t x}{4!}}{\frac{1}{6}-\frac{x\sin{(u)}}{4!}}$$
$$=1$$
Are these intermediate steps correct?
Seems like this was all a lot more work than applying L'Hopital directly to the original limit.
$$\lim\limits_{x\to 0} \frac{e^x-1-x-\frac{1}{2}x^2}{x-\sin{x}}=\lim\limits_{x\to 0} \frac{e^x-1}{\sin{x}}=\lim\limits_{x\to 0} \frac{e^x}{\cos{x}}=1$$

A: Your argumentation is sound. L'Hopital and Taylor are equivalent here, clearly the derivatives of the nominator and the denominator have to be computed, and evaluated at the limit point, in this case $0$, until (at least) one of the two differs from $0$. I would agree, however, that it is reasonable to be aware of both l'Hopital's and Taylor's perspective.
Your intermediate steps are also correct, if you used $u=u(x)$ and $t=t(x)$, both in the interval enclosing $0$ and $x$ (which is $(x,0)$ for negative $x$!), as functions of $x$ as given by the Lagrange form of the remainder.


text:
Q: With Excel Conditional Formatting - Want to Highlight Cells in a range that match any from another range of cells Sheet One has 5 cells in a row with numbers. (A2:F2)
Sheet Two also has 5 cells in a row with numbers. (A3:F3)
I'd like to highlight sheet one's cells yellow every time that sheet two has a matching number entered. (There will be more rows of data added to each sheet, but I am using the first row only, to keep it simple.
It works with creating a CF equals to, but I need something that applies to a range of data, from a range of data to make this less tedious. Thank you for any tips!
I am using conditional formatting. I have tried Vlookup, Match, and Countif, but I am new to this type of formatting.
(Sheet two's numbers can be placed in a list (column), instead of a row, if that matters)

A: I'd suggest using COUNTIF:
=COUNTIF(Sheet2!$A:$F,A2)>0

Snapshot of Sheet1 and the Conditional Formatting:

Snapshot of Sheet2:


text:
Q: 3 same foreign keys in one table, select statement I have table Errors, this table have 3 foreign keys - ID_empl, ID_empl1, ID_empl2 from same table - Employer where ID_empl is primary key and also have other atributes Name and Surname.ID_empl refering to who repair the error, ID_empl1 refering to who report the error amd ID_empl refering to who take over the error.
Now i want to do SELECT on this table Errors and i want to have statement like : ID_empl - name, surname; ID_empl1 - name, surname; ID_empl2 - name, surname . If there was only 1 FK lets say ID_empl i would do SELECT er.ID_empl, em.name||em.surname as EMPLOYER from employer em, error er where er.ID_empl=em.ID_empl. But i dont know how to do this this with 3 same FKs and i need this info (name+surname) 3 times for every FK.
Little Q2:  i have table Company which have some atributes  and FK ID_empl refering to who manage this company. This FK can be null. Now when i want to do :select e.name||e.surname as EMPLOYER from employer e, company c where e.ID_empl=c.ID_empl i get only rows where ID_empl is not bull, but i want all rows.  There is a problem with join that ID_empl can be null but i dont know how to solve this problem.

A: What you are describing sounds like a job for a multiple join. Using your syntax (old, obsolete, not recommended - even Oracle themselves recommend using the modern syntax), it would be
select [whatever], emp1.name || ' ' || emp1.surname as repaired,
                   emp2.name || ' ' || emp2.surname as reported,
                   emp3.name || ' ' || emp3.surname as took_over
from errors er, employer emp1, employer emp2, employer emp3
where er.ID_empl  = emp1.ID_empl
  and er.ID_empl1 = emp2.ID_empl
  and er.ID_empl2 = emp3.ID_empl

This way the name and surname for "repaired" (the person who repaired the error) is read from table "employer" for id = ID_empl in the "error" table (you said that is the foreign key for the column that contains ID for who repaired the error), the name and surname for "reported" is selected from "employer" table for the id = ID_empl1 in table "error" (with the foreign key for the person who reported the error), and similar for "took over."
The proper, modern, SQL standard, recommended join syntax is
..... from errors er join employer emp1 on er.ID_empl  = emp1.ID_empl
                     join employer emp2 on er.ID_empl1 = emp2.ID_empl
                     join employer emp3 on er.ID_empl2 = emp3.ID_empl

For your second question, you simply need an OUTER join. For this, too, there is "old style" proprietary Oracle syntax, which Oracle itself does not recommend. The proper, modern, SQL standard syntax for your outer join is:
select [whatever], e.name || ' ' || e.surname
from company c left outer join e on c.ID_empl = e.ID_empl


text:
Q: java.lang.NegativeArraySizeException When Making Document Topics Matrix using RMallet I'm trying to write some code to get a Mallet Instance List file into a document topics matrix in R. To do this, I read the instance list file into a topic trainer variable called 'topic.model'. Below is the function call I am making to create a document topics matrix in R:
theta <- mallet::mallet.doc.topics(topic.model, smoothed = TRUE, normalized = TRUE)

I got this working on a smaller instance list file (< 1gb), but for a larger instance list (~15gb) I receive the following error:

Error in .jcall(wrapper, "[D", "flat_double") :
    java.lang.NegativeArraySizeException
  Calls: myfunc ... .jevalArray -> newArray -> structure -> .jcall -> .jcheck
  Execution halted

I suspect that the somewhere there is an integer overflow, in which INT_MAX is exceeded, and the NegativeArraySizeException occurs. Interestingly, using the command line, Mallet was able to make the document topics file using the --output-doc-topics parameter (>150gb). Any suggestions would be greatly appreciated.


text:
Q: Return IQueryable from another class instance What I'm trying to accomplish is to make a base class that returns a general purpose IQueryable<T> and use that IQueryable from another class instance to filter further.
Es.
The base class return all records, and the calling class filters from there on.
This is the base class and getDealer_query is the method that returns the main IQueryable
 public class Dealer
 {
    public DAL.DBConn_Nav db = null;
    public G4.Elements.Identity oIdentity = null;

    public Dealer()
    {
        oIdentity = new G4.Elements.Identity();
        oIdentity.read();
    }

    public IQueryable<outerViewModel.NavisionDAL.vmDealer> getDealer_query()
    {
        IQueryable<vmDealer> dealer = (from d in db.DENTALICA_S_P_A__Customer
                                       select new vmDealer()
                                       {
                                           idDealer = d.No_,
                                           name = d.Name + (d.Name_2.Length > 0 ? " " + d.Name_2 : ""),
                                           address = d.Address + (d.Address_2.Length > 0 ? " " + d.Address_2 : ""),
                                           city = d.City,
                                           zip = d.Post_Code,
                                           county = d.County,
                                           email = d.E_Mail,
                                           phone = d.Phone_No_,
                                           fax = d.Fax_No_,
                                           vat = d.VAT_Registration_No_,
                                           ssn = d.Fiscal_Code,
                                           businessAreaCode = d.Business_Area_Code,
                                           businessZoneCode = d.Business_Zone_Code,
                                           clienteDiretto = (d.Cliente_Diretto == (byte)1 ? true : false),
                                           aggancioOrdiniWeb = (d.Deposito_Agg__Ordini_Web == (byte)1 ? true : false),
                                           aggancioOrdiniG4 = (d.Deposito_Agg__Ordini_G4 == (byte)1 ? true : false),
                                           notUse = (d.Not_Use == (byte)1 ? true : false),
                                           blocked = d.Blocked,
                                           shipmentMethodCode = d.Shipment_Method_Code,
                                           paymentTermsCode = d.Payment_Terms_Code,
                                           paymentMethodCode = d.Payment_Method_Code,
                                           shippingAgentCode = d.Shipping_Agent_Code,
                                           customerPriceGroup = d.Customer_Price_Group,
                                           customerDiscountGroup = d.Customer_Disc__Group,
                                           identificaCliente = d.Identifica_Cliente

                                       });
        return dealer;
    }

Here is the other Class Customer that calls the method from an instance of Dealer and finally Lists data.
public class Customer
{
    G4.Elements.Identity oIdentity = null;
    DAL.DBConn_Nav navDB = null;

    public Customer()
    {
        //oIdentity = new G4.Elements.Identity();
        //oIdentity.read();
    }

    ///// <summary>
    ///// Recupera l'elenco dei clienti Navision (i Depositi pr G4) visibili ad un particolare utente
    ///// </summary>
    ///// <returns></returns>
    public IQueryable<outerViewModel.NavisionDAL.vmDealer> getCustomerForOperator_query()
    {
        string idOperator = !string.IsNullOrEmpty(oIdentity.selectedId) ? oIdentity.selectedId : oIdentity.id;

        using (navDB = new DAL.DBConn_Nav()) {
            G4.Models.NavisionDAL.Dealer oD = new G4.Models.NavisionDAL.Dealer();
            // Tutti i Clienti
            IQueryable<outerViewModel.NavisionDAL.vmDealer> allCustomerList_query = oD.getDealer_query();
            IQueryable<outerViewModel.NavisionDAL.vmDealer> customerForOperator_query = (from c in allCustomerList_query                                                                                join cForOp in navDB.DENTALICA_S_P_A__SalesPerson_Customer on c.idDealer equals cForOp.Customer_No_
                                                                                where cForOp.Salesperson_Code.Equals(idOperator)
                                                                                && cForOp.Starting_Date < DateTime.Now
                                                                                && (cForOp.Ending_Date.Equals(new DateTime(1753, 1, 1)) || cForOp.Ending_Date > DateTime.Now)
                                                                                && c.notUse.Equals(false)
                                                                                select c).Distinct();

            return customerForOperator_query;
        }
    }

    public List<G4.outerViewModel.NavisionDAL.vmDealer> getCustomerForOperator()
    {
        using (navDB = new DAL.DBConn_Nav())
        {
            G4.Models.NavisionDAL.Dealer oD = new G4.Models.NavisionDAL.Dealer();
            return getCustomerForOperator_query().ToList();
        }
    }

But it doesn't work! I get a generic "Object not set to an instance...".
Even if I try to debug I get nowhere cause the cursor doesn't stop.
To make it work I have to inherit the Dealer class from the Customer, but it is not what I want.
I think I'm missing something basic here.
Any Idea ?
EDIT - Simplified sample
I'm adding a simplified sample of the same code.
public class Dealer1
{

    public DAL.DBConn_Nav db = null;

    public Dealer1() {

    }

    public IQueryable<outerViewModel.NavisionDAL.vmDealer> getDealer_query()
    {

        IQueryable<vmDealer> dealer = (from d in db.DENTALICA_S_P_A__Customer

                                       select new vmDealer()
                                       {
                                           idDealer = d.No_,
                                           name = d.Name + (d.Name_2.Length > 0 ? " " + d.Name_2 : "")

                                       });

        return dealer;

    }
}

 public class Customer1
{

    public DAL.DBConn_Nav db = null;

    public Customer1()
    {

    }

    public IQueryable<outerViewModel.NavisionDAL.vmDealer> getCustomerForOperator_query()
    {

        // All customers
        G4.Models.NavisionDAL.Dealer1 oD = new G4.Models.NavisionDAL.Dealer1();

        IQueryable<outerViewModel.NavisionDAL.vmDealer> allCustomerList_query = oD.getDealer_query().Where(i => i.name.StartsWith("AAA"));

        return allCustomerList_query;

    }

    public List<G4.outerViewModel.NavisionDAL.vmDealer> getCustomerForOperator()
    {

        using (db = new DAL.DBConn_Nav())
        {
            return getCustomerForOperator_query().ToList();
        }

    }
}

A: There's nothing in your class Dealer that is setting the instance of db.
public DAL.DBConn_Nav db = null;

So even though in Customer you call using (navDB = new DAL.DBConn_Nav()) you are not passing navDB to Dealer so when you call getDealer_query() you get a null reference exception.

Based on your simplified sample I would recommend this code:
public class Dealer1
{
    internal IQueryable<vmDealer> getDealer_query(DAL.DBConn_Nav db)
    {
        return
            from d in db.DENTALICA_S_P_A__Customer
            select new vmDealer()
            {
                idDealer = d.No_,
                name = String.Join(" ", d.Name, d.Name_2)
            };
    }
}

public class Customer1
{
    internal IQueryable<vmDealer> getCustomerForOperator_query(DAL.DBConn_Nav db)
    {
        return new Dealer1().getDealer_query(db).Where(i => i.name.StartsWith("AAA"));
    }

    public List<vmDealer> getCustomerForOperator()
    {
        using (var db = new DAL.DBConn_Nav())
        {
            return getCustomerForOperator_query(db).ToList();
        }
    }
}

This cleanly allows you to segregate responsibility, but it keeps you totally in control of the db instance - which you need to dispose of when done.

A: There shouldn't be a reason why allCustomerList_query is null.
To confirm that the linq statement in the getDealer_query method is working, I would change your code to look this:
        List<outerViewModel.NavisionDAL.vmDealer> something = new List<outerViewModel.NavisionDAL.vmDealer>();
        IQueryable<outerViewModel.NavisionDAL.vmDealer> test = something.AsQueryable();
        return test;

In any case, to prevent the object ref error, you need to guarantee that an instance is returned, which, from the code example, I can't actually tell.
It's rather strange that you can't get a break point to stop inside the getDealer_query method. Are you running this in a test with multiple threads running? What could happen is that the other thread is having an unhandled exception raised, and thus the whole test stops. Try putting break points before return dealer in getDealer_query and on the line G4.Models.NavisionDAL.Dealer oD = new G4.Models.NavisionDAL.Dealer();. Assuming there are no other threads, the code has to stop on one of those.
Last note, looking at the code, I don't see where db is instantiated. If it isn't instantiated, you'll get an object ref error on this line:
    `IQueryable<vmDealer> dealer = (from d in db.DENTALICA_S_P_A__Customer`


text:
Q: Stripe token in a modal form is always an empty string EDIT:
Everything works when I use my transactions.js.coffee on a non-modal version of the form. Something about handling the form as xhr is preventing Stripe.createToken from accessing the f.hidden_field :stripe_card_token. or maybe the jQuery object is being created before the modal exists, so setupForm() fails silently because it can't find $("#new_transaction_button") because that element is in the modal, and thus hidden when the script runs? Maybe :attr_accessor :stripe_card_token doesn't work in the modal?
I'm trying to allow users to enter credit card details in a modal window.
I have combed through this and cannot figure out why Stripe keeps setting the token as an empty string Stripe error while creating customer: Empty string given for card.
I suspect this is an issue with the way the form is getting passed around by jquery.
Here is my transactions.js.coffee file:
jQuery ->
    Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'))
    transaction.setupForm()

transaction =
    setupForm: ->
        $("#new_transaction_button").click ->
            $('input[type=submit]').attr('disabled', true)
            transaction.processCard()
            valuesToSubmit = $("#new_transaction").serialize()
            $("#new_transaction_modal").modal "hide"
            .ajax(
                url: "/posts"
                data: valuesToSubmit
                type: "POST"
            ).success (data, status) ->

            false

    processCard: ->
        card =
            number: $('#card_number').val()
            cvc: $('#card_code').val()
            exp_month: $('#card_month').val()
            exp_year: $('#card_year').val()
        Stripe.createToken(card, transaction.handleStripeResponse)

    handleStripeResponse: (status, response) ->
        if status == 200
            $('#transaction_stripe_card_token').val("test")
            $('#new_transaction')[0].submit()
        else
            alert(response.error.message)

in the handleStripeResponse function above, I've set the #transaction_stripe_card_token.val() as "test" to demonstrate that it seems to me the function handleStripeResponse is not even being called, because otherwise the console would output Stripe error while creating customer: string "test" given for card.. Is this correct? If it is, why isn't handleStripeResponse getting called? Is it because of the way a modal form is handled by my controller?
transactions_controller.rb
 def create
    if @post = Post.where(:id => flash[:the_post_id]).first
    #@price = @post.price
      @tier_id = @post.tier_id
      @amount = @tier_id*100
    else
      @amount = 1000
    end
    respond_to do |format|
      #non-user encountered form and entered credit details AND password- signing up and paying
      if !current_user && params[:password].present?
        @user = User.new(:email => params[:transaction][:email], :password => params[:password])
        @transaction = @user.transactions.new(params[:transaction].merge(:price => @amount))
        @transaction.save_customer(@user)
        if @transaction.save && @user.save
          @user.charge_as_customer(@amount)
          #sign_in @user
          format.js { render }
          format.html { redirect_to @transaction, notice: 'Transaction was successfully created.' }
          format.json { render json: @transaction, status: :created, location: @transaction }
        else
          format.html { render action: "new" }
          format.json { render json: @transaction.errors, status: :unprocessable_entity }
        end

The Modal Credit Card Form: (whitespace/indentation is correct in production. having trouble copy/pasting)
= simple_form_for @transaction, :validate => true, :remote => true, :form => { "data-type" => "json" } do |f|
  %div.modal-header
    %button.close{"aria-hidden" => "true", "data-dismiss" => "modal", :type => "button"} ×
    - if @transaction.errors.any?
      #error_explanation
        %h2= "#{pluralize(@transaction.errors.count, "error")} prohibited this transaction from being saved:"
        %ul
          - @transaction.errors.full_messages.each do |msg|
            %li= msg

  %div.modal-body
    =hidden_field_tag :post_id

    = f.hidden_field :stripe_card_token

%div.row-fluid
  %div
    = label_tag :credit_card_number, nil, :id => "credit_label"
    = text_field_tag :credit_card_number,nil, :class=>"credit-number span12", :id => "card_number"
%div.row-fluid
  %div.span4
    = label_tag :card_month, "Card Expiration"
    = select_month nil, {:add_month_numbers => true}, {:name => nil, :id => "card_month"}
    = select_year nil, {:start_year => Date.today.year, :end_year => Date.today.year+15}, {:name => nil, :id => "card_year"}
  %div.span3
  %div.span2.credit-cvv
    = label_tag :cvv, "CVV"
    = text_field_tag :cvv, nil, :class=>"credit-cvv input-block-level", :id => "card_code"
%div.row-fluid
  =f.label :email
  =f.text_field :email, :validate => true
-unless current_user
  %div.row-fluid
    =label_tag :password
    =text_field_tag :password, params[:password]
  %div.modal-footer
    = f.button :submit, name: 'Get It', class: "btn-primary", id: "new_transaction_button"

And, to be thorough, here is my save_customer method for transactions:
  attr_accessor :stripe_card_token

  def save_customer(user)
    if valid?
      customer = Stripe::Customer.create( :description => email, :card => stripe_card_token)
      user.stripe_customer_id = customer.id
      save!
    end
  rescue Stripe::InvalidRequestError => e
    logger.error "Egads, Stripe error while creating customer: #{e.message}"
    errors.add :base, "There was a problem with your credit card."
    false
  end

Can't for the life of me figure out what the issue is. Any help would be greatly appreciated. Thanks amigos.


text:
Q: Can one show that ${\gamma^5}^\dagger = \gamma^5$ directly from the anticommutation relations? Is it possible to show that ${\gamma^5}^\dagger = \gamma^5$, where
$$ \gamma^5 := i\gamma^0 \gamma^1 \gamma^2 \gamma^3,$$
using only the anticommutation relations between the $\gamma$ matrices,
$$ \left\{\gamma^\mu,\,\gamma^\nu\right\}=2\eta^{\mu\nu}\,\mathbb{1},$$
and without using any specific representation of this algebra and a unitary invariance argument, as is usually done?

A: As the comments explained, you need to know a few properties of the $\gamma$ matrices. First of all, from
$$ \{\gamma_\mu, \gamma_\nu\} = 2 \eta_{\mu \nu} \mathbf{1}_4$$
you can infer that (depending on the metric but not on the representation of the dirac algebra!) in (+---) metric
$\gamma_0$ is hermitian (hint: look at the $\mu = 0, \nu = 0$ component of the above equation), while the $\gamma_i$ ($i = 1, 2, 3$) are anti-hermitian. (In -+++ metric, this would be interchanged). And this should allow you to solve the problem.
The hermicity properties can be condensed into
$$ \gamma_\mu^\dagger = \gamma_0 \gamma_\mu \gamma_0$$
which just reproduces the above if you take the commutation properties into account.

A: Try using the definition of $\gamma^5$ and just apply the conjugation. Remember that conjugation flips the order of the matrices, which means you want to change their order before applying the conjugation.
Then realize that the anticommutation relations give you a way of interchanging two gamma matrices, giving only a minus sign (provided the indices are different).
Lastly, note that, independent of your convention, you have an uneven number of anti-hermitian matrices in this expression (while the rest is hermitian).


text:
Q: Is it possible to merge files into an obsolete branch in clearcase? I have created a view under X branch. checked in the files successfully. But while merging the files I gave incorrect command and my files were merged into Y branch which is obsolete. How is it possible? It means I can merge files even to an Obsolete branch? Kindly clarify.

A: If only the branch type is locked obsolete, that wouldn't prevent the branch (instance of a branch type) to be modified.
You can check the lock status with:
cleartool lslock <branch_name>@/vobs/avob

Or, for the brtype:
cleartool lslock brtype:<branch_name>@/vobs/avob

As Ian W points out in the comments:

If you are using UCM, there's a lock on the project and a locks on the streams. Pretty sure it's the lock on stream you want to have in place.

True: a lock on the UCM stream would lock the associated non-UCM branch.


text:
Q: Using geometry rather than geography data types in SQL Server Spatial? Historically I've mainly worked with simple latitude and longitude coordinates in a SQL Server. I stored them as a geography datatype in SQL Server, and rendered them on a variety of displays (primarily Google Maps).
Recently I've started working with shapefile datasets from various sources, and almost exclusively they are geometry. Further, they use a variety of coordinate reference systems.
It's pretty maddening to work with.

*

*The USGS, for some of their data, use a very rare and hard to ID CRS.

*The county of Los Angels says they use the State Plane 5 (without reference a CRS specifically), and of course there are multiple "state plane 5's" to choose from in QGIS.

Are there really some advantages to these particular spatial reference systems that cannot be achieved by sticking with WGS84, considering that the VAST majority of people viewing and consuming will want it in that format?

A: Maybe check out the properties of Projected Coordinate Systems, to get a view into their utility?
There are 3 aspects or properties presented in Projected Coordinate Systems that establish their utility and rationale. Any projection of 3D space on a 2D surface will of course exhibit distortion versus reality. Depending on your application, using a specific Projected Coordinate System can ensure a more accurate representation of reality, and in some applications, fine grain accuracy matters.
Three properties of Projected Coordinate Systems. You can have perfection in some, but never perfection in all:
Equidistant - Distances (from a particular spot) shown on the map are true to reality.
Conformal - When zoomed in, the angles shown on the map are true to reality.
Equal Area - Areas recorded on the map are equal to the areas of objects in reality.

A: There's a good answer over at Stack Overflow, which goes a little something like this:

The geography type is a little bit more restrictive than geometry. It
  can't cross different hemispheres and the outer ring must be drawn
  counter-clockwise.

The rest can be found in Geography data type vs. Geometry data type in SQL Server.
A Geometry vs Geography article at the SQL from the Trenches blog goes into more detail:

If you're looking for the biggest difference between the two
  datatypes, you'll see it's the functionality. A Geometry object is
  just a 2D, flat polygon. This means, it doesn't matter if you take a
  country on top of the earth (for example Canada, which is "curved"),
  or a country close to the Equator (for example Brazil, which is
  "flat").
A Geography object on the other hand, is a 3D (or even 4D) polygon,
  that has the same curve as the shape of the earth. That means that the
  difference between 2 point isn't calculated in a straight line, but
  it's need to consider the curvature of the earth.

Another crucial difference is the ability store your data in standard coordinate systems, such as NAD_1983_StatePlane_California Zone 5, and use all the capabilities of the spatial database, spatial functions, etc. and most importantly the spatial accuracy of a localized coordinate system - whereas sticking with geography as your data type, you can only store your data in WGS84.
So I'd say if you have the option, go with geometry, use EPSG: 102645/102245 (you'll have to check what is the standard 'state plane zone 5' for SoCal) and you'd be all set for any analysis you want to undertake. If you want to share, export your datasets to WGS84 if that is preferred for sharing.

A: In California, the surveyors' offices use a Lambert Conformal Conic projection and divide the state into zones to minimize distortions.  State Plane 5 is one of those zones.
http://www.conservation.ca.gov/cgs/information/geologic_mapping/state_plane


text:
Q: What is the output of this Core java Code? public void getData(Object o[]) {
    System.out.println("In Side Array");
}

public void getData(Object o) {
    System.out.println("In Side Object");
}

public static void main(String[] args) {
    new JavaEx().getData(null);
}

Here it's printing Array block why, Why it's not printing Object block?

A: Both getData methods can handle a null argument. In this situation Java tries to choose the method that handles the more specific type.
Now Object is by definition the superclass of all Java classes, so in this situation Object[] (which is also an Object) is the more specific type and getData(Object o[]) is the more specific method. This is why Java chooses this method.

A: According JLS(Java Language Specification) for determine method signature time

*

*The first phase performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method
  invocation. If no applicable method is found during this phase then
  processing continues to the second phase.

*The second phase  performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity
  method invocation. If no applicable method is found during this phase
  then processing continues to the third phase.

*The third phase allows overloading to be combined with variable arity methods, boxing, and unboxing.

In Your example:

when you call method getData() by passing argument null the compiler go to first
  phase and found method signature without performing any boxing.
So that output is  "In Side Array"

A: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5
"If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error."

A: Maybe this will make things a bit clearer:
public void getData(Object o[]) {
    System.out.println("In Side Array");
}

public void getData(Object o) {
    System.out.println("In Side Object");
}
public static void main(String[] args) {
    Object[] array = null;

    new JavaEx().getData(array);
}

This implementation will also print "In Side Array", since an uninitialized array can be null. So it becomes obvious, that the array method is called.


text:
Q: Use Nginx callback after x-accel-redirect response (or use logging to socket) my workflow is following:

*

*accept request

*with ruby script do some stuff

*send x-accel-redirect header and return

*... client receives data ...

*client disconnected

*<- here I would like to run some script

What I need: some http headers from client and headers sent by initial script.
My first idea was to parse logs, but it can break really easily. Other option would be force nginx to log to some custom daemon or to socket. Or use some callback after end of x-accel-redirect request.
Question is: Is it possible to setup nginx (without any patch) use as log: syslog, custom daemon, socket or some daemon reading from fake file. Or setup some callback after request?

A: You want post_action.  Be careful where you put it, though, I believe it can recurse.


text:
Q: Simulink shortcut to resolve signal name Since I do this quite often, I would like to create a keyboard shortcut to change the property of a Simulink Signal to enable the checkbox "Signal name must resolve to Simulink signal Object".
Like this blog post suggests, I created my sl_customization file and have the following code in the callback function, which works fine to make Test Points (also a checkbox in the Signal Properties dialog):
function makeResolveToSimulinkObjcb(~)
line = find_system(gcs, 'SearchDepth', 1, 'FindAll', 'on', ...
          'Type', 'line', 'Selected', 'on');
signalObj=get_param(line(1),'Object');
set(signalObj,'TestPoint',1);
end

Any ideas what the parameter name is for this option, instead of 'Test Point'? I didn't find anything in the documentation...

A: The property you want is MustResolveToSignalObject, but for that to work the signal must have a name.  So you want something like,
set(signalObj,'SignalNameFromLabel','MySignalName');
set(signalObj,'MustResolveToSignalObject',1);


text:
Q: Estimating finite sample bias for Instrumental Variables Are there ways to estimate the finite sample bias with instrumental variables? I guess this would be conditional on assuming some structure to the problem and also would involve simulation, but, at least in applied econometrics papers, I have never seen people do it.
PS: If possible, the answer could be illustrated with R code.

A: Using the model with one regressor and many instruments(vector-matrix notation)
$$y = x\beta +u$$
$$x = Z\gamma  +v$$
Bound, Jaeger & Baker  (1995) give the following approximation to the 2SLS finite sample bias:
$$B(\hat \beta_{IV}) = \frac {\operatorname{Cov}(u,v)}{\gamma'Z'Z\gamma}(K-2)$$
where $K$ is the number of instrument (the column dimension of matrix Z). Naturally, one uses the estimated quantities to calculate the above. This as a special case of results in A.L.Nagar (1959).
Other relevant literature  is A.Buse (1992) and Staiger and Stock (1997).


text:
Q: Jackson YAML: mapping a regex Pattern with flags In Jackson, I can map a string in YAML:
regexField: "(\\d{2}):(\\d{2})"

to a Pattern field on a class:
final class MappedFromYaml {
    private Pattern regexField;
    // ... accessors
}

Jackson's ObjectMapper will create a Pattern with default flags. Is it possible to make it create it with specific flags set, such as Pattern.MULTILINE? Ideally I would like to be able to specify those flags in YAML, but failing that a solution that specifies the flags for a specific field in Java code would also be appreciated.

A: There are two ways. The first is embedding flags directly into the regex:
regexField: "(\\d{2}):(\\d{2})(?m)"

Otherwise don't map directly to Pattern, but introduce a custom type like a PatternBuilder
public class PatternBuilder {
  public String regex;
  public boolean multiline;
  public Pattern pattern() {
    int flags = 0;
    if (multiline) flags |= Pattern.MULTILINE;
    return Pattern.compile(regex, flags);
  }
}

that can be built from the YAML
pattern:
  regex: "(\\d{2}):(\\d{2})"
  multiline: true


text:
Q: SLURM how to qsub a task when another task is finished? I am currently using HPC based on Linux which use only SLURM to submit jobs, and the HPC only allows a job to be run for 12 hours. However, I may need to run 24 jobs continuously for a week to have good results.
Is there a way to run a job again (automatically) when it is finished?
Kind regards
Add:
When the job is finished a .out file will be created. In other words, the number of .out file will increase by 1.
Is it possible to requeue the job when the number of .out is increased?
#!/bin/bash
#!
#! Example SLURM job script for Darwin (Sandy Bridge, ConnectX3)
#! Last updated: Sat Apr 18 13:05:53 BST 2015
#!

#!#############################################################
#!#### Modify the options in this section as appropriate ######
#!#############################################################

#! sbatch directives begin here ###############################
#! Name of the job:
#SBATCH -J Validation
#! Which project should be charged:
#SBATCH -A SOGA
#! How many whole nodes should be allocated?
#SBATCH --nodes=1
#! How many (MPI) tasks will there be in total? (<= nodes*16)
#SBATCH --ntasks=1

#!SBATCH --mem=200

#! How much wallclock time will be required?
#SBATCH --time=12:00:00
#SBATCH --mail-user=zl352
#SBATCH --mail-type=ALL
#! Uncomment this to prevent the job from being requeued (e.g. if
#! interrupted by node failure or system downtime):
##SBATCH --no-requeue

#! Do not change:
#SBATCH -p sandybridge

#! sbatch directives end here (put any additional directives above this line)

#! Notes:
#! Charging is determined by core number*walltime.
#! The --ntasks value refers to the number of tasks to be launched by SLURM only. This
#! usually equates to the number of MPI tasks launched. Reduce this from nodes*16 if
#! demanded by memory requirements, or if OMP_NUM_THREADS>1.
#! Each task is allocated 1 core by default, and each core is allocated 3994MB. If this
#! is insufficient, also specify --cpus-per-task and/or --mem (the latter specifies
#! MB per node).

#! Number of nodes and tasks per node allocated by SLURM (do not change):
numnodes=$SLURM_JOB_NUM_NODES
numtasks=$SLURM_NTASKS
mpi_tasks_per_node=$(echo "$SLURM_TASKS_PER_NODE" | sed -e  's/^\([0-9][0-9]*\).*$/\1/')
#! ############################################################
#! Modify the settings below to specify the application's environment, location
#! and launch method:

#! Optionally modify the environment seen by the application
#! (note that SLURM reproduces the environment at submission irrespective of ~/.bashrc):
. /etc/profile.d/modules.sh                # Leave this line (enables the module command)
module purge                               # Removes all modules still loaded
module load default-impi                   # REQUIRED - loads the basic environment

#! Insert additional module load commands after this line if needed:

#! Full path to application executable:
application="~/scratch/code7/viv"

#! Run options for the application:
options=" > test.e"

#! Work directory (i.e. where the job will run):
workdir="$SLURM_SUBMIT_DIR"  # The value of SLURM_SUBMIT_DIR sets workdir to the directory
                             # in which sbatch is run.

#! Are you using OpenMP (NB this is unrelated to OpenMPI)? If so increase this
#! safe value to no more than 16:
export OMP_NUM_THREADS=1

#! Number of MPI tasks to be started by the application per node and in total (do not change):
np=$[${numnodes}*${mpi_tasks_per_node}]

#! The following variables define a sensible pinning strategy for Intel MPI tasks -
#! this should be suitable for both pure MPI and hybrid MPI/OpenMP jobs:
export I_MPI_PIN_DOMAIN=omp:compact # Domains are $OMP_NUM_THREADS cores in size
export I_MPI_PIN_ORDER=scatter # Adjacent domains have minimal sharing of caches/sockets
#! Notes:
#! 1. These variables influence Intel MPI only.
#! 2. Domains are non-overlapping sets of cores which map 1-1 to MPI tasks.
#! 3. I_MPI_PIN_PROCESSOR_LIST is ignored if I_MPI_PIN_DOMAIN is set.
#! 4. If MPI tasks perform better when sharing caches/sockets, try I_MPI_PIN_ORDER=compact.

#! Uncomment one choice for CMD below (add mpirun/mpiexec options if necessary):

#! Choose this for a MPI code (possibly using OpenMP) using Intel MPI.
#!CMD="mpirun -ppn $mpi_tasks_per_node -np $np $application $options"

#! Choose this for a pure shared-memory OpenMP parallel program on a single node:
#! (OMP_NUM_THREADS threads will be created):
CMD="$application $options"

#! Choose this for a MPI code (possibly using OpenMP) using OpenMPI:
#!CMD="mpirun -npernode $mpi_tasks_per_node -np $np $application $options"

###############################################################
### You should not have to change anything below this line ####
###############################################################

cd $workdir
echo -e "Changed directory to `pwd`.\n"

JOBID=$SLURM_JOB_ID

echo -e "JobID: $JOBID\n======"
echo "Time: `date`"
echo "Running on master node: `hostname`"
echo "Current directory: `pwd`"

if [ "$SLURM_JOB_NODELIST" ]; then
        #! Create a machine file:
        export NODEFILE=`generate_pbs_nodefile`
        cat $NODEFILE | uniq > machine.file.$JOBID
        echo -e "\nNodes allocated:\n================"
        echo `cat machine.file.$JOBID | sed -e 's/\..*$//g'`
fi

echo -e "\nnumtasks=$numtasks, numnodes=$numnodes, mpi_tasks_per_node=$mpi_tasks_per_node (OMP_NUM_THREADS=$OMP_NUM_THREADS)"

echo -e "\nExecuting command:\n==================\n$CMD\n"

eval $CMD

A: If your job is intrinsically restartable, all you need to do is to call sbatch at the end of your submission script. Assuming it is called submit.sh
if ! job_is_done;
then
sbatch submit.sh
fi

The job_is_done part should be replaced by a command that returns 0 when the job is done (i.e. computation finished, process converged, etc.) for instance by 'grepping' in the log file for certain clues.
You can also re-queue the job:
job_is_done || scontrol requeue $SLURM_JOB_ID

If your program is not intrinsically restartable, you could use a wrapper such as DMCTP to make it restartable.


text:
Q: Object Not Found Parsing XML I have the following XML being returned to me:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
  <document xmlns="@link" xmlns:xsi="@link" xsi:schemaLocation="@link" version="1.0">
    <field left="0" top="0" right="100" bottom="20" type="text">
      <value encoding="utf-16">11266</value>
      <line left="8" top="4" right="55" bottom="17">
        <char left="8" top="4" right="13" bottom="16" confidence="65" suspicious="true">1</char>
        <char left="18" top="4" right="23" bottom="16" confidence="68" suspicious="true">1</char>
        <char left="27" top="4" right="35" bottom="16" confidence="100">2</char><char left="36" top="4" right="45" bottom="17" confidence="100">6</char>
        <char left="46" top="4" right="55" bottom="16" confidence="100">6</char>
      </line>
   </field>
</document>

I'm trying to read the value node.  My code looks like this:
Dim m_xmld = New XmlDocument()
m_xmld.Load(xmlfile)
Return m_xmld.SelectSingleNode("/field/value").InnerText

What am I doing wrong?  I tried /document/field/value as well to no avail :(

A: Try selecting the node from the root, like this:
Dim m_xmld = New XmlDocument()
m_xmld.Load(xmlfile)

Return FindNode(m_xmld, "value")

Try using this function to search for the node:
Private Function FindNode(list As XmlNodeList, nodeName As String) As XmlNode
    If list.Count > 0 Then
        For Each node As XmlNode In list
            If node.Name.Equals(nodeName) Then
                Return node
            End If
            If node.HasChildNodes Then
                FindNode(node.ChildNodes, nodeName)
            End If
        Next
    End If

    Return Nothing
End Function

A: There are two problems with your code.  First, you need to specify the XML namespace.  The XML document contains a default namespace on the document element (xmlns="@link").  That means that you must explicitly specify that namespace when you reference any element in the document.  To do that with XmlDocument, you need to create an XmlNamespaceManager and pass it to the select methods.  For instance:
Dim m_xmld As New XmlDocument()
m_xmld.Load(xmlfile)
Dim nsmgr As New XmlNamespaceManager(m_xmld.NameTable)
nsmgr.AddNamespace("x", "@link")
return m_xmld.SelectSingleNode("/x:document/x:field/x:value", nsmgr).InnerText

Or, if you don't want to hard-code the namespace URI, you can just grab it from the loaded document, like this:
nsmgr.AddNamespace("x", m_xmld.DocumentElement.NamespaceURI)

The second problem is that you were trying to select /field/value rather than /document/field/value.  When you are selecting from the XmlDocument object, itself, the selection begins from the root of the document ("above" the document element).


text:
Q: Split an query into arrays I have 1 sql query that returns 10 rows, and i want to split that query into 3 arrays like this:
query -> (row1, row2, row3, row4, row5, row6, row7, row8, row9, row10)

colums[1] -> (row1, row4, row7, row10)
colums[2] -> (row2, row5, row8)
colums[3] -> (row3, row6, row9)

A: Would something simple like this do the trick?
<?php

$a = array('row1','row2','row3','row4','row5','row6','row7','row8','row9','row10');
$b = array();
$max_num = 3;

$x = 0;
foreach($a as $value) {
    $b[$x][] = $value;
    $x++;

    if($x >= $max_num) {
        $x=0;
    }
}

var_dump($b);

array (size=3)
  0 =>
    array (size=4)
      0 => string 'row1' (length=4)
      1 => string 'row4' (length=4)
      2 => string 'row7' (length=4)
      3 => string 'row10' (length=5)
  1 =>
    array (size=3)
      0 => string 'row2' (length=4)
      1 => string 'row5' (length=4)
      2 => string 'row8' (length=4)
  2 =>
    array (size=3)
      0 => string 'row3' (length=4)
      1 => string 'row6' (length=4)
      2 => string 'row9' (length=4)


text:
Q: Upgrade to Rails 7, deploy to server with mina deploy and got this error, locally is still good [ E 2022-03-10 23:04:01.7241 3708037/Tm age/Cor/App/Implementation.cpp:221 ]: Could not spawn process for application /home/deploy_super_control/current: The application encountered the following error: Could not find rails-7.0.2.3 in any of the sources (Bundler::GemNotFound)

Error ID: d423b840
Error details saved to: /tmp/passenger-error-dJscfz.html
Everything with Rails 6 latest version is OK.
Anybody will help me with this case.


text:
Q: Why is a function returning undefined and how to debug it? I'm experimenting with closures and classes in data variables and in the example below I'm getting undefined even though I placed a console.log() right before the function returns the result and it isn't undefined. It seems to work if it isn't attached to an event handler. Can someone tell me why is this happening and if there is a way to spot where exactly does the error happen? When debugging it goes from the console log straight to the error and I don't see how that makes sense.
To trigger the error run the snippet and click on the names.
The same functions in $('#Individuals').data('functions') can be chained and work fine when called in IndividualsList(), but not from the event listener, then the result becomes undefined.

$(document).ready(function() {

  var thisWindow = $('#Individuals');
  var randomNames = ['Sonia Small', 'Kurt Archer', 'Reese Mullins', 'Vikram Rayner', 'Jethro Kaye', 'Suhail Randolph', 'Kaydon Crouch', 'Jamaal Elliott', 'Herman Atkins', 'Sia Best', 'Kory Gentry', 'Fallon Sawyer', 'Zayyan Hughes', 'Ayomide Byers', 'Emilia Key', 'Jaxson Guerrero', 'Gracey Frazier', 'Millie Mora', 'Akshay Parker', 'Margareta Emiliana'];
  var generatedIndividuals = [];

  function generateIndividual(name) {
    return {
      IndividualName: name
    };
  }

  function IndividualsList(element) {
    var list = [];

    this.add = function(thisIndividual) {
      $('#Individuals').data('functions').init(element, list).add(thisIndividual);
    }
    this.refresh = function() {
      $('#Individuals').data('functions').init(element, list).refresh();
    }
    this.sort = function(order) {
      $('#Individuals').data('functions').init(element, list).sort(order);
    }
  }

  thisWindow.data('functions', (function() {
    var element = $();
    var list = [];
    return {
      add: function(thisIndividual) {
        list.push(thisIndividual);
        return thisWindow.data('functions');
      },
      init: function(thisElement, thisList) {
        element = thisElement;
        list = thisList;
        return thisWindow.data('functions');
      },
      refresh: function() {
        var thisList = element.html('');
        for (let i = 0; i < list.length; i++) {
          thisList.append(
            '
' + list[i].IndividualName + '
'
          );
        }
        return thisWindow.data('functions');
      },
      sort: function(order) {
        list.sort(function(a, b) {
          if (a.IndividualName  b.IndividualName) return 1 * order;
          return 0;
        });
        console.log(thisWindow.data('functions'));
        return thisWindow.data('functions');
      }
    }
  })());

  for (let i = 0; i < 20; i++) {
    let nameNum = Math.floor(Math.random() * randomNames.length);
    let thisClient = generateIndividual(randomNames[nameNum]);
    generatedIndividuals.push(thisClient);
  }

  (function() {
    var targetElement = thisWindow.find('div.individuals-list');
    var targetData = {}
    targetElement.data('individualsList', new IndividualsList(targetElement));
    targetData = targetElement.data('individualsList');
    for (let i = 0; i < generatedIndividuals.length; i++) {
      targetData.add(generatedIndividuals[i]);
    }
    targetData.refresh();
  })();

  thisWindow.on('click', '.individuals-list', function() {
    var thisElem = $(this);
    var order = parseInt(thisElem.data('order'));
    thisWindow.find('div.individuals-list').data('individualsList').sort(order).refresh();
    thisElem.data('order', order * (-1));
  });

});
.individuals-list {
  border: 1px solid;
  cursor: pointer;
}

https://jsfiddle.net/Kethus/ymgwrLhj/

A: You are referring to the wrong sort() function, hence call it incorrectly so it returns undefined. Then you call refresh() on undefined that was returned from sort. Here's why:
In your IFFE, you use .data() to set the data = new IndvidualsList on thisWindow.find('div.individuals-list')
This code:
thisWindow.find('div.individuals-list').data('individualsList')

Returns that instantiated IndividualsList Object:
IndividualsList = $1
add: function(thisIndividual)
refresh: function()
sort: function(fieldName, order)
  IndividualsList Prototype

Note the sort() function's definition. Sort in this object requires two parameters, fieldName and order; yet you call sort() and only pass order;
This indicates your expectation for the sort() function is incorrect or the wrong sort function is being made available at that line of code (in the click handler).
How to debug

*

*Set a breakpoint at line 132 of the provided JavaScript in the
Fiddle.

*Click a name in the list.

*While at the breakpoint (execution paused), move to the console and run this in the console:
    thisWindow.find('div.individuals-list').data('individualsList')

*Note the sort() function definition in the list of functions

*Next, in the console run this statement:
thisWindow.find('div.individuals-list').data('individualsList').sort(order)

*Note the return is undefined <-- This is the issue

A: The returned value doesn't transfer from the closure to the instance that called it, the class has to be changed like so:
function IndividualsList(element) {
  var list = [];

  this.add = function(thisIndividual) {
    return $('#Individuals').data('functions').init(element, list).add(thisIndividual);
  }
  this.refresh = function() {
    return $('#Individuals').data('functions').init(element, list).refresh();
  }
  this.sort = function(order) {
    return $('#Individuals').data('functions').init(element, list).sort(order);
  }
}

The breakpoint could have been in one of IndividualsList()'s methods so it can be noticed that the closure returns the desired object while the method does not. Different names for either the functions or methods would help to reinforce that they are separate.


text:
Q: CRA development server stop seeing changes in files I'm having some problems with create-react-app development server (npm/yarn start script). It's stops updating the current errors/warning state, even if I fix them or modify the file. I never had this problem in the last years working with it.
As an example, my current terminal output is:
Compiled with warnings.

src/components/CartList.js
  Line 3:15:  'Divider' is defined but never used  no-unused-vars

src/providers/User.js
  Line 16:17:  'setToken' is assigned a value but never used  no-unused-vars

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

But if I modify these files, nothing change on output. I've tried to restart development server, use yarn instead of npm, open development server on different terminals, increase the number of max file watchers...
The only thing that (temporary) fixed it was to stop development server, delete .eslintcache file, then restart development server.
Current packages and scripts:
"dependencies": {
  "@material-ui/core": "^4.11.2",
  "@material-ui/icons": "^4.11.2",
  "clsx": "^1.1.1",
  "comlink": "^4.3.0",
  "cra-template": "1.0.3",
  "react": "^16.14.0",
  "react-app-rewired": "^2.1.8",
  "react-dom": "^16.14.0",
  "react-router-dom": "^5.2.0",
  "react-scripts": "4.0.1",
  "typescript": "^4.1.3",
  "worker-loader": "^3.0.6"
},
"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test",
  "eject": "react-scripts eject"
},
"config-overrides-path": "src/react-app-rewired.config.js",
"eslintConfig": {
  "extends": "react-app"
}

Hope someone can help me... Thanks!
@EDIT
Using Debian Buster, NPM 6.14.9, Node 14.15.3


text:
Q: Bluetooth automatic mouse connection not working I'd like my HP Bluetooth Mouse x4000b (no usb dongle) to connect automatically when starting my HP laptop (Ubuntu 14.04), but I can't succeed in it : I'm forced to do it manually by clicking the connect button.
I know this topic has been answered many times, but no solution worked for me.
Here's what I tried so far :

*

*Creating the file /etc/default/bluetooth with lines :
HIDD_ENABLED=1
HIDD_OPTIONS="--connect F0:65:DD:7D:EC:A0 --server"

*Putting hciconfig hci0 reset at the end of /etc/init.d/bluetooth

*Putting
/etc/init.d/bluetooth stop
sleep 1
/etc/init.d/bluetooth start

in /etc/rc.local
None of these solution worked, I've read a lot of topics but couldn't find a solution ... that's why I'm asking that here, hoping you can help me troubleshooting that.
Update:
ray@ray-HP-EliteBook-840-G1:~$ hciconfig
hci0:   Type: BR/EDR  Bus: USB
BD Address: F8:16:54:02:9F:62  ACL MTU: 1021:5  SCO MTU: 96:5
UP RUNNING PSCAN ISCAN
RX bytes:4672039 acl:306914 sco:0 events:6516 errors:0
TX bytes:36591 acl:372 sco:0 commands:401 errors:0

ray@ray-HP-EliteBook-840-G1:~$ bluez-simple-agent hci0 F8:16:54:02:9F:62
Creating device failed: org.bluez.Error.ConnectionAttemptFailed: Page Timeout

A: OK To run at start up please, open start up applications from dash and choose new. Name it whatever you want and in the command box copy
sudo hidd --connect F0:65:DD:7D:EC:A0

Save it reboot, cross your fingers.

A: This may not apply though I went between dell and logitech support to find out why my logitech BT mice never autoconnect back to the systems and nobody ever supports it. I had to learn the hard way. Maybe this isn't helpful just figured I'd share my hard learned lesson.
None of my BT devices every connect to any OS/Device other than tablets/cell phones automatically. I've found rule of thumb is I have to unpair/remove the device from the OS/system then reconnect as after the device connects to another device it won't autoconnect to device one after it's most recent connection was device two.

A: Remove your BT mouse and add it again assigning "0000" PIN for pairing, do not use default or auto PIN option. Worked for me.

A: Try blueman-manager. Probably you need to install it using apt-get install blueman.
Install it by use your Terminal, Run "sudo apt-get install blueman" This is a bluetooth manege program.


text:
Q: How access data in JavaScript arrays using $.ajax This is a script when the script is executed I want to load the data into  the div of id #trial. The script is an external array with three names the second I am trying to call is 'sarah'. Whats wrong?
<script>
$(document).ready(function(){
    $("#trial").click(function(){
        var attempt=$.ajax({
            url: "names.js",
            dataType: "script"
        });
        var msg=names[1];
        attempt.done(function( msg ) {
            $( "#trial" ).html( msg );
        });
    });
});
</script>

A: Change your code to this:
<script>
   $(document).ready(function(){
       $("#trial").click(function(){

           $.ajax({
                 url: "names.js",
                 dataType: "script",
                 success: function(res){
                      //todo something with res
                 }
           });
       });
   });
</script>


text:
Q: Error with Laravel authentication I'm new to Laravel and I am trying to implement authentication in my application, when I post the login form this error is returned in my browser:

I have no idea what this error means, where it occurs, or how to fix it.
This is my signin function in my authentication controller that handles all logins:
public function signin()
    {
        // validate the info, create rules for the inputs
        $rules = array(
            'email'    => 'required|email', // make sure the email is an actual email
            'password' => 'required|min:6' // password can only be alphanumeric and has to be greater than 3 characters
        );

        // run the validation rules on the inputs from the form
        $validator = Validator::make(Input::all(), $rules);

        // if the validator fails, redirect back to the form
        if ($validator->fails()) {
            return Redirect::to('/authentication')
                ->withErrors($validator) // send back all errors to the login form
                ->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
        } else {

            // create our user data for the authentication
            $user = array(
                'email'     => Input::get('email'),
                'password'  => Input::get('password')
            );

            // attempt to do the login
            if (Auth::attempt($user)) {

                // validation successful!
                // redirect them to the secure section or whatever
                // return Redirect::to('secure');
                // for now we'll just echo success (even though echoing in a controller is bad)
                return Redirect::to('dashboard.index');

            } else {

                // validation not successful, send back to form
                return Redirect::to('/authentication')
                    ->with('failed', 'Incorrect email / password!');

            }

        }
    }

This is my User model:
<?php

class User extends Eloquent{

    // MASS ASSIGNMENT -------------------------------------------------------
    // define which attributes are mass assignable (for security)
    protected $fillable = array('email','school_id','role_id','activation_key','reset_key','login_status','account_status');

    // LINK THIS MODEL TO OUR DATABASE TABLE ---------------------------------
    protected $table = 'users';

    // DEFINE RELATIONSHIPS --------------------------------------------------
    public function roles() {
        return $this->belongsTo('Role');
    }

    public function schools() {
        return $this->belongsTo('Institution');
    }

    public function lectures() {
        return $this->hasOne('Lecturer');
    }

    public function students() {
        return $this->hasOne('Student');
    }

    public function getId()
    {
        return $this->id;
    }
}

A: Let's take a look at Laravel's default User model:
class User extends Eloquent ...

so far so good
... implements UserInterface, RemindableInterface {

Oooops looks like you're missing something ;)
Also the two traits are not unimportant.
Here's how it should look like:
class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    // MASS ASSIGNMENT -------------------------------------------------------
    // define which attributes are mass assignable (for security)
    protected $fillable = array('email','school_id','role_id','activation_key','reset_key','login_status','account_status');

    // [the rest of your model]


text:
Q: Batch convert Microsoft Word files to HTML files How can Microsoft Word files (.doc, .docx) be converted to HTML files as a batch process running on a Linux server?

A: Install unoconv and put together a script, e.g:
for f in *.doc
do
    unoconv -f html $f
done


text:
Q: cannot see source code section of xcode debugger In the XCode debugger, I can only see the disassembly code, I do not see the section for source code. I tried the "source code and disassembly" options in Debugger display. Nothing changes. Can someone please help me with this?

A: You're never going to see any source code that you don't have access to. If you're stepping into Apple's territory (or any other vendor's for that matter), all you'll get is disassembly.

A: Make sure you check the menus. Visit "Product" > "Debug Workflow" and make sure "Show Disassembly When Debugging" is off. Some rabbit activated it for me...

A: You get to the source code by clicking on the method name in the thread window.


text:
Q: MVC3 Hierarchical View Model with check boxes and radio buttons I'm at the point of pulling what little hair I have left out - been learning MVC over the past few months, so I'm relatively new to it, though I've covered a lot of ground...
I'm having trouble trying to output check boxes and radio buttons with a relatively complex view model.
I have the following View (irrelevant fields removed):
@model CreateMediumModel
@using(Html.BeginForm()) {

                        @Html.LabelFor(m => m.MetaData)

                        @Html.EditorFor(m => m.MetaData)

                    @Html.ValidationMessageFor(m => m.MetaData)

}

The hierarchical View Model looks like this:
public class CreateMediumModel {
    public List<MetaData> MetaData { get; set; }
}

public class MetaData {
    ///
    /// The media type that this meta data belongs to.
    ///
    public int MediaTypeID { get; set; }

    ///
    /// The unique ID for the meta data.
    ///
    public int MetaDataID { get; set; }

    ///
    /// The unique text-based identifier for the meta data. Unique per MediaType.
    ///
    public string Key { get; set; }

    ///
    /// The UI description of the meta data.
    ///
    public string Description { get; set; }

    ///
    /// The max length of text based data.
    ///
    public int Length { get; set; }

    ///
    /// Provides a pre-defined list of values for the meta data.
    ///
    public List<MetaDataOption> Options { get; set; }

    ///
    /// Provides the text-based value for the meta data.
    ///
    public string Value { get; set; }

    ///
    /// Determines which value/s to use from the object graph
    ///
    public MetaDataDataType Type { get; set; }

    ///
    /// Defines the UI sort order of the meta data
    ///
    public int SortOrder { get; set; }
}

public class MetaDataDataType {
    public int MetaDataTypeID { get; set; }
    public MetaDataDataTypeEnum Type { get; set; }
    public bool TextBased { get; set; }
}

public class MetaDataOption {
    ///
    /// The unique ID for the option
    ///
    public int MetaDataOptionID { get; set; }

    ///
    /// The pre-defined option value to display.
    ///
    public string Value { get; set; }

    ///
    /// The sort order of the value in the list.
    ///
    public int SortOrder { get; set; }
}

public enum MetaDataEnum {
    Developer,
    PEGI,
    PEGIContent
}

public enum MetaDataDataTypeEnum {
    ///
    /// Simple text
    ///
    TEXT = 1,

    ///
    /// Multi-line text.
    ///
    MULTITEXT = 2,

    ///
    /// Simple number
    ///
    NUMBER = 3,

    ///
    /// Simple date
    ///
    DATE = 4,

    ///
    /// Simple time
    ///
    TIME = 5,

    ///
    /// Simple DateTime
    ///
    DATETIME = 6,

    ///
    /// Single option selection
    ///
    SELECTION = 7,

    ///
    /// Multi option selection
    ///
    MULTISELECTION = 8
}

Each piece of meta data has a single type; the type defines how the meta data is edited and how it's displayed (and where the data is stored in the data layer). The display side of things is working perfectly fine.
When the type is "SELECTION", I want to display a single set of radio buttons, where only one can be selected. When the type is "MULTISELECTION", I want to display a set of checkboxes, where more than one can be selected. I can do this, but I've been able to successfully bind the values selected to the model.
At the moment, I'm using an editor template to display the List, which looks like this:
@model MetaData
@using Business.Enumerations

@if(Model != null) {
    @Html.HiddenFor(m => m.MetaDataID)

            @Model.Description

            @switch(Model.Type.Type) {
                case MetaDataDataTypeEnum.NUMBER:
                case MetaDataDataTypeEnum.DATE:
                case MetaDataDataTypeEnum.TEXT:
                case MetaDataDataTypeEnum.TIME:
                case MetaDataDataTypeEnum.DATETIME:
                    @Html.TextBoxFor(m => m.Value)
                    break;
                case MetaDataDataTypeEnum.MULTITEXT:
                    @Html.TextAreaFor(m => m.Value)
                    break;
                case MetaDataDataTypeEnum.SELECTION:
                    foreach(var o in Model.Options) {
                        @Html.RadioButtonFor(m => m.Value, o.MetaDataOptionID) @o.Value
                    }
                    break;
                case MetaDataDataTypeEnum.MULTISELECTION:
                    foreach(var o in Model.Options) {
                        @Html.CheckBoxFor(m => m.Options.FirstOrDefault(opt => opt.Selected).Selected) @o.Value
                    }
                    break;
   }

}

This will be expanded when I get over this issue, but for now, it outputs everything as expected - I see a radio button list for SELECTION types and a checkbox list for MULTISELECTION types, but it's not bound to the model properly when I call the submit action.
I'm going a bit crazy. Can anyone see anything obvious I'm doing wrong?
As an aside:
I've tried to create an editor template for the MetaDataOption class too, but there seems to be a bug surrounding passing a List into a sub-editor template, when a template name is specified (Html.EditorFor(m => m.Options, "MetaDataOptionsSingle") and Html.EditorFor(m => m.Options, "MetaDataOptionsMulti")) - if I don't specify a name for the editor template, the template can have a MetaDataOption model, but if a specify a name, it requires a List.

UPDATE
OK, I've managed to get this working, but I'm having problems with the unobtrusive validation of checkboxes now. The fix is as follows:
The MetaData editor template now looks like this:
@model MetaData
@using Business.Enumerations

@if(Model != null) {
    @Html.HiddenFor(m => m.Description)
    @Html.HiddenFor(m => m.Type)

            @Model.Description

            @switch (Model.Type) {
                case MetaDataDataTypeEnum.NUMBER:
                case MetaDataDataTypeEnum.DATE:
                case MetaDataDataTypeEnum.TEXT:
                case MetaDataDataTypeEnum.TIME:
                case MetaDataDataTypeEnum.DATETIME:
                    @Html.TextBoxFor(m => m.Value)
                    break;
                case MetaDataDataTypeEnum.MULTITEXT:
                    @Html.TextAreaFor(m => m.Value)
                    break;
                case MetaDataDataTypeEnum.SELECTION:
                    if(Model.Options != null) {
                        foreach (var o in Model.Options) {
                            @Html.RadioButtonFor(m => Model.SelectedMetaDataOptionID, o.MetaDataOptionID)
                            @o.Value
                        }
                    }
                    break;
                case MetaDataDataTypeEnum.MULTISELECTION:
                    @Html.EditorFor(m => m.Options)
                    break;
            }

}

I added another EditorTemplate for the MULTISELECTION EditorFor:
@model MetaDataOption

@if(Model != null) {
    @Html.HiddenFor(m => m.MetaDataOptionID)
    @Html.CheckBoxFor(m => m.Selected)
    @Model.Value
}

And the MetaDataOption class is as follows:
public class MetaDataOption {
    ///
    /// The unique ID for the option
    ///
    public int MetaDataOptionID { get; set; }

    ///
    /// The pre-defined option value to display.
    ///
    public string Value { get; set; }

    ///
    /// The sort order of the value in the list.
    ///
    public int SortOrder { get; set; }
}

The model now populates correctly when submitted. However, validation occurs on ALL checkboxes rendered by the editor template (in the post action method, as I have not yet implemented the client validation), yet there are no data annotations on the "Selected" member of the MetaDataOption class.
Something to note - the "Options" member of the MetaData class is null if no checkboxes are selected.
I have tried to set the Selected property to a nullable bool (bool?), but I run in to issues with the CheckBoxFor() helper in the MetaDataOption editor template not accepting a nullable bool.
This is sending me crazy... I've spent two days trying to get something working that I'd have whizzed through with ASP.Net!


text:
Q: Get label of a given dbpedia resource For a given Dbpedia Resource, I want to get its Rdfs: label. For example, from http://fr.dbpedia.org/resource/Automobile, I should get Automobile,
I tried with easy RDF:
$label= new \EasyRdf\Graph;
$re= $label->label('http://fr.dbpedia.org/resource/Automobile');
var_dump($re)

but it gives me null as a result
I tried also with this Sparql request but it gives me null too:
SELECT ?label WHERE
{
  <http://fr.dbpedia.org/resource/Automobile> rdfs:label ?label.
}

A: Just eliminate the (fr.) from your query:
SELECT ?label WHERE
{
  <http://dbpedia.org/resource/Automobile> rdfs:label ?label.
}


text:
Q: Serialização e Deserialização JSON em aplicação desktop
{"result":[[{"CodigoReduzido":"019076-3","Estoque":200,"Preco":900.77,"PrecoST":225.19,"Descricao":"
  PLACA DE VIDEO ASUS AMD RADEON R5 230 1GB DDR3 64BITS R5230-SL-1GD3-L
  *IMP","Grupo":"PLACA DE VIDEO","Marca":"ASUS","Origem":6,"NCM":"8473.30.43","EAN":"0000000000000","PesoBruto":0,"Largura":0,"Altura":0,"Profundidade":0,"Garantia":"12
  Meses","AliqIPI":0,"AliqICMS":12,"Unidade":"PC","MultiploVenda":1,"Link":"https://www2.meusite.com.br/localnew/_img/fotos_produtos/019076-3.jpg","PartNumber":"R5230-SL-1GD3-L"}]]}

Estou Enviando o Código que estou desenvolvendo..
    private void ButtonConvert_Click(object sender, EventArgs e)
    {
        string fileContents;
        WebRequest request = WebRequest.Create(textBox1.Text);

        WebResponse response = request.GetResponse();
        Stream data = response.GetResponseStream();
        string html = String.Empty;
        using (StreamReader sr = new StreamReader(data))
        {
            fileContents = sr.ReadToEnd();
        }
        richTextBox1.Text = fileContents;
        JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
        Result paging = jsonSerializer.Deserialize<Result>(fileContents);
        textBox2.Text = textBox2.Text + paging.Descricao;

        for (int i = 0; i < 50; i++)
        {

            //richTextBox1.Text = richTextBox1.Text + paging.results[i].id + " ";
            //richTextBox1.Text = richTextBox1.Text + paging.results[i].buyer.id + " ";
            //richTextBox1.Text = richTextBox1.Text + paging.results[i].buyer.first_name + " ";

        }

    }
    public class Result
    {
        public string CodigoReduzido { get; set; }
        public int Estoque { get; set; }
        public double Preco { get; set; }
        public double PrecoST { get; set; }
        public string Descricao { get; set; }
        public string Grupo { get; set; }
        public string Marca { get; set; }
        public int Origem { get; set; }
        public string NCM { get; set; }
        public string EAN { get; set; }
        public double PesoBruto { get; set; }
        public int Largura { get; set; }
        public int Altura { get; set; }
        public int Profundidade { get; set; }
        public string Garantia { get; set; }
        public int AliqIPI { get; set; }
        public int AliqICMS { get; set; }
        public string Unidade { get; set; }
        public int MultiploVenda { get; set; }
        public string Link { get; set; }
        public string PartNumber { get; set; }
    }

    public class RootObject
    {
        public List<Result> result { get; set; }
    }

Utilizando json2csharp
generate c# classes from json
    public class RootObject
    {
         public List<List<>> result { get; set; }
    }

Mais eu não consegui utilizar dessa maneira..
Agora creio que consegui explicar melhor
Agradeco a ajuda dos amigos...

A: Nativamente, você pode utilizar a classe System.Web.Script.Serialization.JavaScriptSerializer.
new JavaScriptSerializer().Serialize(obj);

Serializa o objeto obj.
new JavaScriptSerializer().Deserialize<T>(objStr);

Faz o papel contrário, desserializando a string objStr para o tipo T.

A: O pacote JSON.NET faz a serialização de um objeto pra você:

https://www.nuget.org/packages/newtonsoft.json/

Assim:
string json = JsonConvert.SerializeObject(produto);

E desserializando:
var produto = JsonConvert.DeserializeObject<Produto>(jsonString);

A documentação completa está aqui.

A: Resolvido Problema de Duas Maneiras
    public class RootObject
    {
        public List<List<Result>> result { get; set; }
    }

    public class Result
    {
        public string CodigoReduzido { get; set; }
        public int Estoque { get; set; }
        public double Preco { get; set; }
        public double PrecoST { get; set; }
        public string Descricao { get; set; }
        public string Grupo { get; set; }
        public string Marca { get; set; }
        public int Origem { get; set; }
        public string NCM { get; set; }
        public string EAN { get; set; }
        public double PesoBruto { get; set; }
        public int Largura { get; set; }
        public int Altura { get; set; }
        public int Profundidade { get; set; }
        public string Garantia { get; set; }
        public int AliqIPI { get; set; }
        public int AliqICMS { get; set; }
        public string Unidade { get; set; }
        public int MultiploVenda { get; set; }
        public string Link { get; set; }
        public string PartNumber { get; set; }
    }

Resolvido o problema da Seguinte Maneira Utilizando JSON.NET
    private void Json2_Click(object sender, EventArgs e)
    {
        try
        {
            string fileContents;
            WebRequest request = WebRequest.Create(textBox1.Text);

            WebResponse response = request.GetResponse();
            Stream data = response.GetResponseStream();
            string html = String.Empty;
            using (StreamReader sr = new StreamReader(data))
            {
                fileContents = sr.ReadToEnd();
            }
            richTextBox1.Text = fileContents;

            JsonTextReader reader = new JsonTextReader(new StringReader(fileContents));
            RootObject rootobject = JsonConvert.DeserializeObject<RootObject>(fileContents);
            textBox2.Text = "";
            for (int i = 0; i < 1; i++)
            {
               for (int j = 0; j < rootobject.result[i].Count() ; j++)
                {
                    textBox2.Text = textBox2.Text + rootobject.result[i][j].CodigoReduzido + "   ";
                    textBox2.Text = textBox2.Text + "  " + rootobject.result[i][j].Descricao + "\r\n";
                    */* aqui voce coloca o restante dos seus campos */*
                }
            }
        }
        catch (Exception ex)
        {
            textBox3.Text = ex.Message;
        }
    }

Solução usando Modo Nativo JavaScriptSerializer
    private void ButtonConvert_Click(object sender, EventArgs e)
    {
        try
        {
            string fileContents;
            WebRequest request = WebRequest.Create(textBox1.Text);
            WebResponse response = request.GetResponse();
            Stream data = response.GetResponseStream();
            string html = String.Empty;
            using (StreamReader sr = new StreamReader(data))
            {
                fileContents = sr.ReadToEnd();
            }
            richTextBox1.Text = fileContents;
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();

            RootObject rootobject = new JavaScriptSerializer().Deserialize<RootObject>(fileContents);
            textBox2.Text = "";
            for (int i = 0; i < 1; i++)
            {
                for (int j = 0; j < rootobject.result[i].Count() ; j++)
                {
                    textBox2.Text = textBox2.Text + rootobject.result[i][j].CodigoReduzido + "   ";
                    */* aqui voce coloca o restante dos seus campos */*
                }
            }
        }
        catch (Exception ex)
        {
            label1.Text = ex.Message;
        }

    }


text:
Q: How would I put a BR tag into double quotes? How would I write a regular expression that selects the lines containing the html BR tag and surround it with double quotes?
Would this be correct? "
"

A: No, In HTML that would be incorrect, you would just type

 however in php it could be used like echo "
";


text:
Q: i get spaces interpretted as boxes by the web broswer for the font "bebas" how to work around this Basically, this font type interprets spaces as boxes, for some reason.  How do I work around this without having to change the font type?

A: well you will HAVE to add spans or other tags. I do not think there is anyways except by using php (Which I do not know). you will have to use
@font-face {
font-family: font-name;
src: url('/*url here*/');}
.my-font{
font-family: font-name;
}

and spans
<span class='my-font'>(Char that makes box?)</space>