Q:

Updating values in table based on ranges defined in another table

I have two tables definitions and history with the following schema:
create table definitions (
    id UNIQUEIDENTIFIER,
    revision INT,
    majorVersion INT
  );

create table history (
   id UNIQUEIDENTIFIER,
   revision INT
   );

I want to update table history with another column majorVersion where the value ranges are defined in table definitions. For example, if records in definitions look like:
+--------------------------------------+-----------+---------------+
|                  id                  |  revision |  majorVersion |
+--------------------------------------+-----------+---------------+
| 9f717823-b9ca-4c7b-97f9-7770aaafb468 |         2 |             1 |
| 9f717823-b9ca-4c7b-97f9-7770aaafb468 |         4 |             2 |
+--------------------------------------+-----------+---------------+

Then the updated table history should look something like this:
+--------------------------------------+-----------+---------------+
|                  id                  |  revision |  majorVersion |
+--------------------------------------+-----------+---------------+
| 9f717823-b9ca-4c7b-97f9-7770aaafb468 |         1 |             1 |
| 9f717823-b9ca-4c7b-97f9-7770aaafb468 |         2 |             1 |
| 9f717823-b9ca-4c7b-97f9-7770aaafb468 |         3 |             2 |
| 9f717823-b9ca-4c7b-97f9-7770aaafb468 |         4 |             2 |
+--------------------------------------+-----------+---------------+

Here is a SQL Fiddle with a more number of rows.
The table definitions can contain potentially thousands of different id and multiple majorVersion. Subsequently, table history can contain can contains close to a million rows.
I want to make the query as fast and optimized as possible. One possible solution is to use something like this:
update history
set majorVersion = (
  select top 1 majorVersion
  from definitions
  where definitions.id = history.id
  and definitions.revision >= history.revision
  order by definitions.majorVersion
  )
where history.majorVersion = 0;

But the problem with this is that we are querying rows for every row in table history (which can be very large compared to definitions). Any suggestions on how to improve upon this?

A:

One of two solutions
solution 1
If you are able to split the work in two update statements, first update all the matching revisions
UPDATE h
set h.majorVersion = d.majorVersion
FROM dbo.history h
INNER JOIN
dbo.definitions d
ON d.id = h.id
and d.revision = h.revision;

Then use a CTE and windowing functions to update the majorVersion's that are still 0 on the updated table
;WITH CTE
AS
(
SELECT ID,revision, MAX(majorVersion) OVER (PARTITION BY Value2) as majorVersionUpdated,majorVersion
FROM
(
    SELECT ID, majorVersion,revision
        ,COUNT(case when majorVersion = 0 then NULL else majorVersion END) OVER (ORDER BY ID DESC,revision desc) AS Value2
    FROM dbo.history
) a
)

UPDATE CTE
SET majorVersion = majorVersionUpdated
WHERE majorVersion = 0;

SELECT * FROM dbo.history;

An index like this could help
CREATE INDEX IX_id_revision
on dbo.history(id,revision)
include(majorVersion)

Result
SELECT * FROM dbo.history;

id                                 revision majorVersion
9F717823-B9CA-4C7B-97F9-7770AAAFB468    1   1
9F717823-B9CA-4C7B-97F9-7770AAAFB468    2   1
9F717823-B9CA-4C7B-97F9-7770AAAFB468    3   1
9F717823-B9CA-4C7B-97F9-7770AAAFB468    4   2
9F717823-B9CA-4C7B-97F9-7770AAAFB468    5   2
9F717823-B9CA-4C7B-97F9-7770AAAFB468    6   3
9F717823-B9CA-4C7B-97F9-7770AAAFB468    7   3
546EF185-54AC-4AF8-82C6-61EFA3202353    1   1
546EF185-54AC-4AF8-82C6-61EFA3202353    2   2
546EF185-54AC-4AF8-82C6-61EFA3202353    3   2

SQL Fiddle

solution 2,  still two updates but with a CROSS APPLY and a self join. The self join is not ideal.
First update all the matching revisions
UPDATE h
set h.majorVersion = d.majorVersion
FROM dbo.history h
INNER JOIN
dbo.definitions d
ON d.id = h.id
and d.revision = h.revision;

Then do a self join to update the other majorVersions to the next one that is not 0
UPDATE H
SET h.majorVersion = h2.majorVersion
FROM dbo.history h
CROSS APPLY(
SELECT MIN(CASE WHEN h2.majorVersion = 0
           THEN NULL
           ELSE h2.majorVersion END) as majorVersion
FROM
dbo.history h2
WHERE h2.id = h.id
AND h2.revision >= h.revision
) h2
WHERE h.majorVersion = 0;

SELECT * from dbo.history;

SQLFiddle
You would have to add BEGIN TRANSACTION ... COMMIT TRANSACTION to the updates if they have to be executed in one batch. The fastest way will depend on additional factors, such as your indexes & data, more than an example can show. YMMV


Q:

how to make a custom kernel which boots a custom initrd.img file

I was mining information on "how to create a kernel" and have created a simple kernel which just prints "my first kernel". Later, I went on to creating a small initrd.img file which launches a "busybox ash -login" command. Now, my question is, how to make the kernel use the initrd.img file to boot into a shell [the $ screen] ??
I am trying to create my own Linux Distribution and so I am trying to understand the basics
I do know my task does not require an initrd but I am curious that's all :)

A:

Check out this link. Here exactly your requirement is explained where it prints hello world at the boot by creating initrd image.


Q:

How to block another domain to access and get result from my website?

Another domain is showing duplicate content of my website (all pages)
When I entered this domain I see my site content.
If I change something on my site, I see it immediately on the another domain.
I think he's using some function fopen or curl or something else to show my content immediately from my website
How do I block it?
*my server: cpanel, php5

A:

You can use their IP address to serve them a 404 page. Or if you really want to be clever. For just their IP address serve wrong or embarrassing information that looks similar but is not the good content.
if($_SERVER['REMOTE_ADDR'] == "12.1.3.5"){ //banned IP

    //do something else

}


Q:

Error: Attempt to run compile-and-go script on a cleared scope

Since upgrading to Firefox 4.0, I've noticed that I'm occasionally getting an error in the console stating:

attempt to run compile-and-go script on a cleared scope

The only information I can find about this on the net currently is on the mozilla groups forum, where it is suggested that it's something to do with session restoring. In my case, though I haven't been able to reliably reproduce the error, it happens at any time, not just after a restore.
What's the deal? How do I stop the error?

A:

For me (Firefox 11, Firebug 1.9.1) it happens sometimes after I refresh the page (either F5 or CTRL+F5) while debugger is paused on a breakpoint.
The solution seems to be to continue the execution of the script, and refresh the page only when Firebug is not paused.

A:

In my case, it was document.write method causing the problem on Firefox 4, 5, 6 on Windows. Linux versions are unaffected. What I had to do is to overwrite document.write method.
I aware that document.write shouldn't be used these days, but deployJava.js, a standard Java Applet deployment script written by Sun/Oracle, is using it. Google is using it in Google AdSense ads. document.write is everywhere.
<script>
    var documentWriteOutput = '';
    var got = document.write;
    document.write = function(arg) { documentWriteOutput += arg; }
</script>
<script src="badScriptThatIsUsingDocumentWrite.js"></script>
<script>
    runBadScriptThatIsUsingDocumentWrite();
    document.write = got;
    // Do whatever you want with the documentWriteOutput
    // e.g. $('#somewhere').html(documentWriteOutput);
</script>

I hope this helps. However, I saw lots of "solutions" on the Internet that didn't work for me. It may mean that "Attempt to run compile-and-go script on a cleared scope" is a Firefox JavaScript engine problem/bug.

A:

I've noticed that this error can happen if you write to the document with document.write after the document has completed loading (e.g. in a function called from JQuery's $(document).ready() method). When this happens, it seems that Firefox discards the old document and writes a new one. I don't know if this is new behavior or not. It seems that when you try to operate on the old document, e.g. with JQuery selectors, you get this error. For me, fixing the script in question to not call document.write after the document had loaded fixed the error.


Q:

What's the best way to synchronize times to millisecond accuracy AND precision between machines?

From what I understand, the crystals on PC's are notorious for clock skew. If clocks are always skewing, what is the best way to synchronize clocks between machines with millisecond accuracy and precision? From what I've found, NTP and PTP are possible solutions, but I was wondering if anybody had any experience on stackoverflow.com!
I understand NTP is the popular choice, but am wondering if anybody has had any experience with PTP (IEEE1588)

A:

Just run the standard NTP daemon.
It does have options to take input from several GPS devices as well as talking to network servers.
Edit: I was referring to http://www.ntp.org/, not the one that comes with Windows.
I don't have any suggestion as to what NTP clients are best for windows, but for Unix machines there's no real reason to not run NTP.

A:

Here's some 15-year-old software that syncs to within a hundredth of a millisecond.  (My team wrote it when NTP wasn't good enough for our lab.)
From the conference paper's abstract:  "A distributed clock for networked commodity PC's. With no extra hardware, this clock correlates sensor data from multiple PC's with latency and jitter under 10 microseconds average, 100 microseconds worst case."
Source code: https://github.com/camilleg/clockkit
(Until 2020 Feb 13 it was at http://zx81.isl.uiuc.edu/clockkit/, now offline.)

A:

You cannot synchronize machines to the level of milliseconds by exchanging data, because any data exchange itself already takes at least milliseconds to happen and thus spoils your result! Even protocols that try to first measure how long a data transfer takes and then sending out the time info (taking the measured delay into account) are just a bit better than average but they are still not good since not every data transfer takes equal time (just constantly ping a server on the Internet and see how every ping has a different delay).
The only way to really synchronize two computers in the milliseconds range is by having them both obtain the time from the same source via a transfer method that has no unknown or constantly changing delay. E.g. if both receive a satellite signal, that broadcasts the time. The signal will always have a constant delay (from satellite to earth) and they are both receiving it almost within the same nanosecond.
Germany for example has a radio controlled time. Somewhere in the country is an atomic clock (that has correct time to the nanosecond for hundreds of years) and some sender permanently broadcast the current time on a given frequency all over the country. Alarm clocks and even wristwatches exist that can receive this time and permanently synchronize with it (well, not really permanently, most models do that only once every 24 hours to save battery runtime). Such receiver devices also exist for computers and come with software that can permanently synchronize your computer clock with that time signal.
As far I know GPS also sends time information (either that, or the time can be calculated somehow from the GPS information, I'm not too familiar with the GPS protocol). So attaching a GPS receiver to both computers can probaly also get them synchronized to the millisecond. If your synchronization is done via the Internet however, don't expect a better synchronization than one computer being at most 20 milliseconds off.
To update on the commenter,
NTP is not that accurate as people love to claim here:

NTP can usually maintain time to within tens of milliseconds over the
  public Internet, and can achieve better than one millisecond accuracy
  in local area networks under ideal conditions.

Source: Wikipedia
I would rather keep them all in sync without any network involved and farther keeping them in sync to the official GMT time and here GPS is probably the only way to get really accurate results on all machines (and that not only down to the ms, actually down to microseconds).


Q:

Congratulations, Arturo!

I think congratulations are due to Arturo Magidin on hitting 100k reputation points here on MSE! All the users of this site are better off for his tireless contributions, and we appreciate his positive influence on mathematics and mathematics education via this site.

A:

Thank you kindly, one and all. Now, if I can only get as much done in my research...

A:

Indeed, kudos! You're actually the first user on the entire network to reach this 100k threshold outside of Stack Overflow -- which is 333x larger by my current (poor) math calculations. Yes, even before the older and larger sites like Super User and Server Fault, etc.
I also announced this on Twitter to ~62k followers. Congrats!
https://twitter.com/#!/codinghorror/status/164058222368530432


Q:

How can I get a link to load with overflow hidden and show full content on hover?

I am trying to get a link to load with the text cut off at a certain width. Then when the user hovers over, it shows the full content of the anchor tag.  I have a fiddle at http://jsfiddle.net/GCXsq/564/ but it initially shows the full content of the link, and it also makes the link width 0 on hover.

A:

http://jsfiddle.net/GCXsq/565/
Your main problem was that your hovering element had no (elemental) children, so you were always animating from 0 width.


Q:

SRS indicator light keeps coming on, code 7-2 "Internal failure of SRS unit"

As in this question, my SRS light keeps coming on.  I read the code using a paperclip in the OBDII connector, which is always code 7-2 "Internal failure of SRS unit", and then reset it using the SRS connector.  It stays off for weeks or months and then comes back on.  Any idea how to troubleshoot this?  Or do I have to take it to a mechanic?  Obviously messing around with airbags is dangerous if you don't know what you're doing.
2003 Honda Civic

A:

I eventually just bit the bullet and let the dealership replace the SRS unit for several hundred dollars.  Light hasn't come back on since.


Q:

Copy range to clipboard

I would like to copy a range (specified in the VBA code: A1:I1) into the clipboard, so that the user can paste it whereever he like. How could I do this?

A:

Range has a Copy method on it, so to copy a range you can just do:
Sub Macro1()
    Range("A1:I1").Copy
End Sub


Q:

'In any case, follow the guideline "prefer ++i over i++" and you won't go wrong.' What is the reason behind this in C?

I had come across this answer to this question. In one of the line, the author mention's:

In any case, follow the guideline "prefer ++i over i++" and you won't go wrong.

I know that ++i is slightly faster than i++, but thought that there is no reason for them to go wrong. I searched for a while, and the closest I could get to was this. It explained clearly that why is it preferred to use ++i, but not still how could you go wrong using i++.
So can anyone tell me how can i++ go wrong?
NOTE: My question isn't a dupe, as I am not asking about the performance. I have already seen that question. I am asking how can i++ be wrong as mentioned in the answer I have mentioned above.

A:

In the case of
for (i=start; i<end; i++)

vs
for (i=start; i<end; ++i)

their meanings are completely identical, because the value of the expressions i++ and ++i are not used. (They are evaluated for side effects only.) Any compiler which produces different code for the two is pathologically bad and should be chucked in the garbage. Here, use whichever form you prefer, but i++ is idiomatic among C programmers.
In other contexts, use the form that yields the value you want. If you want the value from before the increment, use i++. This makes sense for things like:
index = count++;

or
array[count++] = val;

where the old value of count becomes the index of a new slot you're going to store something in.
On the other hand, if you want the value after increment, use ++i.
Note that for integer types, the following are all completely equivalent:

i += 1
++i
i++ + 1

and likewise the following are equivalent:

(i += 1) - 1
i++
++i - 1

For floating point and pointers it's more complicated.
As far as any objective reasons are concerned, the advice you found is just nonsense. If on the other hand you find ++i easier to reason about, then feel free to take the advice, but this is going to depend entirely on the individual and what you're used to.


Q:

Every locally integrable function defines a Radon measure

I have just started with Measure Theory and I have read several times that

Every locally integrable function defines a Radon measure.

I understand this statement in the sense that if we have $f\in L^1_{loc}(\mathbb{R}^N)$ (respecto to Lebesgue measure) , then $\mu(E)=\int_{E}f(x)dx$ (where the integral is respect to Lbesgue measure) defines a Radon measure. Is this right? How could I prove it?
Is there any measure which is not of this form?
Maybe these questions are trivial, but I am a little lost.
Thanks.
Edit: After see the answer of @JustDroppedIn I was wondering what happens if $f$ is not non-negative.  I thought that in this case we would obtain a signed measure. However, if $f$ we descompose $f=f^+-f^-$, where $f^+=\frac{f+|f|}{2}\geq{0}$ and $f^-=\frac{f-|f|}{2}\geq{0}$, then $\mu(E)=\int_E f=\int_E f^+-\int_E f^- $ and, by the answer of @JustDroppedIn, $\mu$ is the difference of two positive Radon measures. The problem is that this difference doesn't have to bee a signed measure so I would like to know what extra hypothesis we neeed above $f$ to obtain a signed Radon measure.

A:

Let's recall: a Radon measure is a measure $\mu:\mathcal{B}(\mathbb{R}^N)\to[0,\infty]$ such that $\mu$ is regular and $\mu$ is locally finite. Suppose that $f\in L^1_{loc}(\mathbb{R}^N)$ and that $f\geq0$. Define $\mu(E)=\int_Ef$. This is a measure and the fact that $f\in L^1_{loc}$ shows immediately that $\mu$ is locally finite. Regularity of $\mu$ follows directly from the regularity of the Lebesgue measure and an application of the well-known convergence theorems.


Q:

Export Highcharts polar chart csv with categories in place of polar coordinates

I've implemented a polar chart in which each series has 4 values corresponding to 4 categories. When I export the chart csv, the category column contains polar coordinates. I would like to replace these with the corresponding category name. How do I do this?
Adding the categories to each series, had no effect. I also tried adding a categories property to the xAxis, but it had not effect. An xAxis.label formatter successfully returns the category name for each data polar coordinate.
const options = {
  chart: {
    polar: true,
  },
  title: {
    text: '',
  },
  tooltip: {
    valueDecimals: 2,
    headerFormat: '
',
  },
  legend: {},
  pane: {
    startAngle: 0,
    endAngle: 360,
  },
  xAxis: {
    tickInterval: 45,
    min: 0,
    max: 360,
    labels: {
      // eslint-disable-next-line
      formatter: function() {
        switch (this.value) {
          case 45:
            return 'Experience'
          case 135:
            return 'Frictionless'
          case 225:
            return 'Low Price'
          case 315:
            return 'Brand'
          default:
            return ''
        }
      },
    },
  },
  yAxis: {
    min: 0,
    max: 10,
    labels: {
      format: '{}',
    },
  },
  plotOptions: {
    series: {
      pointStart: 45,
      pointInterval: 90,
    },
    column: {
      pointPadding: 0,
      groupPadding: 0,
    },
  },
  series: kahnSeries,
}

A:

To avoid changing the chart's current display, I wrapped the getCSV function and replaced the CSV category values. If there was a simpler way, please share it.
{
  (function (H) {
    H.wrap(H.Chart.prototype, 'getCSV', function (
      proceed,
      useLocalDecimalPoint
    ) {
      // Run the original proceed method
      const result = proceed.apply(
        this,
        Array.prototype.slice.call(arguments, 1)
      )
      const itemDelimiter = ','
      const lineDelimiter = '\n'
      const rows = result.split(lineDelimiter)
      let newResult = ''
      let rowCategories = false
      rows.forEach((row, rowIndex) => {
          const columns = row.split(itemDelimiter)
          if (rowIndex === 0 && columns[0] === '"Category"') {
            rowCategories = true
          }
          if (rowIndex > 0 && rowCategories) {
            let newRow = formatter(columns[0])
            columns.forEach((column, columnIndex) => {
              if (columnIndex > 0) {
                newRow += itemDelimiter
                newRow += column
              }
            })
            newResult += newRow
          } else {
            newResult += row
          }
          if (rowIndex < rows.length - 1) {
            newResult += lineDelimiter
          }
        }
      )
      return newResult
    })
  }(Highcharts))
}


Q:

Bootstrap tab: strange behaviour in ios chrome

I noticed very strange behaviour of bootstrap tab plugin in my iOS chrome browser. When I click on tab once - chrome shows its loading bar (blue line under the address field), I click on other tab - the bar is hide. One again I click on tab - the bar is visible. See the attachments. All tabs are without any ajax-loaded content. The latest version.
Had somebody same issues maybe?
Thank you

A:

You can try prevent the default behavior of the links by adding this inside your document ready.
$('ul.classOfUlTab li a').click(function(e) {
    e.preventDefault();
});

This will works because will prevent the #nnn(id of current tab) that is pushed to the url (thus showing address bar again).
The only downside I think of it now is that the #nnn will not update on the url. Can't remember if tabs load the proper one when you refresh the page but if it does, then you lost that functionality (which enables the 'back' of browser to go to previous tab).


Q:

Should I write custom validation or configurate spring correctly?

I have an entity. I use rest controller.
My goal is to validate all fields in the coming JSON object. If I find one or more incorrect fields, I need to return all incorrect fields. How can I do it with spring?
Should I check every field in try - catch?
@Entity
public class Client {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Size(min = 4, message = "Min length 4")
    private String first_name;

    @Size(min = 4, message = "Min length 4")
    private String last_name;

    @Size(min = 4, message = "Min length 4")
    private String fathers_name;

}

A:

You just need to annotate your client with @RequestBody and @Valid in rest method. Here is an example:
@RestController
@RequestMapping("/api/client")
public class ClientController {
    @PostMapping
    public ResponseEntity createNewClient(@RequestBody @Valid Client client) {
        // insert client
        return new ResponseEntity(HttpStatus.CREATED);
    }
}

If JSON data will be not valid, method will throw MethodArgumentNotValidException. You can handle it in such way:
@ControllerAdvice
public class ExceptionHandlerController {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleArgumentNotValidException(
            MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        BindingResult bindingResult = ex.getBindingResult();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errors.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }

}


Q:

Key-Agreement & Key-Transport for Symmetric Authentication System

Question: I want to know what kind of Master Key sharing process is pursuit on Symmetric encryption environments (strictly symmetric, also in the key sharing scheme).
As I am aware there are several ways to establish the Master Key transportation and storage between two entities. The processes can pursuit a Key-Agreement or a Key-Transport scheme.
In key transportation a key wrapping function is used to protect the shared secret, then I assume that we do not need any public-key system such as DHKE or ECDH.
In key agreement asymmetric encryption processes are used to transport master keys between entities, then this is not a full symmetric master key exchange, correct?
Thanks in advance.

A:

For a full symmetric key key transport, the symmetric key is created from a random number generator. This is then signed with the owners static private key and then encrypted with the recipients static public key (key wrapping), and then sent to the recipient. The recipient will receive, decrypt and verify the signature, and the symmetric key is decided on. Whilst a key agreement algorithm like ECDH(E) or DH(E) isn't needed, an asymmetric cipher such as RSA is needed. This is referred to as a KEM system (key management), and requires an asymmetric cipher algorithm for the key wrapping.
For a key agreement or KEX (key exchange), then ECDH(E) or DH(E) is used, where both parties exchange bits of info and then calculate a shared secret, which goes through a HKDF to convert in into the format of a symmetric key.
So even for key wrapping, an asymmetric cipher must be used at some point, so that the key can be securely transported to the recipient, and it's authenticity verifiable.


Q:

add different data at the end of different lines in a file

I have a txt file with the following structure:

and I want to add to the end of each long line, the data (after the comma) of the short lines above them, without the description (STN_NO, STN_ID, INST_HT), like that:

is it possible? Any ideas?
p.s. I am using puthon 3.3

A:

Alternatively, you could use a simpler (albeit longer) solution that does not involve regex.
f = open('file.txt')
for line in f:
    line = line.replace('\n', '')
    if 'STN_NO' in line:
        stn_no = line.split(',')[-1]
        print(line)
    elif 'STN_ID' in line:
        stn_id = line.split(',')[-1]
        print(line)
    elif 'INST_HT' in line:
        inst_ht = line.split(',')[-1]
        print(line)
    else:
        print(line[:-1] + ',' + stn_no + ',' + stn_id + ',' + inst_ht)

Note that this puts the semicolon from the INST_HT line back at the end of every long line. If not desired, it can be removed with inst_ht[:-1].


Q:

Add documents to draft envelope without signHereTabs

we are developing, with Java library from REST API, a procedure to sign multiple documents where the signature position is set using anchorString in signHereTabs for each signer (anchorString is a string inserted into the document to be signed);
since we have documents with size greater than 25MB, we are using what has been reported in https://developers.docusign.com/esign-rest-api/guides/resource-limits , that is we create a draft envelope (status=created) and then we updates the envelope with the documents;
the problem is that when we set the envelope with status = sent, the signer receives the email, open the link to DocuSign, but only the first document allow to access the anchorString.
Is there any particular way to update the list of documents in the draft envelope ?
Thanks
...
// add a recipient to sign the document, identified by name and email we used above
int recipientId = 0;
List<Signer> signerList = new ArrayList<Signer>();

/* to fix the position where the signature has to be inserted */
int buyerIdx = 0;
int supplierIdx = 0;
for(DSSignerInfo signerInfo : signers) {
  Tabs tabs = new Tabs();

  Signer signer = new Signer();
  signer.setEmail(signerInfo.getEmail());
  signer.setName(signerInfo.getName());
  signer.setRecipientId(String.valueOf(++recipientId));
  signer.setRoutingOrder(String.valueOf(recipientId)); // sequential
  signer.setRoleName("role unknown");

  RecipientEmailNotification emailNotification = new RecipientEmailNotification();
  emailNotification.setEmailBody("emailBody - "+signerInfo.getName());
  emailNotification.setEmailSubject("emailSubject - "+signerInfo.getName());
  emailNotification.setSupportedLanguage(signerInfo.getLanguage());
  signer.setEmailNotification(emailNotification);

  // create a signHere tab somewhere on the document for the signer to sign
  // default unit of measurement is pixels, can be mms, cms, inches also
  for(int documentId = 1; documentId <= documentFiles.size(); documentId++) {
    SignHere signHere = new SignHere();
    signHere.setDocumentId("" + documentId);
    signHere.setPageNumber("1");
    signHere.setRecipientId(String.valueOf(recipientId));

    if(signerInfo.getRole().equalsIgnoreCase("buyer")) {
      signHere.setAnchorString("BUYER_"+buyerIdx);
    } else {
      signHere.setAnchorString("SUPPLIER_"+supplierIdx);
    }
    signHere.setAnchorXOffset("10");
    signHere.setAnchorYOffset("10");
    tabs.addSignHereTabsItem(signHere);
  }
  signer.setTabs(tabs);
  signerList.add(signer);
  if(signerInfo.getRole().equalsIgnoreCase("buyer")) {
    buyerIdx++;
  } else {
    supplierIdx++;
  }
}
Recipients recipients = new Recipients();
recipients.setSigners(signerList);
envDef.setRecipients(recipients);

try {
  String envelopeId = null;
  EnvelopesApi envelopesApi = null;

  // create a byte array that will hold our document bytes
  int documentId = 1;
  for(String documentFile : documentFiles) {
    byte[] fileBytes = null;
    try {
      // read file
      Path path = Paths.get(documentFile);
      fileBytes = Files.readAllBytes(path);
    } catch (IOException ioExcp) {
      // handle error
      System.out.println("Exception: " + ioExcp);
      return null;
    }

    // add a document to the envelope
    Document doc = new Document();
    String base64Doc = Base64.getEncoder().encodeToString(fileBytes);
    doc.setDocumentBase64(base64Doc);
    String fileName = new File(documentFile).getName();
    doc.setName(documentId+"_"+fileName);
    doc.setFileExtension(fileName.lastIndexOf('.') > 0 ? fileName.substring(fileName.lastIndexOf('.') + 1) : "");
    doc.setDocumentId("" + documentId++);

    envDef.addDocumentsItem(doc);

    if(envelopeId == null || envelopesApi == null) {
      // To save as a draft set to "created" (for test purpose I create and envelope with only one file)
      envDef.setStatus("created");
      envelopesApi = new EnvelopesApi();
      EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);
      envelopeId = envelopeSummary.getEnvelopeId();
    } else {
      // the files after the 1st are updated in the draft envelope
      envDef.setRecipients(recipients);
      List<Document> tmpDocumentList = new ArrayList<Document>();
      doc.setApplyAnchorTabs("true");
      tmpDocumentList.add(doc);
      envDef.setDocuments(tmpDocumentList);
      EnvelopeDocumentsResult envelopeDocumentsResult = envelopesApi.updateDocuments(accountId, envelopeId, envDef);
    }
  }
  Envelope envelope = envelopesApi.getEnvelope(accountId, envelopeId);
  envelope.setStatus("sent");
  envelope.setPurgeState(null);
  EnvelopesApi.UpdateOptions uo = envelopesApi. new UpdateOptions();
  uo.setAdvancedUpdate("true");
  EnvelopeUpdateSummary envelopeUpdateSummary = envelopesApi.update(accountId, envelopeId, envelope, uo);

  documentId = 1;
  for(String documentFile : documentFiles) {
    Tabs tabs = envelopesApi.getDocumentTabs(accountId, envelopeId, ""+documentId++);
    System.out.println("CARLO Tabs 3, documentId "+(documentId - 1)+": "+tabs);
  }

Thanks for your answer.
More details:
in the envelope we have more than one document;
the size of each document is less than 25MB;
the sum of the sizes of all the documents is more than 25MB.
We can upload documents in envelope with status "created", but when the status is changed to "sent" and the signer goes into the signature page then it is not required to sign these documents; it seem that the signHereTabs is not set in the documents added while envelope status is "created".
If after having set envelope status = "sent" we execute the following code
documentId = 1;
for(String documentFile : documentFiles) {
    Tabs tabs = envelopesApi.getDocumentTabs(accountId, envelopeId, ""+documentId++);
    System.out.println("Tabs: documentId "+(documentId - 1)+": "+tabs);
}

we obtain
Tabs: documentId 1: class Tabs {
    ...
    signHereTabs: [class SignHere {
        anchorCaseSensitive: null
        anchorHorizontalAlignment: null
        anchorIgnoreIfNotPresent: null
        anchorMatchWholeWord: null
        anchorString: BUYER_0
        anchorUnits: pixels
        anchorXOffset: 10
        anchorYOffset: -10
        conditionalParentLabel: null
        conditionalParentValue: null
        customTabId: null
        documentId: 1
        errorDetails: null
        mergeField: null
        name: SignHere
        optional: false
        pageNumber: 1
        recipientId: edb96dfd-9700-4328-ba45-825a1284b030
        scaleValue: 1.0
        stampType: signature
        stampTypeMetadata: null
        status: null
        tabId: e484087c-70c2-431c-9825-47605e1f44c2
        tabLabel: Sign Here
        tabOrder: null
        templateLocked: null
        templateRequired: null
        tooltip: null
        xPosition: 123
        yPosition: 297
    }]
    ...
}
Tabs: documentId 2: class Tabs {
    ...
    signHereTabs: []
    ...
}
where documentId 1 has been uploaded when the envelope has been created (status="created"), and documentId 2 has been uploaded in a second step (both documentId 1 and 2 contain the anchorString: BUYER_0).

A:

To add on to Amit's answer, every individual API request to DocuSign must be less than 25MB.
Since the default technique is to send Base64 encoded documents within a JSON object, the effective max total size for all of the documents sent in a single request is around 18MB.
You can avoid the Base64 overhead by sending the API request as a multi-part MIME message. This technique enable you to send the documents as binary objects. See the code example for scenario 10 in C# (also available for PHP, Java, Node.js, Python, and Ruby)
Additional
If each of your documents is less than 18 MB, then you can use the "regular" JSON object and Base64 encode one document at a time. If the sum of the document sizes is greater than 18MB then you must upload them one at a time:

Create the envelope, include one of the documents. The document status should be created so the envelope is not sent at this time.
Add more documents to the envelope, one at a time. You can use EnvelopeDocuments::updateList API method. You'd probably want query parameter apply_document_fields on.
Update the envelope status to sent using Envelopes::update

For adding tabs to the documents, you could define them at the beginning if you use anchor tab positioning. Or you could add the tabs to the envelope definition after you finish adding the documents to the envelope.


Q:

Hiding terminal output when chaining commands

From the terminal, I like launching my standard working applications ... gedit with my todo-list, firefox and chromium.
To save time, I (1) chain this command into one line, (2) silence all error messages from stderr and stdout with 2&>1 >/dev/null and (3) background the processes with & to regain a clean terminal:
gedit ~/Desktop/todo.txt 2&>1 > /dev/null & firefox 2&>1 > /dev/null & chromium-browser 2&>1 > /dev/null &

It seems to work fine except for one small detail.  Gedit opens the todo file as well as a new textfile with the name 2.  Are the pipes misplaced?

A:

I tend to see >/dev/null 2>&1 and not 2>&1 >/dev/null
Then > is probably key here since the next options for gedit is (a) filename(s).
Man page for gedit states for filename(s):

Specifies the file to open when gedit starts - if this is not specified, gedit will load a blank file with an Untitled label. Multiple files can be loaded if they are separated by spaces. gedit also supports handling of remote files. For example, you can pass the location of a webpage to gedit, like "http://www.gnome.org", or load a file from a FTP server, like "ftp://ftp.gnome.org/robots.txt".

If I read this correctly: the 2 is seen as a filename since a space preceeds it. That would suggest you need the > to tell gedit that it is not a filename that comes next.

I myself would create a script and have the commands on separate lines.


Q:

Calculate number of small cubes making up large cube given number in outermost layer

I have a large cube made up of many smaller cubes. Each face of the cube is identical, and all of the smaller cubes are identical. I need to calculate the number of small cubes that make up the large cube. Just to make it clear, the cube is solid (made up of little cubes all the way through).
The only value I have to work this out from is the number of small cubes that make up the outermost layer. This number is $100,614,152$.
What is the simplest way to calculate the total number of small cubes making up the large cube?

A:

Let the big cube be of dimension $(x+2)$ (made up of $(x+2)^3$ smaller cubes). Then $(x+2)^3-x^3=100,614,152$. This reduces to a quadratic equation which you can solve.

A:

Let $x$ be the number of small cubes along each edge of the large cube. Then each face of the large cube contains $x^2$ small cubes. $6x^2$ isn't the total number of cubes around the outside, though, because we're double-counting the cubes along each of the edges, so we need to subtract off $12x$. Then we aren't counting the cubes at the corners (we counted them three times--once in each face--and subtracted them three times), so we need to add back on 8. So we have
$$6x^2 -12x + 8 = 100,614,152.$$
Now this is just a simple quadratic. Combine the terms on one side and use the quadratic formula (or Wolfram Alpha) to find that $x = 4096$.


Q:

How to define symbols that will work like ( and ) by symbol macro?

I am trying define symbols a and b in following way
a + 1 1 b
2

I am trying to do this by using define-symbol-macro
(define-symbol-macro a '( )
(define-symbol-macro b ') )

but this way is not working.

A:

What Lisp does with source code
Common Lisp is an incredibly flexible language, in part because its source code can be easily represented using the same data structures that are used in the language.  The most common form of macro expansion transforms the these structures into other structures.  These are the kind of macros that you can define with define-symbol-macro, define-compiler-macro, defmacro, and macrolet.  Before any of those kind of macroexpansions can be performed, however, the system first needs to read the source from an input stream (typically a file, or an interactive prompt). That's the reader's responsibility.  The reader also is capable of executing some special actions when it encounters certain characters, such ( and '. What you're trying to do probably needs to be happening down at the reader level, if you want to have, e.g., (read-from-string "a + 1 1 b") return the list (+ 1 1), which is what you want if you want (eval (read-from-string "a + 1 1 b")) to return 2.  That said, you could also define a special custom language (like loop does) where a and b are treated specially.
Use set-macro-character, not define-symbol-macro
This isn't something that you would do using symbol-macros, but rather with macro characters.  You can set macro characters using the aptly named set-macro-character.   For instance, in the following, I set the macro character for % to be a function that reads a list, using read-delimited-list that should be terminated by ^.  (Using the characters a and b here will prove very difficult, because you won't be able to write things like (set-macro-character ...) afterwards;  it would be like writing (set-m(cro-ch(r(cter ...), which is not good.)
CL-USER> (set-macro-character #\% (lambda (stream ignore)
                                    (declare (ignore ignore))
                                    (read-delimited-list #\^ stream)))
T
CL-USER> % + 1 1 ^
2

The related set-syntax-from-char
There's a related function that almost does what you want here, set-syntax-from-char.  You can use it to make one character behave like another.  For instance, you can make % behave like (
CL-USER> (set-syntax-from-char #\% #\()
T
CL-USER> % + 1 1 )
2

However, since the macro character associated with ( isn't looking for a character that has the same syntax as ), but an actual ) character, you can't simply replace ) with ^ in the same way:
CL-USER> (set-syntax-from-char #\^ #\))
T
CL-USER> % + 1 1 ^
; Evaluation aborted on #<SB-INT:SIMPLE-READER-ERROR "unmatched close parenthesis" {1002C66031}>.

set-syntax-from-char is more useful when there's an existing character that, by itself does something that you want to imitate.  For instance, if you wanted to make ! an additional quotation character:
CL-USER> (set-syntax-from-char #\! #\')
T
CL-USER> (list !a !(1 2 3))
(A (1 2 3))

or make % be a comment character, like it is in LaTeX:
CL-USER> (set-syntax-from-char #\% #\;)
T
CL-USER> (list 1 2 % 3 4
               5 6)
(1 2 5 6)

But consider why you're doing this at all…
Now, even though you can do all of this, it seems like something that would be utterly surprising to anyone who ran into it.  (Perhaps you're entering an obfuscated coding competition? ;))  For the reasons shown above, doing this with commonly used characters such as a and b will also make it very difficult to write any more source code.  It's probably a better bet to define an entirely new readtable that does what you want, or even write a new parser. even though (Common) Lisp lets you redefine the language, there are still things that it probably makes sense to leave alone.

A:

A symbol-macro is a symbol that stands for another form. Seems like you want to look at reader macros.

http://clhs.lisp.se/Body/f_set__1.htm
http://dorophone.blogspot.no/2008/03/common-lisp-reader-macros-simple.html

I would second Rainer's comment though, what are you trying to make?


Q:

Teechart Mobile - Column3DStacked graph

I would like to create a graph that looks similar to the following:

However I can't find anything in TeeChart that would produce a similar result.
I have tried to create a Bar3D series and set it's MultiBar property to different values but the closest one that I found was MultiBars.None.
Any suggestions?

A:

Yes, this is possible with standard Bar series setting the MultiBar property to Stacked, for example:
  Steema.TeeChart.Themes.ExcelTheme excelTheme = new Steema.TeeChart.Themes.ExcelTheme(tChart1.Chart);
  excelTheme.Apply();

  tChart1.Aspect.View3D = true;
  tChart1.Axes.Bottom.Grid.Visible = false;

  tChart1.Legend.Pen.Visible = false;

  Steema.TeeChart.Styles.Bar bar1 = new Steema.TeeChart.Styles.Bar(tChart1.Chart);
  bar1.Marks.Visible = false;
  bar1.MultiBar = Steema.TeeChart.Styles.MultiBars.Stacked;
  bar1.BarWidthPercent = 50;
  bar1.Title = "Net personally receivable";

  Steema.TeeChart.Styles.Bar bar2 = new Steema.TeeChart.Styles.Bar(tChart1.Chart);
  bar2.Marks.Visible = false;
  bar2.MultiBar = Steema.TeeChart.Styles.MultiBars.Stacked;
  bar2.BarWidthPercent = 50;
  bar2.Title = "Tax and costs";

  Random rnd = new Random();

  bar1.Add(rnd.Next(), "Do Nothing");
  bar1.Add(rnd.Next(), "Bonus");
  bar1.Add(rnd.Next(), "Dividend");
  bar1.Add(rnd.Next(), "Interest");
  bar1.Add(rnd.Next(), "Alpha Index\nTrades");

  bar2.Add(rnd.Next(), "Do Nothing");
  bar2.Add(rnd.Next(), "Bonus");
  bar2.Add(rnd.Next(), "Dividend");
  bar2.Add(rnd.Next(), "Interest");
  bar2.Add(rnd.Next(), "Alpha Index\nTrades");

Produces this chart:


Q:

Dynamically create a link and open it in same iframe

I have a link that is being dynamically created with url params and all sort of good stuff in my javascript.
I am then obviously trying to open that page. I would like to open it within the same iframe, but anything I try keeps opening it in a new tab (can't do it this way because I loose all context and data).
I have tried
window.open(url, '#iframeId');
window.open(url);
window.open(url, '_top'); //This kind of worked, but overtook the whole window ignoring the iframe

Any ideas? Most of what I saw when I searched was coming from the html side and I don't have access to changing that.

A:

Fist you need to set your <iframe name="test"> name like this and
than use window.open('www.google.co.in', "test") this


Q:

Euclidean algorithm in Euclid's words

When describing the Euclidean algorithm in his book, Elements, Euclid says the following:

When the less of the numbers $a$ and $b$ is continually subtracted from the greater, some number is left which measures the one before it.

So when looking for a GCD of, say, $25$ and $15$, we can subtract $15$ from $25$ and get $10$. So $10$ is the number left which should measure(divide) the one before it. It measures neither $15$ nor $25$.
Can anyone interpret what Euclid wanted to say with that sentence?

A:

You're missing the word "continually".
In your example:
$(25,15) \to (10,15) \to (10,5)$ and now $5$ measures $10$ and we're done.
I guess the sentence could also use the addition of "eventually":

When the less of the numbers $a$ and $b$ is continually subtracted from the greater, eventually some number is left which measures the one before it.


Q:

How can i Integrate FullCalendar with Codeigniter

I am using Codeigniter. I am trying to integrate FullCalendar with my project. It is working. But, i am not able to save the events in database(mysql) using codeigniter. Is it possible to save selected events to database with date?

A:

yes, It's possible. you can put your AJAX call whenever a event create/updated/deleted with fullcalendar events and you can save the data into database. Checkout the below library which shows basic CRUD operations of FullCalendar with codeigniter.
https://github.com/eboominathan/Basic-Crud-in-Full-Calendar-Using-Codeigniter-3.0.3


Q:

How to list syntax and available tags for -Xlog

OpenJDK 9's new Unified JVM Logging can filter logs by tags, but the JEP does not provide a list of all available tags. How can I list all available arguments?

A:

java -Xlog:help prints the argument syntax, including the list of tags available in that particular version, which may change over time.
Note that logging with -Xlog:<tag> may not print everything related to that tag since it requires the log message to only have that tag. Use -Xlog:<tag>* instead to include messages containing multiple tags.


Q:

Django Internal Server Error instead of 404

I am using Django 1.6, uwsgi and nginx, the application works fine but I am getting 500 error and the email below for every invalid URL that I am trying to access, instead of a 404 error.
I get this for http://my_project_url.com/whatever or even for http://my_project_url.com/favicon.ico
I have looked over the URL's but there is no regex matching this pattern.
Here is the traceback from the email:
Traceback (most recent call last):

  File "/project/virtenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 152, in get_response
    response = callback(request, **param_dict)

  File "/project/virtenv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 99, in _wrapped_view
    response = view_func(request, *args, **kwargs)

  File "/project/virtenv/local/lib/python2.7/site-packages/django/views/defaults.py", line 30, in page_not_found
    body = template.render(RequestContext(request, {'request_path': request.path}))

  File "/project/virtenv/local/lib/python2.7/site-packages/debug_toolbar/panels/templates/panel.py", line 55, in _request_context__init__
    context = processor(request)

  File "./project/context_processors.py", line 88, in app_delegate
    app_name = resolve(request.path).app_name

  File "/project/virtenv/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 453, in resolve
    return get_resolver(urlconf).resolve(path)

  File "/project/virtenv/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 333, in resolve
    raise Resolver404({'tried': tried, 'path': new_path})

Resolver404: {u'path': u'favicon.ico', u'tried': [[<RegexURLResolver <module 'custom_

If I am trying to access an URL from the app where I do raise Http404 it's fine, I get the regular nginx error page.

A:

It seems you have a custom processor trying to resolve path:
File "./project/context_processors.py", line 88, in app_delegate
  app_name = resolve(request.path).app_name

Quoting django resolve() docs:

If the URL does not resolve, the function raises a Resolver404 exception (a subclass of Http404) .

I suggest to you to manage exception in custom processor code to look like this one:
try:
    resolve_result = resolve(request.path)
    app_name = resolve_result.app_name
    ... your code ....
except Resolver404:
    pass


Q:

pep8 compliance with long json dictionary lookup?

Using a character length of 79, how would someone formulate a command such as:
return method_returning_json()['LongFieldGroup1']['FieldGroup2']['FieldGroup3']['LongValue']

If I move the lookups to the next line, such as:
return method_returning_json()\
    ['FieldGroup1']['FieldGroup2']['FieldGroup3']['Value']

pep8 complains about "space before [" since there are several tabs. However, if I move the second/third/etc group to a newline it does the same thing.
I know I can add the # noqa tag to the end of the line but I am hoping there is a better way.

A:

Use implicit line continuation that occurs inside parentheses:
return (method_returning_json()
          ['LongFieldGroup1']
          ['FieldGroup2']
          ['FieldGroup3']
          ['LongValue'])

(You may need to adjust the actual indentation to make the pep8 tool happy.)
You can even use the indexing brackets themselves to allow implicit line continuation, although I don't really find any of the variations particularly readable.
# Legal, but probably not desirable.
# At the very least, pick one style and be consistent; don't
# use a variety of options like I show here.
return method_returning_json()[
         'LongFieldGroup1'][
         'FieldGroup2'][
         'FieldGroup3'
         ][
         'LongValue'
         ]


Q:

The Game vs The Game Engine?

I was wondering if somebody could tell me how the game and the game engine fit into game development. Specifically what I mean is, the game engine does not actually have a game. So where I'm unclear about is basically, do game developpers build an engine, then create a new class that inherits from engine which becomes the game?
Ex:
class ShooterGame : public Engine
{
};

So basically i'm unclear on where the game code fits into the engine.

A:

The distinction between the game and the actual game engine is architectural. The game logic is specific for one game whereas the game engine is something that can be reused. Much like an operating system provides utilities for applications the game engine does the same for the game code.
Game engines will typically have different APIs for:

Loading multimedia data like audio, textures, 3d models
Providing a game loop and firing off various events caused by the users input
Networking
Graphics rendering and various techniques to make the game look nice using lighting, particle effects or bump mapping
Audio
Artificial Intelligence
An API to allow for defining game rules, game play, and game logic

Most game developers do not write their own game engine. It would be too much work. Instead they'll reuse a game engine their company has or license one. For first person shooters, id Software, and Unreal are two popular choices.
Once they have the engine they have to start writing code to make their game. This is done using the API provided by the game engine. For example Valve makes developers use C++. If you wanted a monster you would extend off of the Entity class and define how this monster behaves in that base class.
I would recommend reading through the documentation and tutorials provided by the various game engine providers. Keep in mind some games are classified as "mods" and some as "total conversions." Typically, a mod does not change the engine of the game and the total conversion may add or remove significant features to a game engine.
Here are a few sources I would recommend:

http://developer.valvesoftware.com/wiki/SDK_Docs
http://udk.com
id Software releases their game engines as GPL after a few years. Reading through their code you'll learn a lot: ftp://ftp.idsoftware.com/idstuff/source/quake3-1.32b-source.zip. I would also recommend taking a look at Enemy Territory which was a based of quake 3 code: ftp://ftp.idsoftware.com/idstuff/source/ET-GPL.zip.

A:

Actually, I can not tell the difference between engine and framework. It's just two different names.
What really odd is that game engine is all about client side,  it seems like you do not need a  server framework, whereas pure socket is enough for it.
But the reality is not like this, at least, there should be some framework like rails or django to ease your server development. Not to see game server is harder than web development in scalability, broadcast and other areas.
There is a commercial solution called smartfox server, and a new open source solution called pomelo framework, I've tried both, pomelo is much better.  pomelo.netease.com  is its home.


Q:

Set a treeview to specific location

I have a folder in my C: drive that I want to access as soon as my form loads. I don't want to scroll through opening each node everytime. I'm wanting to use a treeview as I know how to use a lot of the features in these and it will suit my purpose.
I shall give you an example of what i am wanting using a basic file structure:
C:\Users\user\Documents\Visual Studio 2010\Projects
This would take me a number of nodes to gain access to if I was to to it through the entire treeview. I want my treeview to to start with, so the main node to be
Projects
How would I go about doing this?

A:

I am sure that the answer above would work. However i managed to sort it out by doing:
        Dim backupfolder As String = netpath & "\MANUFPC BACKUP PROCESS\" & site & "\" & factory & "\" & line & "\" & pc

        Dim mRootNode As New TreeNode
        mRootNode.Text = pc
        mRootNode.Tag = backupfolder
        mRootNode.Nodes.Add("*DUMMY*")
        'adds plus icon to allow extension
        backupFolderDirectory.Nodes.Add(mRootNode)

then the two other functions:
Private Sub TreeView1_BeforeCollapse(ByVal sender As Object, ByVal e As TreeViewCancelEventArgs) Handles backupFolderDirectory.BeforeCollapse
    ' clear the node that is being collapsed
    e.Node.Nodes.Clear()
    ' add a dummy TreeNode to the node being collapsed so it is expandable
    e.Node.Nodes.Add("*DUMMY*")
End Sub

Private Sub TreeView1_BeforeExpand(ByVal sender As Object, ByVal e As TreeViewCancelEventArgs) Handles backupFolderDirectory.BeforeExpand
    ' clear the expanding node so we can re-populate it, or else we end up with duplicate nodes
    e.Node.Nodes.Clear()

    ' get the directory representing this node
    Dim mNodeDirectory As DirectoryInfo
    mNodeDirectory = New DirectoryInfo(e.Node.Tag.ToString)
    ' add each subdirectory from the file system to the expanding node as a child node
    Try
        For Each mDirectory As DirectoryInfo In mNodeDirectory.GetDirectories
            ' declare a child TreeNode for the next subdirectory
            Dim mDirectoryNode As New TreeNode
            Dim mystring(1) As String
            mystring(0) = mDirectory.FullName
            mystring(1) = "directory"
            ' store the full path to this directory in the child TreeNode's Tag property
            mDirectoryNode.Tag = mystring(0)
            ' set the child TreeNodes's display text
            mDirectoryNode.Text = mDirectory.Name
            ' add a dummy TreeNode to this child TreeNode to make it expandable
            mDirectoryNode.Nodes.Add("*DUMMY*")
            ' add this child TreeNode to the expanding TreeNode
            e.Node.Nodes.Add(mDirectoryNode)
        Next

        For Each mFiles As FileInfo In mNodeDirectory.GetFiles
            ' declare a child TreeNode for the next subdirectory
            Dim mFileNode As New TreeNode
            Dim mystring(1) As String
            mystring(0) = mFiles.FullName
            mystring(1) = "file"
            ' store the full path to this directory in the child TreeNode's Tag property
            mFileNode.Tag = mystring(0)
            ' set the child TreeNodes's display text
            mFileNode.Text = mFiles.Name
            ' add this child TreeNode to the expanding TreeNode
            e.Node.Nodes.Add(mFileNode)
        Next

    Catch ex As IOException
        'sets up 2 different exceptions then the last one catches other exceptions that could be made from adding folder/files etc
        e.Node.Remove()
        MsgBox("Device/Folder not accessible", MsgBoxStyle.OkOnly, "Device not Ready")
    Catch exc As NullReferenceException
        e.Node.Remove()
        MsgBox("Sorry this File/Folder can not be added", MsgBoxStyle.OkOnly, "Sorry")
    Catch exce As Exception
        e.Node.Remove()
        MsgBox("Device/Folder not accessible", MsgBoxStyle.OkOnly, "Device not Ready")
    End Try
End Sub


Q:

Dynamic 301 Redirect

We made a mistake in the scope of our dynamic pages on a new site, and have some incorrect pages already spidered in Google.
I need to redirect the following format:
http://www.domain.com/dir/dir/?q=120
To this format:
http://www.domain.com/dir/dir/?p=120
Only difference is the 'q' needs to be a 'p'.
RewriteEngine is on, as I've already consolidated traffic from domain.com to www.domain.com
This is what I have in my root .htaccess file:
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^centerline.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]
RewriteRule ^(/leadership/detail/)\?q=([0-9]+)$    $1?p=$2 [R=301, L]

A:

Try this:
RewriteCond %{QUERY_STRING} q=([0-9]+)$
RewriteRule ^(.*)$ /$1?p=%1 [L,R=301]

You'll need the RewriteCond as apache doesn't allow matching against the querystring in a RewriteRule
EDIT
RewriteCond %{REQUEST_URI} ^/leadership/detail/$
RewriteCond %{QUERY_STRING} q=([0-9]+)$
RewriteRule ^(.*)$ /$1?p=%1 [L,R=301]


Q:

SQL Query, Where Not Exist doesn't work

I wrote following Query to see if a row exist or not, and If Row not exist then update else do nothing.
My Code:s
UPDATE [Computer] SET [ComputerTag] = @ComputerTag, [CustID] = @CustID,
[PcModel] = @PcModel, [ServicetagNo] = @ServicetagNo,
WHERE [ComputerID] = @ComputerID
AND NOT EXIST ( SELECT [ComputerTag] FROM [Computer]
WHERE [ComputerTag] = @ComputerTag)

But it shows error "Error in list of function arguments: 'SELECT' not recognized.
Error in list of function arguments: 'EXIST' not recognized". How can I fix this?
Update:
Thanx for your answers, But now it shows different kind of error "The Compound statement SQL construct or statement is not supported". Why is that?

A:

You have an extra comma in the query after @ServicetagNo.


Q:

USB for embedded devices - designing a device driver/protocol stack

I have been tasked to write a device driver for an embedded device which will communicate with the micro controller via the SPI interface. Eventually, the USB interface will be used to download updated code externally and used during the verification phase.
My question is, does anyone know of a good reference design or documentation or online tutorial which covers the implementation/design of the USB protocol stack/device driver within an embedded system? I am just starting out and reading through the 650 page USB v2.0 spec is a little daunting at the moment.
Just as a FYI, the micro controller that I am using is a Freescale 9S12.
Mark
Based upon goldenmean's (-AD) comments I wanted to add the following info:
1) The embedded device uses a custom executive and makes no use of a COTS or RTOS.
2) The device will use interrupts to indicate data is ready to be retrieved from the device.
3) I have read through some of the docs regarding Linux, but since I am not at all familiar with Linux it isn't very helpful at the moment (though I am hoping it will be very quickly).
4) The design approach, for now at least, it to write a device driver for the USB device then a USB protocol layer (I/O) would reside on top of the device driver to interpret the data. I would assume this would be the best approach, though I could be wrong.
Edit - A year later
I just wanted to share a few items before they vanish from my mind in case I never work on a USB device again.  I ran into a few obstacles when developing code and getting it up and running for the first.
The first problem I ran into was that when the USB device was connected to the Host (Windows in my case) was the host issues a Reset request.  The USB device would reset and clear the interrupt enable flags.  I didn't read the literature enough to know this was happening, thus I was never receiving the Set-Up Request Interrupt.  It took me quite a while to figure this out.
The second problem I ran into was not handling the Set-Up Request for Set_Configuration properly.  I was handling it, but I was not processing the request correctly in that the USB device was not sending an ACK when this Set-Up Request came in.  I eventually found this out by using a hardware USB protocol analyzer.
There were other issues that I ran into, but these were the two biggest ones that took me quite a while to figure out.  The other issue I had to worry about is big-endian and little-endian, Freescale 9S12 vs USB data format (Intel), respectively.
I ended up building the USB device driver similar to UART device drivers I had done in the past. I have posted the code to this at the following URL.
http://lordhog.wordpress.com/2010/12/13/usb-drive
I tend to use structures a lot, so people may not like them since they are not as portal as using #defines (e.g., MAX3420_SETUP_DATA_AVAIL_INT_REQR 0x20), but I like them since it makes the code more readable for me.  If anyone has questions regarding it please feel free to e-mail and I can try to give some insight to it.  The book "USB Complete: The Developer's Guide" was helpful, so long as you knew what areas to concentrate on.  This was a simple application and only used low-speed USB.

A:

While writing a device driver for any interface (USB, Parallel port, etc...) the code needed to be developed would depend upon whether there is any Operating System(OS), RTOS running on that Processor/Micro controller.
  e.g. if thats going to run say WinCE - It will have its own Driver development Kit , and steps to be followed in the device driver development. Same for any other OS like Linux, symbian.
If its going to be a plain firmware code(No OS) which is going to control the processor/microcontroller, then it's a different situation altogether.
So based on either of the above situation u are in, one needs to read & understand:-
1.) The Hardware Specification of the processor/micro controller development board - Register files, ports, memory layout, etc.
2.) USB spec
3.) Couple of pointers i found quickly. Google shud be ur friend!
http://www.lrr.in.tum.de/Par/arch/usb/usbdoc/ - Linux USB device driver
http://www.microsoft.com/technet/archive/wce/support/usbce.mspx
-AD

A:

I've used an earlier edition of USB Complete by Jan Axelson. Indeed very complete.
From the editorial review:

Now in its fourth edition, this developer's guide to the Universal Serial Bus (USB) interface covers all aspects of project development, such as hardware design, device firmware, and host application software.


Q:

Formula for max volume of rectangular bag

I'd like a formula for a bag made of two flat equal sized rectangles (e.g. a freezer bag). Assume no stretching, and perfect flexibility. Volume in terms of a and b, the dimensions of the bag when flat.
Thanks

A:

I think this problem is difficult.  It certainly is difficult if you started with two congruent disks rather than two congruent rectangles.  The disks problem is sometimes known as the Mylar Balloon problem.  See, e.g., "The Mylar Balloon Revisited," 2003, Amer. Math. Monthly (JSTOR link).
See also Igor Pak's 2006 paper, "Inflating polyhedral surfaces" (CiteSeer link).


Q:

Does an upgrade to a partition format get applied to an already existing partition?

I have often wondered, when an update is made to ext4 for example in the kernel and then more performance updates are made to it (And they keep up adding up over time) when i upgrade to the latest Ubuntu version, do they get applied to an already internal hard drive that is using ext4 already since 10.04.
I have 2 hard drives with ext4 which i formatted a year ago. Do this performance or fixes in the kernel need a reformat to the hard drives or do the ext4 partitions need nothing more than just to connect to the new kernel.
What is the actual difference between formatting in an old Ubuntu version using an old ext4 version versus formatting a new hard drive with a new shiny Ubuntu.
Am using ext4 as an example but any other partition format applies that has received updates with the release of newer kernel versions.

A:

Normally these changes happen "transparently". Your filesystem on-disk remains mostly the same (unless there have been changes to the on-disk structure, which is rare), but the real change is what happens in the kernel (software level).
In essence, you don't need to reformat or anything, the changes will be carried onward. The only instance I can think of that requires physical change is when their is a new feature added, such as lets saw for example, Copy On Write support for a file system that doesn't have it normally. In such a case, the only change usually needed is to add a mount option to the FSTAB file.


Q:

How to customize angular ui-grid row background color?

I am trying to change background color of angular ui-grid row based on condition so if riskValue is 1 trying to make it red and if value is 2 row background color should be Yellow. Any easy way to achieve this task ?
config.js
"columnDefs": [{
        "name": "Ticket Number",
        "field": "ticketNum",
        "width": 120
    },
    {
        "name": "Asset Id ",
        "field": "assetID",
        "width": 100
    },
    {
        "name": "Severity",
        "field": "severity",
        "width": 100
    },
    {
        "name": "Risk Index",
        "field": "riskIndex",
        "width": 100
    },
    {
        "name": "Risk Val",
        "field": "riskValue",
        "cellTemplate": "

{{row.entity.riskValue}}

",
        "sort": {
            "direction": "aesc",
            "priority": 0
        },
        "width": 100,
        "visible": false
    }
],

A:

You can use gridOptions.cellClass
cellClass: function(grid, row, col, rowRenderIndex, colRenderIndex) {
    if (row.entity.riskValue === 1)
        return 'red';
    if (row.entity.riskValue === 2)
        return 'yellow';
}

where red and yellow are css classes.
This method requires adding the function to all of your columnDefs but allows to choose only some columns, which should have changed background color.
Sample: http://plnkr.co/edit/Xie68a3sT9CXTdCuI3tq?p=preview


Q:

Angular: how to switch routes based on function calls

I have three routes in my app.js but when i am switching from create to any other route i want to check whether the user has intentionally click to switch or is it a mistake so there will be return popup that will ask user to stay on the page or leave the page. In usual cases it would have worked with this code:
window.onbeforeunload = confirmExit;
function confirmExit() {
    return "You have attempted to leave this page. Are you sure?";
}

but since this is a SPA application i have to run this function while switching the routes:
HERE IS MY ROUTES
testApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/tests', {
        templateUrl: 'partials/list.html',
        controller: 'ListCtrl'
      }).
      when('/tests/:testsId', {
        templateUrl: 'partials/detail.html',
        controller: 'DetailCtrl'
      }).
      when('/create/', {
        templateUrl: 'partials/create.html',
        controller: 'CreateCtrl'
      }).
      otherwise({
        redirectTo: '/tests'
      });
  }]);

any help is much appreciated.

A:

I would to this with an angular directive :
.directive('confirm', [
    function() {
        return {
            restrict: 'AEC',
            link: function($scope, element) {
                element.bind('click', function(event) {

                        if (!confirm('You have attempted to leave this page. Are you sure?')) {
                            event.preventDefault();
                            return false;
                        }
                });
            }
        };
    }
]);

and in your HTML :
link

This way the standard link redirection will get intercepted and the redirection will only occur if user confirm it.
Working fiddle : http://jsfiddle.net/HB7LU/3119/
edit: removed jquery reference + jsfiddle link
edit2: for global redirection interception (like a backspace key or any clicked link on the page), see this fiddle http://jsfiddle.net/9MnE9/124/
Here, I use $routeChangeStart to watch any location change.


Q:

How to set path in bitbake append file?

I am updating a device tree in Beagle Bone Black to enable i2c configuration. I have created a new layer meta-test. In meta-test there is a recipes-kernel where I have a leds.cfg and am335x-boneblack.dts file with linux-yocto_%.bbappend file. The bbappend file looks like this:
FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}:"

PACKAGE_ARCH = "${MACHINE_ARCH}"

SRC_URI += "\
file://am335x-boneblack.dts \
file://leds.cfg \
"

After building the kernel with bitbake both the files are transferred to "build/tmp/work/beaglebone_yocto-poky-linux-gnueabi/linux-yocto/4.18.25+git**" directory
But I want the dts file to get transfer to another directory "build/tmp/work-shared/beaglebone-yocto/kernel-source/arch/arm/boot/dts
"
How do I achieve this within the bbappend file?

A:

I was able to solve it adding this line:
do_configure_append() {
    cp ${WORKDIR}/am335x-boneblack.dts ${S}/arch/arm/boot/dts/
}


Q:

Select badges from table only if all requirements rows exist

I got three tables.
I want to query the badges table to get the badge if all the missions exists for the badge_id in the badge_requirements table.
In the case below, the badge would be returned because for badge_id = 1, all missions exist.
But if, for example, one record in the finished_missions table would not exist, then no badge would be returned.
The user_id will be supplied from the application.
table badges
+----+------+-------+
| id | name | image |
+----+------+-------+
| 1  | OHYE | path  |
+----+------+-------+
PK(id)

table badge_requirements
+------------+----------+
| mission_id | badge_id |
+------------+----------+
| 3          | 1        |
+------------+----------+
| 5          | 1        |
+------------+----------+
UNIQUE(mission_id, badge_id)
FK(mission_id, missions.id)
FK(badge_id, badges.id)

table finished_missions
+----+---------+------------+
| id | user_id | mission_id |
+----+---------+------------+
| 3  | 221     | 3          | // if any of these record doesn't exist
+----+---------+------------+
| 5  | 221     | 5          | // the badge associated with this mission would not be returned
+----+---------+------------+
PK(id)
FK(user_id, users.id)
FK(mission_id, missions.id)

EDIT
Changed the missions table to finished_missions for better readability.
The user id and mission id are just referencing the user and mission table.
EDIT 2
I've tried this, given from an answer:
SELECT * FROM badges b
INNER JOIN finished_missions fm ON (fm.user_id = 221)
INNER JOIN badge_requirements br ON (br.mission_id = fm.mission_id AND br.badge_id = b.id)

But it still returns the badge even if I have just one record in finished_missions table.

A:

There are many ways. This should be one:
SELECT badge_id
FROM  (  -- count missions per badge for the given user
   SELECT br.badge_id, count(*) AS ct
   FROM   finished_missions fm
   JOIN   badge_requirements br USING (mission_id)
   WHERE  fm.user_id = 221
   GROUP  BY  1
   ) u  -- count missions per badge total
JOIN (
   SELECT br.badge_id, count(*) AS ct
   FROM   badge_requirements
   ) b USING (badge_id, ct)  -- only badges with the full count of missions

In addition to the constraints you declared there should also be a, UNIQUE(user, mission_id) on finished_missions to disallow duplicate entries. Or you have to use count(DISTINCT mission_id) AS ct in the first subquery, so you can rely on the count.
And UNIQUE(mission_id, badge_id) should really be the PK  - or add a NOT NULL constraint for both columns.


Q:

Scala: Import scala.io.StdIn.readLIne -- error importing

I am getting an error if I import readline, as follows:
import scala.io.StdIn.{readline, readInt} =>
error: value readline is not a member of object scala.io.StdIn
import scala.io.StdIn.{readline, readInt}

Scala code runner version 2.12.1

If I don't import this, I get a deprecated message:
warning: there was one deprecation warning (since 2.11.0); re-run with -deprecation for details
one warning found

I get no errors if I use the fill path to the function:
var x = scala.io.StdIn.readLine.toInt

Let me know if you can help me resolve the import.  Thanks.

A:

A very tiny overlook:
import scala.io.StdIn.{readLine, readInt}

readLine has an upper case L


Q:

Removing anonymous event handlers with some parameters

I subscribe to an event like this:
private void CoupleOverlay(IMapVisual mapVisual)
{
      overlay.DrawTilesProgressChanged += (s, e) =>
      {
          mapVisual.DrawingProgress = e.ProgressPercentage;
      };
}

The application may call CoupleOverlay event many times so I need to unsubscribe DrawTilesProgressChanged event and subscribe again but because it is an anonymous event I can't unsubscribe from it. I tried to convert to
private void CoupleOverlay(IMapVisual mapVisual)
{
    overlay.DrawTilesProgressChanged -=overlay_DrawTilesProgressChanged;
    overlay.DrawTilesProgressChanged +=overlay_DrawTilesProgressChanged;
}

private void overlay_DrawTilesProgressChanged(object sender, DrawTilesProgressChangedTileOverlayEventArgs e)
{
    mapVisual.DrawingProgress = e.ProgressPercentage;
}

It is not working because mapVisual is not valid variable on overlay_DrawTilesProgressChanged method.
If I change the code to
private void CoupleOverlay(IMapVisual mapVisual)
{
    EventHandler<DrawTilesProgressChangedTileOverlayEventArgs> drawEvent = (s, e) =>
    {
        mapVisual.DrawingProgress = e.ProgressPercentage;
    };

    overlay.DrawTilesProgressChanged -= drawEvent;
    overlay.DrawTilesProgressChanged += drawEvent;
}

It will not work cause drawEvent is a local variable and next time I call CoupleOverlay, it will create new one.
So How can I unsubscribe from this event handler? Or how can I know I'm subscribed to the event so I don't need to subscribe again?

A:

it will not work cause drawEvent is local variable and next time I call CoupleOverlay, it will create new one.

Indeed. You'd basically need to keep an instance variable instead of a local variable. The instance variable would effectively be "the currently subscribed event handler". Then in CoupleOverlay you'd remove that event handler, create a new one (storing it in the variable) and resubscribing with it.
An alternative would be to use a single event handler, but keep the "current" overlay and map visual as instance variables, used by the event handler. The CoupleOverlay method would then just need to update those variables.


Q:

Brexit Amendments

Recently, in the news, there has been much talk of Brexit votes. In particular, the votes of the House of Commons on specific amendments, like amendments in which the Commons supports the PM's deal, or votes on a no deal, or to extend the exit date. All of these amendments are spoken of in the same context. But what Bill are these amendments actually amending?

A:

what Bill are these amendments actually amending?

None.
They are amendments to a government motion for debate.
For example this motion:

That this House declines to approve leaving the European Union without a Withdrawal Agreement and a Framework for the Future Relationship on 29 March 2019; and notes that leaving without a deal remains the default in UK and EU law unless this House and the EU ratify an agreement.

On which MPs will each vote aye or nay at 7 p.m. today 13th March 2019.


Q:

PC XNA Game converted to Xbox 360 - Huge Performance Issues

So I wanted to convert my PC game to work on the Xbox 360.  It ran damn fine on the PC, with a Intel Core 2 Quad @ 2.40Ghz and a Radeon 4850 512MB.
I ported it to the Xbox, and right off the bat, there was some problem with invariance and inheritance regarding importing of lists, so I simply used the LINQ method called .Cast<>().
If that method is takes a big overhead, let me know, because I cannot deploy Performance Analysis on the 360 for some reason, most likely because it plays on the 360.
Then another problem came, and it was a nice System.OutOfMemoryException.  My skybox textures were 4096x4096, so reducing them by half removed that error.  Odd though, they were only 3MB x 6, so it shouldn't be using that much of the 512MB available.
So when all those problems were cleared out of the way, a nice 1 frame per 2 seconds were introduced.  It then crashes after 1 minute of gameplay, a "Code 4" whatever that means.
It plays like a powerpoint.  Here are some performance analysis images from PC gameplay.  They are not bad.
CPU: http://i.imgur.com/JYx7Z.png
RAM: http://i.imgur.com/C29KN.png  And 72% = 150MB mind you.
I hope anyone here has some experience on this issue. Frankly I am all ears.

A:

The root cause of your performance problems is almost certainly because you're allocating memory while your game is running (after startup, during the Draw/Update loop).
On Windows this is fine. The garbage collector on Windows is generational (will only clean up new objects when possible) and extremely fast. It is clever about when it chooses to run, too.
The garbage collector on the Xbox 360, on the other hand, is completely rubbish. It runs for every 1MB of memory allocated. It checks the entire managed heap when it runs. And it's quite slow to boot.
So the answer is to never allocate memory while your game is in its running state.
There's a good blog post about this here. (It also describes the alternative to never allocating memory - which is to reduce heap complexity - which is really very difficult to implement and I don't recommend it.)

You will have to remove things like LINQ, as the query objects it creates are heap objects, as are the delegates it frequently requires. Use simple loops instead.
If you are allocating your own reference types in draw/update, you will have to convert to using value types where possible or add object pooling.
Creating string objects is another common source of memory allocations - instead you can re-use a StringBuilder and render that directly.
Converting things (especially: numbers) to strings, even for StringBuilder will allocate memory. You need to write/find allocation-free alternatives. My answer to this similar question has one for int.

The best way to diagnose where you are allocating memory is to run your game with the CLR Profiler on Windows. This will tell you where and when memory is being allocated. Simply optimise until you're not allocating.
(Or until you're reliably allocating less than 1MB per level/map/room/whatever, and do a manual GC during a time where it's appropriate to stutter - like a static loading screen or a fade-to-black.)
Code 4 is an Unhandled Exception. You need to install a top-level exception handler that outputs a message, or run your game in the debugger, to determine the cause.
Finally: That is probably the compressed size of your textures (using PNG or JPEG or similar). If your textures are uncompressed, 4096 × 4096 × 6 × 4 bytes = 384MB. This is huge - no wonder you ran out of memory. You could compress them with DXT1 and make them 6 times smaller (instructions, wiki). You could also reduce their resolution. And do you need the bottom face at all?


Q:

Php Single page form processing issue

(Sorry for my bad english)
Well, I've 3 errors in my code.
Error's:

First of all it's show : Notice: Undefined index: form in C:\xampp\htdocs\evantechbd\index.php on line 461. When i run this form.
if any error found it's show error message, well, but correct field is empty. Example: In this form there is 4 fields. a) upload image, b) select discussion c) subject and d) message. Suppose you upload a image, select a discussion and write a subject but forgot to write message. Then It's show "Message Required" and every filed is empty. I don't want empty field which is correct.
After successfully submitted the form it's show "Discussion was submitted ". But after that if i refresh the page it's send the data to database. But I did not click submit button. why this happen?

Here is my code:
<?php
if ($_POST['form'] == "Submit") {
    $err       = array();
    $filed     = addslashes($_FILES['file']['tmp_name']);
    $img_named = addslashes($_FILES['file']['name']);
    $img_type  = addslashes($_FILES['file']['type']);
    @$imgd = addslashes(file_get_contents($_FILES['file']['tmp_name']));

    function getExtension($str)
    {
        $i = strrpos($str, ".");
        if (!$i) {
            return "";
        }
        $l   = strlen($str) - $i;
        $ext = substr($str, $i + 1, $l);
        return $ext;
    }
    $extension        = getExtension($img_named);
    $extension        = strtolower($extension);
    $image_named_uniq = uniqid() . '.' . $extension;
    $upload_path_dis  = 'user/manage/discussionimg/';

    $diss = $_POST['type'];
    $sub  = $_POST['sub'];
    $msg  = $_POST['msg'];
    $date = "On " . date("F Y h:i:s A");

    if (!isset($_SESSION['uname']))
        $err[] = "You need to login";

    else {
        $uname = $_SESSION['uname']; //session username

        if (empty($sub) && empty($msg) && empty($filed))
            $err[] = "All field required";
        else {
            if (empty($sub))
                $err[] = "Subject Requried";

            if (empty($msg))
                $err[] = "Message Requried";

            if (empty($filed))
                $err[] = "SORRY, you have to be upload a image";
        }
    }

    if (!empty($err)) {
        foreach ($err as $er) {
            echo "$er
";
        }
    }

    else {
        $sql = mysql_query("INSERT INTO discussion VALUES ('', '$imgd', '$image_named_uniq',
'$diss', '$sub', '$msg', '$uname', '$date' ) ");
        if (!$sql)
            echo "Can't submit your discussion" . mysql_error();

        if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_path_dis . $image_named_uniq)) {
            die('File Not Uploading');
        } else {
            echo "Discussion was submitted";
        }
    }
}
?>

Many Thanks for your help!!
Kanta.

A:

Try changing your first if condition as follows
if (isset($_POST['submit']))
Now most of web sites uses client side validations using javascript. You can use jquery frame work to make things easier. However since you already uses validations after the POST event. You have to set values to relevant fields as bellow code. It will set tha value of the subject.
<input type="text" name="sub" value="<?php if(isset($_POST["sub"]))  echo $_POST["sub"];  ?>" size="46"/>
Yes if you refresh the code it will again do the post and insert.  You have to do few controls. However these things depend on your data.

a. Make unique key indexes in the database
b. Check for existing record before the insertion.
c. Redirect your page to the same page after few seconds once the user see the successful message.


Q:

Can anyone suggest tricks for targeting specific units in a big army?

Often the engagement of 2 big armies is just a mass of graphics.  Sometimes though you know something is coming.  Like a Ghost with an EMP, or a High Templar with Psionic Storm, etc.  In these engagements you'd obviously want to do what you can to kill these units before they get a chance to do their damage.  Any suggestions?

A:

Try adjusting your video settings;  Different features stand out more or less when you adjust things like texture resolution and effects quality.  A good way to experiment is to open a replay with an engagement similar to what you're describing, watching the engagement; making an adjustment to your settings and watching the engagement again.  Do this until you find a balance you are pleased with.
In my own experience, on my own machine, lowering the effects qualtiy tends to make cloaked units more visible, but at the cost of making  burrowed units less visible.


Q:

Determine if a function is increasing/decreasing at a particular point

I'm getting better at using trig functions, but this problem has me up against a wall.
As I understand it, to find if a function is increasing or decreasing over a given interval, select a number inside that interval and if the result is greater or less than zero, the interval is increasing and decreasing, respectively.
Given $f(x)=5x+10 \sin x$ on the interval $(0, 2\pi)$, find the open intervals where the function is increasing or decreasing.
The given intervals are $(0, \frac{2\pi}{3}), (\frac{2\pi}{3}, \frac{4\pi}{3}), (\frac{4\pi}{3}, 2\pi).$
On the first interval, I selected $\frac{\pi}{2}$ as the test for x.  Thus $$f(x)= 5x+10 \sin x \Rightarrow 5(\frac{\pi}{2}) + 10 \sin(\frac{\pi}{2})\Rightarrow \frac{5\pi}{2}+10$$
$\frac{5\pi}{2}+10 > 0$, so the function should be increasing at that point
The second interval test variable was $\pi$, and thus $5(\pi)+10 \sin(\pi)= 5\pi > 0$ So the interval of $(\frac{2\pi}{3}, \frac{4\pi}{3})$ should be increasing.
The third interval test variable was $\frac{3\pi}{2}$, and $5(\frac{3\pi}{2})+10 \sin(\frac{3\pi}{2})= \frac{15\pi}{2}-10 > 0$, so that interval is increasing as well.
However, the WebAssign site didn't accept those answers.  What is missing with my logic and work?

A:

You are nearly on the right track but are missing a key ingredient.
In calculus we learn that if the DERIVATIVE of a function is positive on an interval, then the function is increasing on that interval.  If the DERIVATIVE of a function is negative on an interval, then the function is decreasing on that interval.  So, you should first take the derivative to get $f'(x) = 5 + 10\cos x$ and then plug in values to the derivative (not the original function).  That is, $f'(\pi/2) = 5 > 0$ so $f$ is increasing on $(0, 2\pi/3)$.  $f'(\pi) = -5 < 0$, so $f$ is decreasing on the interval $(2\pi/3,4\pi/3)$.  $f'(3\pi/2) = 5 > 0$, so $f$ is increasing on the third interval.
Now, there is also another missing step, which is to find the correct intervals to use.  It seems as if you are given these intervals in the problem.  If they were not given, or if you want to ensure you were given the correct intervals, you find where the derivative is 0 or undefined.


Q:

Rethinkdb replace with getAll

I have a table with users, each row looks like this:
{
  id: <user's id>,
  email: <user's email>
}

Where id is the primary key and there's a secondary index for email.
I want to add a user only if no other use with the same email exists. Normally I would use two queries for this: getAll(<user's email>, {index: 'email'}) to make sure the email is not taken, followed by insert({email: <user's email>} but these are two separate queries (i.e. not an atomic operation).
Is there a way to check-and-set atomically using getAll?
Note: I know it's possible to do it with get as shown here but that doesn't work with getAll

A:

You can't do atomic operations on secondary indexes, unfortunately.  The best thing to do would probably be to add another emails table where the primary key is the email address.


Q:

Fit Squares of x area in rectangular area of m*n

I am looking for a formula to fit squares of fix area (say $a$) into a given area of $M$ x $N$
I have some data with me for instance say $a = 324$

20 squares fit an area of $120^2$
42 squares fit an area of $150^2$

What will be the formula to fit $a = 324$ squares in $M$x$N$

A:

Your data makes zero sense, so I shall ignore it.

What will be the formula to fit [area] a=324 squares in MxN

You can fit
$$\left\lfloor\frac{M}{x}\right\rfloor\left\lfloor\frac{N}{x}\right\rfloor$$
squares of size $x$ by $x$ into a rectangle of size $M$ by $N$, where $\lfloor\rfloor$ denotes the floor operation (rounding down), and the squares are aligned to the rectangle (not rotated).
If the area of the square is $a$, then $x = \sqrt{a}$. Therefore, the number $n$ of squares of area $a$ that fit, aligned (without rotating), within a rectangle of size $M$ by $N$, is
$$n = \left\lfloor\frac{M}{\sqrt{a}}\right\rfloor\left\lfloor\frac{N}{\sqrt{a}}\right\rfloor$$


Q:

How to enable my bugfix extension to run in a specific Magento 2 version?

I'm creating a module in order to fix a bug in Magento 2.3.0 that will be part of the next release. So, I would like to restrict via Composer the dependencies of that module.
How can I restrict my module to run just with the Magento 2.3.0?

A:

You can check the Magento 2 version and run it when it's the version that you want, if not you can add a log warning to show a message like this example:
if($this->helper->getVersion() !== self::MAGENTO_COMPATIBLE_VERSION){
    $this->logger->emergency('You are using a updated Magento version ' . Data::AMASTY_MODULE_NAME .'. Please check the module MyCompany_HotFix compatibility!' );
}

Reference:
How to check the Magento 2 version?
How to use logger?