text:
Q: How to vertically center content with variable height within a div? What is the best way to vertically center the content of a div when the height of the content is variable.  In my particular case, the height of the container div is fixed, but it would be great if there were a solution that would work in cases where the container has a variable height as well. Also, I would love a solution with no, or very little use of CSS hacks and/or non-semantic markup.

A: Best result for me so far:
div to be centered:
position: absolute;
top: 50%;
transform: translateY(-50%);
margin: 0 auto;
right: 0;
left: 0;

A: You can use margin auto. With flex, the div seems to be centered vertically too.
body,
html {
  height: 100%;
  margin: 0;
}
.site {
  height: 100%;
  display: flex;
}
.site .box {
  background: #0ff;
  max-width: 20vw;
  margin: auto;
}

blabla

blabla

blablabla

lbibdfvkdlvfdks

A: Just add
position: relative;
top: 50%;
transform: translateY(-50%);

to the inner div.
What it does is moving the inner div's top border to the half height of the outer div (top: 50%;) and then the inner div up by half its height (transform: translateY(-50%)). This will work with position: absolute or relative.
Keep in mind that transform and translate have vendor prefixes which are not included for simplicity.
Codepen: http://codepen.io/anon/pen/ZYprdb

A: This seems to be the best solution I've found to this problem, as long as your browser supports the ::before pseudo element: CSS-Tricks: Centering in the Unknown.
It doesn't require any extra markup and seems to work extremely well.  I couldn't use the display: table method because table elements don't obey the max-height property.

.block {
  height: 300px;
  text-align: center;
  background: #c0c0c0;
  border: #a0a0a0 solid 1px;
  margin: 20px;
}

.block::before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */

  /* For visualization
  background: #808080; width: 5px;
  */
}

.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
  padding: 10px 15px;
  border: #a0a0a0 solid 1px;
  background: #f5f5f5;
}

Some text

But he stole up to us again, and suddenly clapping his hand on my
           shoulder, said—"Did ye see anything looking like men going
           towards that ship a while ago?"

A: This is something I have needed to do many times and a consistent solution still requires you add a little non-semantic markup and some browser specific hacks.  When we get browser support for css 3 you'll get your vertical centering without sinning.
For a better explanation of the technique you can look the article I adapted it from, but basically it involves adding an extra element and applying different styles in IE and browsers that support position:table\table-cell on non-table elements.

            Excuse me. What did you sleep in your clothes again last night. Really. You're gonna be in the car with her. Hey, not too early I sleep in on Saturday. Oh, McFly, your shoe's untied. Don't be so gullible, McFly. You got the place fixed up nice, McFly. I have you're car towed all the way to your house and all you've got for me is light beer. What are you looking at, butthead. Say hi to your mom for me.

There are many ways (hacks) to apply styles in specific sets of browsers. I used conditional comments but look at the article linked above to see two other techniques.
Note: There are simple ways to get vertical centering if you know some heights in advance, if you are trying to center a single line of text, or in several other cases.  If you have more details then throw them in because there may be a method that doesn't require browser hacks or non-semantic markup.
Update: We are beginning to get better browser support for CSS3, bringing both flex-box and transforms as alternative methods for getting vertical centering (among other effects). See this other question for more information about modern methods, but keep in mind that browser support is still sketchy for CSS3.

A: you can use flex display such as below code:

.example{
  background-color:red;
  height:90px;
  width:90px;
  display:flex;
  align-items:center; /*for vertically center*/
  justify-content:center; /*for horizontally center*/
}

Some text

A: Using the child selector, I've taken Fadi's incredible answer above and boiled it down to just one CSS rule that I can apply. Now all I have to do is add the contentCentered class name to elements I want to center:

.contentCentered {
  text-align: center;
}

.contentCentered::before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -.25em; /* Adjusts for spacing */
}

.contentCentered > * {
  display: inline-block;
  vertical-align: middle;
}

Some text

But he stole up to us again, and suddenly clapping his hand on my
      shoulder, said—"Did ye see anything looking like men going
      towards that ship a while ago?"

Forked CodePen: http://codepen.io/dougli/pen/Eeysg

A: For me the best way to do this is:
.container{
  position: relative;
}

.element{
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

The advantage is not having to make the height explicit

A: This is my awesome solution for a div with a dynamic (percentaged) height.
CSS
.vertical_placer{
  background:red;
  position:absolute;
  height:43%;
  width:100%;
  display: table;
}

.inner_placer{
  display: table-cell;
  vertical-align: middle;
  text-align:center;
}

.inner_placer svg{
  position:relative;
  color:#fff;
  background:blue;
  width:30%;
  min-height:20px;
  max-height:60px;
  height:20%;
}

HTML

            <svg> some Text here</svg>

Try this by yourself.


text:
Q: Can i use python os.nice to lower the niceness of a celery task? Can i use python os.nice to lower the niceness of a celery task?
I was thinking of something like this:
@task()
def maintenance_requests():
    os.nice(5)
    request = requests.session()
    request.get('http://maintenance/', params={})

Is there any other way of doing this?
Thanks in advance!
EDIT: Since my application is IO bound, i've discovered that ionice was the command i needed. Did some tests, and it works like a charm. Thanks

A: I don't think you can specify the niceness of a particular Celery task as niceness is a property of the process. A task is simply some code that runs on a Celery worker.
However you can setup a Celery worker with a lower niceness and route maintanance tasks to that worker using Celery's task routing configuration.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What Web Server/Servlet Container Do You Use For Clojure Web Apps?
Possible Duplicate:
Good Web Server/Servlet Container for Clojure Web Apps?

I'm looking around to decide what web server to use for my clojure web app and am interested in what and how others are deploying their Clojure apps to web servers, especially production web servers.


text:
Q: Edit header in dotx/docx file I am currently trying to generate a new docx file from an existing template in dotx format. I want to change the firstname, lastname, etc. in the header but I'm not able to access them for some reason...
My approach is the following:
 public void generateDocX(Long id) throws IOException, InvalidFormatException {

    //Get user per id
    EmployeeDTO employeeDTO = employeeService.getEmployee(id);

    //Location where the new docx file will be saved
    FileOutputStream outputStream = new FileOutputStream(new File("/home/user/Documents/project/src/main/files/" + employeeDTO.getId() + "header.docx"));

    //Get the template for generating the new docx file
    File template = new File("/home/user/Documents/project/src/main/files/template.dotx");
    OPCPackage pkg = OPCPackage.open(template);
    XWPFDocument document = new XWPFDocument(pkg);

    for (XWPFHeader header : document.getHeaderList()) {
        List<XWPFParagraph> paragraphs = header.getParagraphs();
        System.out.println("Total paragraphs in header are: " + paragraphs.size());
        System.out.println("Total elements in the header are: " + header.getBodyElements().size());
        for (XWPFParagraph paragraph : paragraphs) {
            System.out.println("Paragraph text is: " + paragraph.getText());
            List<XWPFRun> runs = paragraph.getRuns();
            for (XWPFRun run : runs) {
                String runText = run.getText(run.getTextPosition());
                System.out.println("Run text is: " + runText);
            }
        }
    }

    //Write the changes to the new docx file and close the document
    document.write(outputStream);
    document.close();
}

The output in the console is either 1, null or empty string... I've tried several approaches from here, here and here but without any luck...

Here is what's inside the template.dotx

A: IBody.getParagraphs and IBody.getBodyElements- only get the paragraphs or body elements which are directly in that IBody. But your paragraphs are not directly in there but are in a separate text box or text frame. That's why they cannot be got this way.
Since *.docx is a ZIP archive containijg XML files for document, headers and footers, one could get all text runs of one IBody by creating a XmlCursor which selects all w:r XML elements. For a XWPFHeader this could look like so:
 private List<XmlObject> getAllCTRs(XWPFHeader header) {
  CTHdrFtr ctHdrFtr = header._getHdrFtr();
  XmlCursor cursor = ctHdrFtr.newCursor();
  cursor.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//*/w:r");
  List<XmlObject> ctrInHdrFtr = new ArrayList<XmlObject>();
  while (cursor.hasNextSelection()) {
   cursor.toNextSelection();
   XmlObject obj = cursor.getObject();
   ctrInHdrFtr.add(obj);
  }
  return ctrInHdrFtr;
 }

Now we have a list of all XML elements in that header which are text-run-elements in Word.
We could have a more general getAllCTRs which gets all CTR elements from any kind of IBody like so:
 private List<XmlObject> getAllCTRs(IBody iBody) {
  XmlCursor cursor = null;
  List<XmlObject> ctrInIBody = new ArrayList<XmlObject>();

  if (iBody instanceof XWPFHeaderFooter) {
   XWPFHeaderFooter headerFooter = (XWPFHeaderFooter)iBody;
   CTHdrFtr ctHdrFtr = headerFooter._getHdrFtr();
   cursor = ctHdrFtr.newCursor();
  } else if (iBody instanceof XWPFDocument) {
   XWPFDocument document = (XWPFDocument)iBody;
   CTDocument1 ctDocument1 = document.getDocument();
   cursor = ctDocument1.newCursor();
  } else if (iBody instanceof XWPFAbstractFootnoteEndnote) {
   XWPFAbstractFootnoteEndnote footEndnote = (XWPFAbstractFootnoteEndnote)iBody;
   CTFtnEdn ctFtnEdn = footEndnote.getCTFtnEdn();
   cursor = ctFtnEdn.newCursor();
  }

  if (cursor != null) {
   cursor.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//*/w:r");
   while (cursor.hasNextSelection()) {
    cursor.toNextSelection();
    XmlObject obj = cursor.getObject();
    ctrInIBody.add(obj);
   }
  }
  return ctrInIBody ;
 }

Now we have a list of all XML elements in that IBody which are text-run-elements in Word.
Having that we can get the text out of them like so:
 private void printAllTextInTextRunsOfIBody(IBody iBody) throws Exception {
  List<XmlObject> ctrInIBody = getAllCTRs(iBody);
  for (XmlObject obj : ctrInIBody) {
   CTR ctr = CTR.Factory.parse(obj.xmlText());
   for (CTText ctText : ctr.getTList()) {
    String text = ctText.getStringValue();
    System.out.println(text);
   }
  }
 }

This probably shows the next challenge. Because Word is very messy in creating text-run-elements. For example your placeholder <<Firstname>> can be split into text-runs << + Firstname + >>. The reason migt be different formatting or spell checking or something else. Even this is possible: << + Lastname + >>; << + YearOfBirth + >>. Or even this: <<Firstname + >> << + Lastname>>; << + YearOfBirth>>. You see, replacing the placeholders with text is nearly impossible because the placeholders may be split into multiple tex-runs.
To avoid this the template.dotx needs to be created from users who know what they are doing.
At first turn spell check off. Grammar check as well. If not, all found possible spell errors or grammar violations are in separate text-runs to mark them accordingly.
Second make sure the whole placeholder is eaqual formatted. Different formatted text also must be in separate text-runs.
I am really skeptic that this will work properly. But try it yourself.
Complete example:
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlCursor;

import java.util.List;
import java.util.ArrayList;

public class WordEditAllIBodys {

 private List<XmlObject> getAllCTRs(IBody iBody) {
  XmlCursor cursor = null;
  List<XmlObject> ctrInIBody = new ArrayList<XmlObject>();

  if (iBody instanceof XWPFHeaderFooter) {
   XWPFHeaderFooter headerFooter = (XWPFHeaderFooter)iBody;
   CTHdrFtr ctHdrFtr = headerFooter._getHdrFtr();
   cursor = ctHdrFtr.newCursor();
  } else if (iBody instanceof XWPFDocument) {
   XWPFDocument document = (XWPFDocument)iBody;
   CTDocument1 ctDocument1 = document.getDocument();
   cursor = ctDocument1.newCursor();
  } else if (iBody instanceof XWPFAbstractFootnoteEndnote) {
   XWPFAbstractFootnoteEndnote footEndnote = (XWPFAbstractFootnoteEndnote)iBody;
   CTFtnEdn ctFtnEdn = footEndnote.getCTFtnEdn();
   cursor = ctFtnEdn.newCursor();
  }

  if (cursor != null) {
   cursor.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//*/w:r");
   while (cursor.hasNextSelection()) {
    cursor.toNextSelection();
    XmlObject obj = cursor.getObject();
    ctrInIBody.add(obj);
   }
  }
  return ctrInIBody ;
 }

 private void printAllTextInTextRunsOfIBody(IBody iBody) throws Exception {
  List<XmlObject> ctrInIBody = getAllCTRs(iBody);
  for (XmlObject obj : ctrInIBody) {
   CTR ctr = CTR.Factory.parse(obj.xmlText());
   for (CTText ctText : ctr.getTList()) {
    String text = ctText.getStringValue();
    System.out.println(text);
   }
  }
 }

 private void replaceTextInTextRunsOfIBody(IBody iBody, String placeHolder, String textValue) throws Exception {
  List<XmlObject> ctrInIBody = getAllCTRs(iBody);
  for (XmlObject obj : ctrInIBody) {
   CTR ctr = CTR.Factory.parse(obj.xmlText());
   for (CTText ctText : ctr.getTList()) {
    String text = ctText.getStringValue();
    if (text != null && text.contains(placeHolder)) {
     text = text.replace(placeHolder, textValue);
     ctText.setStringValue(text);
     obj.set(ctr);
    }
   }
  }
 }

 public void generateDocX() throws Exception {

  FileOutputStream outputStream = new FileOutputStream(new File("./" + 1234 + "header.docx"));

  //Get the template for generating the new docx file
  File template = new File("./template.dotx");
  XWPFDocument document = new XWPFDocument(new FileInputStream(template));

  //traverse all headers
  for (XWPFHeader header : document.getHeaderList()) {
   printAllTextInTextRunsOfIBody(header);

   replaceTextInTextRunsOfIBody(header, "<<Firstname>>", "Axel");
   replaceTextInTextRunsOfIBody(header, "<<Lastname>>", "Richter");
   replaceTextInTextRunsOfIBody(header, "<<ProfessionalTitle>>", "Skeptic");
  }

  //traverse all footers
  for (XWPFFooter footer : document.getFooterList()) {
   printAllTextInTextRunsOfIBody(footer);

   replaceTextInTextRunsOfIBody(footer, "<<Firstname>>", "Axel");
   replaceTextInTextRunsOfIBody(footer, "<<Lastname>>", "Richter");
   replaceTextInTextRunsOfIBody(footer, "<<ProfessionalTitle>>", "Skeptic");
  }

  //traverse document body; note: tables needs not be traversed separately because they are in document body
  printAllTextInTextRunsOfIBody(document);

  replaceTextInTextRunsOfIBody(document, "<<Firstname>>", "Axel");
  replaceTextInTextRunsOfIBody(document, "<<Lastname>>", "Richter");
  replaceTextInTextRunsOfIBody(document, "<<ProfessionalTitle>>", "Skeptic");

  //traverse all footnotes
  for (XWPFFootnote footnote : document.getFootnotes()) {
   printAllTextInTextRunsOfIBody(footnote);

   replaceTextInTextRunsOfIBody(footnote, "<<Firstname>>", "Axel");
   replaceTextInTextRunsOfIBody(footnote, "<<Lastname>>", "Richter");
   replaceTextInTextRunsOfIBody(footnote, "<<ProfessionalTitle>>", "Skeptic");
  }

  //traverse all endnotes
  for (XWPFEndnote endnote : document.getEndnotes()) {
   printAllTextInTextRunsOfIBody(endnote);

   replaceTextInTextRunsOfIBody(endnote, "<<Firstname>>", "Axel");
   replaceTextInTextRunsOfIBody(endnote, "<<Lastname>>", "Richter");
   replaceTextInTextRunsOfIBody(endnote, "<<ProfessionalTitle>>", "Skeptic");
  }

  //since document was opened from *.dotx the content type needs to be changed
  document.getPackage().replaceContentType(
   "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml",
   "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");

  //Write the changes to the new docx file and close the document
  document.write(outputStream);
  outputStream.close();
  document.close();
 }

 public static void main(String[] args) throws Exception {
  WordEditAllIBodys app = new WordEditAllIBodys();
  app.generateDocX();
 }
}

Btw.: Since your document was opened from *.dotx the content type needs to be changed from wordprocessingml.template to wordprocessingml.document. Else Word will not open the resulting *.docx document. See Converting a file with ".dotx" extension (template) to "docx" (Word File).
As I am skeptic about the replacing-placeholder-text-approach, my preferred way is filling forms. See Problem with processing word document java. Of course such form fields cannot be used in header or footer. So headers or footers schould be created form scratch at whole.


text:
Q: I get a cookie that contains a Session Token from my Login WS call ? It always gives me the login page, as a response, because, it doesn't see me as logged in.
This is the code for my POST method ( i call it both on the login and other web services):
protected WebEntity sendPOST(WebServiceTask.InputParam param) throws Exception {
    WebEntity result = null;
    httppost = new HttpPost(param.url);

    if ((param.nameValuePairs != null) && !param.nameValuePairs.isEmpty()) {
        httppost.setEntity(new UrlEncodedFormEntity(param.nameValuePairs, "UTF-8"));
        LogService.log("sendPOST", "======params========" + param.nameValuePairs);
    }
    System.out.println("----blabla_session : "+blabla_session);
    if (blabla_session != null) {
        CookieStore cookieStore = httpclient.getCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("blabla_session", blabla_session);
        cookie.setDomain("http://blbla.kz");
        cookieStore.addCookie(cookie);
        httpclient.setCookieStore(cookieStore);
        httppost.setHeader("Set-Cookie", blabla_session);

    }
    LogService.log("WEB-SERVER-CLIENT POST : ", httppost.getURI().toString());
    HttpResponse response = httpclient.execute(httppost);

    if (response.getStatusLine().getStatusCode() >= 400) {
        String maybeThereIsSomeExtraMessageInBody = "";
        try {
            maybeThereIsSomeExtraMessageInBody = (String) getResponseStream(response, response.getEntity(), String.class);
        } catch (Exception e) {
            e.printStackTrace();
            // DO NOTHING
        }
        return new WebEntity(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase() + "\n" + maybeThereIsSomeExtraMessageInBody);
    }
    Header cp = response.getFirstHeader("Set-Cookie");
    if(cp!=null){
        HeaderElement[] he = cp.getElements();
        for (int i = 0; i < he.length; i++) {
            if(he[i].getName().equalsIgnoreCase("blabla_session")){
                blabla_session = he[i].getValue();
                break;
            }
        }
    }
    HttpEntity responseEntity = response.getEntity();
    if (responseEntity != null) {
        if (result != null) {
            result.success = true;
        } else {
            result = new WebEntity(false);
        }
    }
    return result;
}

Now the first WS call i do, is the Login WS, at this time, blabla_session is null, so that part of the code, does not initiate. From the second WS call, the blabla_session (which is static) is initiated with the necesary session_code, i get from the session. This is why, it enters the (blabla_session != null) part of code, where it should create the cookie, to send with the WS call
This is the code they use for the WebService, i call:
r = requests.post('http://blabla.kz/api/login/',data={'username':'USERNAME','password':'123'})
rr = requests.get('http://blabla.kz/api/validate_coupon/bsdfsdfsd/', cookies=r.cookies)
rr.text

A: When i was invoking the webservice call, i had a parameter that shouldn;t be there, in the nameValuePairs, and that is why it was crashing


text:
Q: Counting letters in a text and printing the count plus the highest and lowest Other than the bad format why cant this just print out them all once. I dont think im storing it in the array right or at all. So If you guys could please help me with where I am in the wrong it would be greatly appreciated
import java.util.*;

public class LetCount {

    public static final int NUMCHARS = 26 + 1; //You define

    public static int addr(char ch) {
        return (int) ch - (int) 'A' + 1;
    }

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in); // for reading input
        int[] count = new int [NUMCHARS];
        int curIndex = 0;
        int max = 0;
        System.out.println("Enter text to be read");
        while (keyboard.hasNext()) {
            String str1 = keyboard.nextLine().toUpperCase();
            char ch = str1.charAt(curIndex);
            for(curIndex = 0; curIndex < str1.length(); curIndex++) {
                ch = str1.charAt(curIndex);
                if (ch >= 'A' && ch <= 'Z') {
                    addr(ch);
                    count[ch - 'A']++;
                }

                for (int i = 0; i > 26; ++i) {
                    int highest;
                    highest = count[i];

                    System.out.printf(" %c ", i + 'A');
                    System.out.println("occurred " + count[i] + " times");
                    if (highest >= max) {
                        if (highest > max) {
                            max = highest;
                        }
                    }
                }

                System.out.println(max);
            }
        }
    }
}

A: A couple of issues in your code:

*

*You were calculating string length number of times.

*Your for loop reads this: for (int i = 0; i > 26; ++i) { It should be for (int i = 0; i < 26; ++i) {

*You were printing the entire array string length number of times.

*You do not need to use the function addr anymore.

Following is the corrected code:
import java.util.*;

public class LetCount {

public static final int NUMCHARS = 26 + 1; //You define

public static int addr(char ch) {
    return (int) ch - (int) 'A' + 1;
}

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in); // for reading input
    int[] count = new int [NUMCHARS];
    int curIndex = 0;
    int max = 0;
    System.out.println("Enter text to be read");
    while (keyboard.hasNext()) {
        String str1 = keyboard.nextLine().toUpperCase();
        char ch = str1.charAt(curIndex);
        for(curIndex = 0; curIndex < str1.length(); curIndex++) {
            ch = str1.charAt(curIndex);
            if (ch >= 'A' && ch <= 'Z') {
              //  addr(ch); No need to use this
                count[ch - 'A']++;
            }

        }
        int highest;
            for (int i = 0; i < 26; ++i) {   //you had the < sign wrong here.

                highest = count[i];
                if (highest >= max) {
                    if (highest > max) {
                        max = highest;
                    }
                }
            }
            //print the entire thing only once.
            for (int i = 0; i < 26; ++i) {
                System.out.printf(" %c ", i + 'A');
                System.out.println("occurred " + count[i] + " times");
             }

            System.out.println("Maximum is " + max);
          }
    }
}


text:
Q: Unable to add CrmDeploymentService Web Reference due to Authentication Issue I am having an issue adding a Web Service Reference to the CRM Deployment Service at http:///MSCRMServices/2007/CrmDeploymentService.asmx
When I first attempt to connect it says Connecting to  and prompts for credentials. After entering my credentials, it will continue to prompting for credentials indefinately.
When I attempt to navigate to the service in IE, I get prompted for credentials and after submitting them a few times, I get a 401 error.
When I attempt to navigate to the service in Firefox or Opera, the basic authentication dialog pops up and I enter credentials. The service description page correctly appears.
Is there something preventing IE/VS from submitting the credentials correctly? In each place, I am using the same domain/user credentials. I have tried it from IE on both a computer on the domain and a computer not on the domain and get the same results.

A: Not sure if this will help, but I vaguely remember something like this happening to us at work, and someone fixed it by disabling IPV6.  Like I said my memory is hazy so I don't know if this is the exact problem that we were having too.  I just remember that the solution was to disable IPV6 on the server.


text:
Q: CPU memory allocation failed in Dynet I am not sure why I am running out of memory. Take the parser of Goldberg, all I do is to change this line:

scores, exprs = self.__evaluate(conll_sentence, True)

and add a for loop around it to repeat it K times:
for k in xrange(K):
    scores, exprs = self.__evaluate(conll_sentence, True)
    # do something

Then in the getExpr, i do the following:
samples_out = np.random.normal(0,0.001, (1, self.hidden_units))
samples_FOH = np.random.normal(0,0.001,(self.hidden_units, self.ldims * 2))
samples_FOM = np.random.normal(0,0.001,(self.hidden_units, self.ldims * 2))
samples_Bias = np.random.normal(0,0.001, (self.hidden_units))

XoutLayer = self.outLayer.expr()+inputTensor(samples_out)
XhidLayerFOH = self.hidLayerFOH.expr()+inputTensor(samples_FOH)
XhidLayerFOM = self.hidLayerFOM.expr()+inputTensor(samples_FOM)
XhidBias = self.hidBias.expr()+inputTensor(samples_Bias)

if sentence[i].headfov is None:
    sentence[i].headfov = XhidLayerFOH * concatenate([sentence[i].lstms[0], sentence[i].lstms[1]])
if sentence[j].modfov is None:
    sentence[j].modfov  = XhidLayerFOM * concatenate([sentence[j].lstms[0], sentence[j].lstms[1]])

output = XoutLayer * self.activation(sentence[i].headfov + sentence[j].modfov + XhidBias)
return output

Essentially what is happening in the above block is to first generate normally distributed noise, then add it to the trained values. But it seems somewhere along the way, all the generated values stay in the memory and it just runs out of memory. Any one knows why?

A: Dynet expressions stay in memory until the next call to renew_cg().
So the fix would be to call it after each iteration of your loop, provided that you have retrieved all information you needed from the computation graph.
Side note: when you do a simple addition, such as:
XoutLayer = self.outLayer.expr()+inputTensor(samples_out)

no addition is actually performed. You just create a new expression and specify how to evaluate it from other expressions. The actual computation is performed when there is a call to .forward() (or .value(), etc) on XoutLayer or on an expression whose computation depends on XoutLayer.
So, dynet needs to allocate memory for all expressions in the current computation graph.


text:
Q: How do I output the max int from user input? I wrote a program that should output the maximum int from user input:
15 20 0 5 -1

should output Max: 20
There seems to be an infinite loop because it never gets to the final cout statement. The while loop should stop with a negative number. It's not outputting anything right now.
Here is my code:
#include <iostream>

using namespace std;

int main()
{

    int currV;
    int maxSoFar;

    // 15 20 0 5 -1

    // should output 20

    cin >> currV;
    if (currV > 0)
    {
        maxSoFar = currV;
    }

    while (currV > 0)
    {

        if (currV > maxSoFar)
        {
            maxSoFar = currV;
        }
        cin >> currV;
    }
    cout << "Max: " << maxSoFar;
}

A: Firstly, I recommend formatting your code better.
Furthermore, your code looks quite confusing and I recommend something like this for what you are trying to do:
#include <iostream>
using namespace std;

int main() {

    int currV = 0;
    int maxSoFar = 0;

    while (cin >> currV)
    {
        if(currV < 0)
        {
            cout << "Max: " << maxSoFar;
            return 0;
        }

        if(currV > maxSoFar)
        {
            maxSoFar = currV;
        }
    }
}

A: You need to initialize maxSoFar. Reading/using an uninitialized variable will cause undefined behaviour, then afterward anything could happened. This could be solve by initializing maxSoFar = -1; beforehand.
You can use max() to get maximum value of 2 integers as well.
#include <iostream>
using namespace std;

int main()
{
    int currV, maxSoFar = -1; //initializing maxSoFar

    while(cin >> currV)
    {
        if (currV < 0) {break;}
        maxSoFar = max(maxSoFar, currV);
    }
    cout << "Max : " << maxSoFar; return 0;
}

Result:
5 20 0 5 -1
Max : 20

Also, see Why is "using namespace std;" considered bad practice?
Related : What happens to a declared, uninitialized variable in C? Does it have a value?

A: #include <iostream>

using namespace std;

int main()
{
    int currV, maxSoFar = -1;

    if (cin >> currV && currV >= 0)
    {
        maxSoFar = currV;
        while (cin >> currV && currV >= 0)
        {
            if (currV > maxSoFar)
            {
                maxSoFar = currV;
            }
        }
    }

    cout << "Max: " << maxSoFar;
}

Online Demo

A: int currV;
int maxSoFar = 0; // if all integers are negetive than `maxSoFar` should be 0

while (cin >> currV)
{
    if (currV < 0) break;
    maxSoFar = max(maxSoFar, currV);
}
cout << "Max: " << maxSoFar;

see this - https://isocpp.org/wiki/faq/input-output#stream-input-failure


text:
Q: AssetDatabase.GetAssetPath return empty string for prefab I use unity5.5.4, drag a particle effect prefab to a UI prefab, do not hit apply, so the select button could select the original particle prefab in editor. I use script to findchild the effect prefab node, and then call AssetDatabase.GetAssetPath(go) to get the effect path, but the return value is an empty string
this is the code I used to find the dragged particle effect prefab from UI prefab:
GameObject child = go.transform.GetChild(i).gameObject;
if (child.tag == "particle") return child


text:
Q: Is it mandatory for $F$ to be divergence free to have surface independent property? I was trying to solve the problem to find $\int_{C}F\cdot dr$ where $C$ is the curve of intersection of cone $z^2=x^2+y^2$ and plane $z=1$. Also $F(x,y,z)=y\vec{i}+z\vec{j}+x\vec{k}$

So here we have two possible surfaces $S_1$ and $S_2$ with same boundary $C$ oriented positively.
I tried verifying for above $F$ which is divergence free and successfully showed that $$\iint_{S1}\text{curl}(F) \cdot dS_1=\iint_{S_2}\text{curl}(F)\cdot dS_2$$
But in this link:
https://mathinsight.org/stokes_theorem_examples
they have taken $F=\left(\sin x-\frac{y^3}{3}, \cos y+\frac{x^3}{3}, xyz\right)$ and its been told that
$$\iint_{S_1}\text{curl}(F)\cdot dS_1=\iint_{S_2}\text{curl}(F)\cdot dS_2$$
any clarification?

A: The field $F$ in your first example is "by coincidence" divergence free. This has no avail for the line integral $\int_C F\cdot dr$.
By Stokes' theorem this line integral is equal to the surface integral $\int_S{\rm curl}(F)\cdot dS$ for any surface $S$ with $\partial S=C$, in particular for the two surfaces $S_1$, $S_2$ in your figures:
$$\int_{\partial S} F\cdot dr=\int_S{\rm curl}(F)\cdot dS\ .$$
There is no divergence appearing here.
On the other hand the curl of any field $F$ is divergence free: $${\rm div}\,{\rm curl}(F)\equiv0\ .$$ This plays a rôle in your second example: The two surfaces $S_1$, $S_2$ together bound a three-dimensional cone $K$, whereby $\partial K=S_1-S_2$. By Gauss' theorem we therefore have
$$\int_{S_1}{\rm curl}(F)\cdot dS-\int_{S_2}{\rm curl}(F)\cdot dS=\int_{\partial K}{\rm curl}(F)\cdot dS=\int_K {\rm div}\,{\rm curl}(F)\>dV=0\ .$$


text:
Q: Facebook ignores timezone info for non-logged in users on uploaded events with ISO-8601 datetime Events entered manually into facebook show correct times regardless of logged in state, but events uploaded via an app with datetimes to ISO-8601 (which includes time zone info ie 2013-09-27T13:00:00+01:00) result in facebook assuming event is US based for display.
Once a user is logged in, facebook shows the event correctly using the timezone info.
Its noticeable that manually entered events show a UTC+1 indicator, which does not appear on uploaded events.
Why is facebook ignoring timezone info when a visitor is not logged in, but only for uploaded events?
Is facebook requiring additional timezone data or is this a bug.
Dates are pulled from the dBase and converted to ISO8601 with:
date("c", strtotime($date))
then upload function is:
        `$page = $facebook->api("/{$page_id}");
        $event_data = array(
            'name' => stripslashes($_POST['name']),
            'description' => stripslashes(preg_replace('/£/', '£', $_POST['description'])),
            'start_time' => $_POST['start_time'],
            'end_time' => $_POST['end_time'],
            'ticket_uri' => $_POST['ticket_uri'],
            'location' => $_POST['location'],
            'location_id' => $_POST['location_id'],
            'no_feed_story' => ($_POST['no_feed_story'] == 1),
            'picture' => $_POST['picture'],
            'access_token' => $access_token,
            'page_id' => $page_id);
     }

    $post = @$facebook->api('/' . $page_id . '/events?fields=name,picture,description,start_time,end_time,ticket_uri,location,no_feed_story', 'POST', $event_data);`

When not logged into facebook this will give:
     [When] 27 September at 05:00 until 29 September at 07:00
and once logged in:
     [When] 27 September at 13:00 until 29 September at 15:00
And I am in the UK so viewing from the indicated timezone (UTC+1), my IP location is London.
Editing an uploaded event the timezone is also shown as UTC+01 though that does not display when logged out ??
Some additional info, I`ve downloaded the event feed for the page and note the following errors:
An uploaded datetime of 2013-09-27T13:00:00+01:00 is changed to 2013-09-27T12:00:00+0000
and no time zone is shown, so is it expecting some other timezone data on upload?
I've now added to the code to allow editing of existing events using:
$post = $facebook->api('/' . $_POST['event_id'] . '/', 'POST', $event_data);
for update and note that editing a originally manually edited event (that has the timezone) changing the event times using above datetime format, the timezone is retained, changing location has no effect either.

A: Have you enabled time zone support in the Facebook app settings?

You can read about this more here.


text:
Q: "echo" mostra número decimal com virgula em vez de ponto Tenho este código no PHP 7:
$total_pedido = 123.90;
$frete_valor = 13.98;

$total_geral = ($total_pedido + $frete_valor);

echo ($total_geral); // Mostra 137,88

O resultado da soma (137.88) o que está correto, porém dando um echo (sem nenhum tratamento) ele traz 137,88 com virgula, não deveria vir com ponto?
Devido a esse resultado com virgula tenho que tratar a string antes de enviar a um webservice.
Esse comportamento é normal no PHP ou é devido a alguma configuração no php.ini?

A: Conforme a documentação até o PHP7.x a conversão de string era afetada pelo locale
Um valor pode ser convertido em uma string usando o (string) $variavel ou a função strval(). A conversão de string é feita automaticamente no escopo de uma expressão onde uma string é necessária. Isso acontece ao usar as funções de echo ou print, ou quando uma variável é comparada a uma string. As seções sobre Types e Type Juggling tornarão o seguinte mais claro.
Um int ou float é convertido em uma string que representa o número textualmente (incluindo a parte do expoente para floats). Os números de ponto flutuante podem ser convertidos usando a notação exponencial (4.1E+6).
No PHP8, o caractere do ponto decimal é sempre o "ponto" (.). Antes do PHP8, o caractere do ponto decimal é definido no locale do script (LC_NUMERIC), que justamente é o ocorrido em seu caso.
Em resumo antes do PHP8 era afetado pelo locale, para fazer o teste usei o German_Germany.1252:
<?php

setlocale(LC_NUMERIC, 'German_Germany.1252');

// Apenas obtem o locale atual, sem alterar
$locale = setlocale(LC_ALL, 0);

echo 10.14, "\n";

var_dump($locale);

No PHP7
10,14
string(99) "LC_COLLATE=C;LC_CTYPE=Portuguese_Brazil.1252;LC_MONETARY=C;LC_NUMERIC=German_Germany.1252;LC_TIME=C"

Saída no PHP8:
10.14
string(78) "LC_COLLATE=C;LC_CTYPE=C;LC_MONETARY=C;LC_NUMERIC=German_Germany.1252;LC_TIME=C"

Possíveis causas da saída atual estar com vírgula:

*

*Você pode estar usando um auto_prepend_include que esteja usando setlocale()

*O LC_NUMERIC (ou LC_ALL) pode ter sido configurado no /etc/default/locale

*Ou até mesmo pode ter sido uma configuração no .bashrc
Confira essas situações (o SetEnv do Apache eu não pude testar, talvez em Fast-CGI exista alguma configuração que afete o locale, se encontrar algum detalhe atualizo a resposta).


text:
Q: how to show multiple values of same attribute in tooltip in highcharts? I'm displaying pie chart from geojson data in pop up window in my geodjango application.
below is the javascript code
$(function () {
    $('#container').highcharts({
        chart: {
            type: 'pie',
            backgroundColor: 'rgba(0,0,0,0)',
            y: 100
        },
        title: {
            text: 'sfs '
        },
        yAxis: {
            title: {
                text: ' '
            }
        },
        plotOptions: {
            pie: {
//                y:1,
                shadow: false,
//                center: ['50%', '50%'],
                borderWidth: 0,
                showInLegend: false,
                size: '80%',
                innerSize: '60%',
                data: [
                    ['Plant Functional Type1', 18],
                    ['Plant Functional Type2', 14],
                    ['Plant Functional Type3', 11]
                ]
            }
        },
        tooltip: {
//            valueSuffix: '%',
            formatter: function () {
                return  this.series.name +
                        '
Species: ' + feature.properties.species +
                        '
 name ' + feature.properties.listvalues;
            }
        },
        series: [{
            type: 'pie',
            name: 'PFT',
            dataLabels: {
                color:'white',
                distance: -20,
                formatter: function () {
                    if (this.percentage != 0) return Math.round(this.percentage) + '%';
                }
            }
        }, {
            type: 'pie',
            name: 'PFT',
            dataLabels: {
                connectorColor: 'grey',
                color:'black',
//                y:-10,
                softConnector: false,
                connectorWidth:1,
                verticalAlign:'top',
                distance: 20,
                formatter: function () {
                    if (this.percentage != 0) return this.point.name;
                }
            }
        }]
    });
});

The geojson data is
{"type": "FeatureCollection", "crs": {"properties": {"type": "proj4", "href": "http://spatialreference.org/ref/epsg/4326/"}, "type": "link"}, "features": [{"properties": {"species": "Oxalis corniculata L.", "listvalues": 0, "model": "pft.existing_data_apft"}, "type": "Feature", "geometry": {"coordinates": [76.320083, 32.233167], "type": "Point"}, "id": 1}, {"properties": {"species": "Pinus roxburghii Sargen", "listvalues": 2, "model": "pft.existing_data_apft"}, "type": "Feature", "geometry": {"coordinates": [76.320083, 32.233167], "type": "Point"}, "id": 2}, {"properties": {"species": "Trifolium repens L.", "listvalues": 1, "model": "pft.existing_data_apft"}, "type": "Feature", "geometry": {"coordinates": [76.320083, 32.233167], "type": "Point"}, "id": 3}, {"properties": {"species": "Poa annua L.", "listvalues": 0, "model": "pft.existing_data_apft"}, "type": "Feature", "geometry": {"coordinates": [76.320083, 32.233167], "type": "Point"}, "id": 4}, {"properties": {"species": "Fragaria nubicola Lindley ex Lacatia", "listvalues": 0, "model": "pft.existing_data_apft"}, "type": "Feature", "geometry": {"coordinates": [76.320083, 32.233167], "type": "Point"}, "id": 5}, {"properties": {"species": "Cedrus deodara (Roxb. ex Lambert.) G.Don.", "listvalues": 2, "model": "pft.existing_data_apft"}, "type": "Feature", "geometry": {"coordinates": [76.320083, 32.233167], "type": "Point"}, "id": 6}]}

In tooltip , I want to dispaly

*

*all the species whose listvalues is 0

*all the species whose listvalues is 1

*all the species whose listvalues is 2

How to do this?
Here is jsfiddle

A: TL;DR
I've updated your code. See the jsfiddle. https://jsfiddle.net/gqe55wj7/3/
I implemented based on Donut chart of the Highcharts demo.
If you want to make a pie chart rather than a donut chart, you should set one series to highcharts options (not multiple).
Create series
Create series of the inner pie chart (PFT: Plant Functional Type) & outer pie chart (plants).
var colors = Highcharts.getOptions().colors;

// stores the data for every PFT
var datas = {};
$.each(json.features, function (i, feature) {
    var type = feature.properties.listvalues;
    if (!datas[type]) {
        datas[type] = [];
    }
    datas[type].push(feature);
});

// create series.
var pftSeries = [];
var plantSeries = [];
$.each(datas, function (i, features) {
    var color = colors[i];
    pftSeries.push({
        name: 'Plant Functional Type' + i,
        y: features.length,
        color: color
    });

    $.each(features, function (j, feature) {
        plantSeries.push({
            name: feature.properties.species,
            listvalues: feature.properties.listvalues,
            y: 1,
            color: color
        });
    });
});

Set Series
$('#container').highcharts({

    //...

    series: [{
        // inner pie chart (PFT).
        type: 'pie',
        name: 'PFT',
        size: '60%',
        data: pftSeries,
        dataLabels: {
            color:'white',
            distance: -20,
            formatter: function () {
                if (this.percentage != 0) return Math.round(this.percentage) + '%';
            }
        }
    }, {
        // outer pie chart (plants).
        type: 'pie',
        name: 'PFT',
        innerSize: '60%',
        size: '80%',
        data: plantSeries,
        dataLabels: {
            connectorColor: 'grey',
            color:'black',
            softConnector: false,
            connectorWidth:1,
            verticalAlign:'top',
            distance: 20,
            formatter: function () {
                if (this.percentage != 0) return this.point.name;
            }
        }
    }]
});

Tooltips
Series of the index is 0 is the inner chart(PFT).

*

*get the index of the point.

*identify listvalues from key of the datas with the index of the point.

*get the data of the plants from datas[listvalues].

*build tooltip text and return.

Series of the index is 1 is the outer chart(plant).

*

*get the index of the point.

*identify listvalues from datas with the index of the point.

*build tooltip text and return.

tooltip: {
    formatter: function () {
        var index;
        var listvalues = 0;
        if (this.series.index === 0) {
            // inner pie chart. (PFT)
            index = this.series.data.indexOf(this.point);
            var i = 0;
            for (var key in datas) {
                if (datas.hasOwnProperty(key)) {
                    if (index === i) {
                        listvalues = key;
                        break;
                    }
                    i++;
                }
            }
            var features = '';
            $.each(datas[listvalues], function (i, feature) {
                features += 'Species: ' + feature.properties.species +
                            '
 name ' + feature.properties.listvalues + '
';
            });
            return '' + this.series.name + '
' + features;
        } else {
            // outer pie chart. (plant)
            index = this.series.data.indexOf(this.point);
            var name = this.point.name;
            var length = 0;
            $.each(datas, function (i, features) {
                length += features.length;
                if (index < length) {
                    listvalues = i;
                    return false;
                }
            });
            return '' + this.series.name + '
Species: ' + name + '
 name ' + listvalues
        }
    }
},


text:
Q: Word for curiosity that gets one into trouble Is there a term that describes a person's quality of being curious but getting into trouble because of it? For example, Odysseus in "The Odyssey" wants to see the cyclops so he decides to stay in the cave but because if it his crew almost dies. I am looking for a word that I can use to say: "Because of Odysseus's [insert word] he makes several decisions that nearly lead to the loss of his crew".

A: Curiosity itself can get one into trouble but it is more likely that a "morbid curiosity" leads to trouble. So you can use "morbid curiosity" in your example.
From wikipedia:

A morbid curiosity exemplifies addictive curiosity. It has as its object death, violence, or any other event that may cause harm physically or emotionally, the addictive emotion being explainable by meta-emotions exercising pressure on the spontaneous curiosity itself.

The metaphor "curiosity killed the cat" can support your subject also.

A: Consider prying, this sense of which is defined by oxforddictionaries.com as

Excessively interested in a person's private affairs; too inquisitive.

Another similar sense might be conveyed by nosiness, though this has an informal feel to it.

A: Mischievous is the word that you might be thinking of.


text:
Q: Should Python library modules start with #!/usr/bin/env python? Should Python library modules start with #!/usr/bin/env python?
Looking at first lines of *.py in /usr/share/pyshared (where Python libs are stored in Debian) reveals that there are both files that start with the hashbang line and those that do not.
Is there a reason to include or omit this line?

A: The reason why some files in /usr/share/pyshared have declared the shebang & some do not are easy to explain. Take the files uno.py and pyinotify.py. The former has no shebang and the latter has.

*

*uno.py is a python module which will be imported and used in other programs/scripts. Thus it will never be executed directly from the command line.

*On the other hand pyinotify.py contains the shebang and you can see that it contains the following line at the bottom (it can made into an executable if you run a chmod u+x on it):
if __name__ == '__main__':
    command_line()

You can hardcode the python binary in the shebang, but as others have mentioned, using /usr/bin/env will make it more portable.

A: This line is a Shebang line. For details, please consult the wikipedia article. Basically, it specifies the interpreter with which the file can be executed if directly run from the command line.
There is no need to include this line on the top of a file unless you are planning to directly run it from the shell. Some Python modules (e.g. ftplib) have some functionality when you directly run them. These will have the #! line on top. Most don't have such functionality and therefore don't need this line.

A: if you want your script to be an executable, you have to include this line


text:
Q: moving images in java applet The question is about java applet programming
I used a java applet to draw an image in the paint method using the following code:
       g.draw(Myimage,0,0,this);

The image was drawn on the screen, But what i want to do is to be able to change the position of this image without clearing the screen and without drawing blank image in the previous position of the image..
Thanks in advance.

A: You can simply draw another image in other place. Just change the parameters in your code. For more details about graphics object follow the link. http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/Graphics.html
Other wise why dont you simply extend GraphicsProgram class provided by acm. It has a move function which will exactly do what you want to do. Check out the link.
http://jtf.acm.org/rationale/graphics-package.html
Hope this helps.

A:
But what i want to do is to be able to change the position of this image without clearing the screen and without drawing blank image in the previous position of the image..

Then use a JLabel. When you want to move the label you use the setLocation() method. The RepaintManager will repaint the location where the label was and then paint the label in its new location so you don't have to worry about calculating the area affected by the move.


text:
Q: Find the covariance of $Y_1$ and $Y_2$ I had a statistics question I was hoping for help on:
Let $Y_1$ and $Y_2$ be discrete random variables with join probability function:
$$f(x,y) = \begin{cases} \dfrac{y_1 + 2y_2}{18} & \text{if $y_1 = 1,2 ; y_2 = 1,2$} \\ 0 & \text{elsewhere} \end{cases}$$
Find the covariance of $Y_1$ and $Y_2$.

Below is my work, would anyone be able to let me know if I'm right or if there are any errors? Thank you so much in advance, I really appreciate it!
Probabilities derived from the above function:
$(Y_1,Y_2)$
$(1,1) = \dfrac{1}{6}$, $(2,1) = \dfrac{2}{9}$
$(1,2) = \dfrac{5}{18}$, $(2,2) = \dfrac{1}{3}$
Marginal Probabilities from the above probabilities:
$p_1(1)$ = $\dfrac{4}{9}$
$p_1(2)$ = $\dfrac{5}{9}$
$p_2(1)$ = $\dfrac{7}{18}$
$p_2(2)$ = $\dfrac{11}{18}$
$E[Y_1 Y_2] = (1)(1)(1/6)+(1)(2)(2/9)+(2)(1)(5/18)+(2)(2)(1/3) = \dfrac{5}{2}$
$E[Y_1]$ = (1)(4/9)+(2)(5/9) = $\dfrac{14}{9}$
$E[Y_2] = (1)(7/18) + 2(11/8) = \dfrac{29}{18}$
$$\operatorname{Cov}(Y_1,Y_2)=E[Y_1 Y_2]-E[Y_1] E[Y_2] = \frac{5}{2} - \frac{14}{9} \cdot \frac{29}{18} = -\frac{1}{162}$$

A: You can easily check your work with a computer algebra system. There are a number of such packages around, for applications such as Maple and Mathematica. For your example, the bivariate joint pmf of $(Y_1,Y_2)$ is given as $f(y_1,y_2)$:
$$f=\frac{1}{18} \left(y_1+2 y_2\right); \quad \text{domain}[f] = \{ \{y_1, 1, 2\}, \{y_2, 1, 2\} \}  \text{ && } \{Discrete\};$$
You seek:
$\quad \text{Cov}[\{y_1, y_2\},f]$

$-\frac{1}{162}$

where I am using the Cov function from the mathStatica package for Mathematica to automate. As disclosure, I should perhaps mention that I am one of the authors.


text:
Q: Installing Sonar and Jenkins on Tomcat I have a tomcat server and I wish to install Jenkins and Sonar on it. I am on a debian distibution, therefore I got tomcat6 and Jenkins via apt-get. When I copy the jenkins.war to my tomcat6/webapps directory, everything runs fine. However when I copy the sonar.war to tomcat6/webapps, sonar works fine, but jenkins throws an error 500:
javax.servlet.ServletException: org.apache.commons.jelly.JellyTagException: jar:file:/var/lib/tomcat6/webapps/jenkins/WEB-INF/lib/jenkins-core-1.435.jar!/hudson/model/View/index.jelly:39:43: <st:include> PermGen space
    org.kohsuke.stapler.jelly.JellyClassTearOff.serveIndexJelly(JellyClassTearOff.java:112)
    org.kohsuke.stapler.jelly.JellyFacet.handleIndexRequest(JellyFacet.java:124)
    org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:550)
    org.kohsuke.stapler.Stapler.invoke(Stapler.java:646)
    org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:612)
    org.kohsuke.stapler.Stapler.invoke(Stapler.java:646)
    org.kohsuke.stapler.Stapler.invoke(Stapler.java:477)
    org.kohsuke.stapler.Stapler.service(Stapler.java:159)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:95)
    hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:87)
    hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:47)
    hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)
    hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:76)
    hudson.security.HudsonFilter.doFilter(HudsonFilter.java:164)
    hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:81)

I've also install the manager (tomcat6-admin) and the manager is failing too when i add the sonar.war.
I've installed sonar by downloading it from codehaus, setting the database configuration and building the war.
Does anyone know why this is happening and might have a solution?

A: In your exception, it appears :
PermGen space
org.kohsuke.stapler.jelly.JellyClassTearOff.serveIndexJelly(JellyClassTearOff.java:112)

There's a problem with the permgen :

This error occurs when the JVM runs out of space in the permanent generation heap

To fix the error, you need to put the -XX:MaxPermSize=<Y>m (where <Y> is the memory you want) in the CATALINA_OPTS environment variable.
How do you achieve this ? Follow this article (for example) :
How can I increase memory in my application server ?

A: I had this configured on a RHEL server with 8Gb RAM. I found I needed (in catalina.sh or the non-interactive shell running tomcat) VM options of -Xms1024m -Xmx2048m -XX:PermSize=256m -XX:MaxPermSize=512m
I also needed to reset the Executor maxThreads, and minSpareThreads in the conf/server.xml file (400, and 50 respectively), otherwise the server crawled.
By the way, if you're using Virtual Servers, you could try an already configured VM, SecureCI, which sets up a complete Maven/Jenkins/Sonar CI environment out of the box. There's no configuration if your build relies on Maven.


text:
Q: Typescript Type - Map nested object / functions and flatten with prepending parent keys Given an object with nested objects and functions like so:
const commands: {
 doSomething: () => 'Yo',
 table: {
   rows: () => 10,
   columns: () => 6,
   name: ( name: string) => name + ' hello'
 },
 doSomethingElse: () => 'Boo',
 modal: {
   sub: {
      hello: () => 'hello'
   }
 }
}

I would like to call a function that returns a flat object like so:
const mappedCommands = {
 doSomething: () => 'Yo',
 table_rows: () => 10,
 table_columns: () => 6,
 table_name: ( name: string) => name + ' hello'
 doSomethingElse: () => 'Boo',
 modal_sub_hello: () => 'hello'
}

I would also like this typed. So when I do:
type Commands = typeof mappedCommands

I would get the type:
{
 doSomething: () => string,
 table_rows: () => number,
 table_columns: () => number,
 table_name: (name: string) => string
 doSomethingElse: () => string,
 modal_sub_hello: () => string
}

I've currently got as far as writing this, but it's not typed.
const createCommands = <N extends string, T extends Record<string, any>>(inputs: T, prepend: N) => {
  const mappedCommands: Record<string, any> = {};
  // for each command
  Object.keys(inputs).forEach((key) => {
    const current = inputs[key];
    if (typeof current === 'function') {
      mappedCommands[`${prepend}${key}`] = inputs[key];
    } else {
      const subCommands = createCommands(current, `${key}_`);
      // we add them to the level above.
      Object.keys(subCommands).forEach((key) => {
        mappedCommands[`${prepend}${key}`] = subCommands[key];
      });
    }
  });
  return mappedCommands;
};

I've asked a few related questions, but I think this would be a better solution if I can get it working.
Related questions:
Typescript - Type that Map keys and flatten objects
Typescript Type - append string for each key in object


text:
Q: I am getting mutation of state error between dispatches from redux i am getting the following error:
A state mutation was detected between dispatches, in the path 'notifications.adhans.AsrAdhan'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)]
Following is my notifications reducer in notifications.ts file.
  import {
  RESTORE_NOTIFICATIONS,
  SET_ADHAN,
  SET_ADHANTOGGLE,
  SET_REMINDER,
  SET_REMINDERTOGGLE,
} from "./../constants";

export const initialState = {
  reminderToggle: true,
  adhanToggle: true,
  adhans: {
    FajrAdhan: false,
    DhuhrAdhan: true,
    AsrAdhan: false,  //--->getting mutation error for this
    MaghribAdhan: true,
    IshaAdhan: true,
  },
  reminders: {
    FajrReminder: false,
    DhuhrReminder: false,
    AsrReminder: true,
    MaghribReminder: false,
    IshaReminder: true,
    SunriseReminder: true,
    MidnightReminder: false,
  },
};

export default (state = initialState, action: AnyAction): notificationsT => {
  switch (action.type) {
    case SET_REMINDERTOGGLE:
      return {
        ...state,
        reminderToggle: action.payload,
      };
    case SET_ADHANTOGGLE:
      return {
        ...state,
        adhanToggle: action.payload,
      };
    case SET_ADHAN:
      return {
        ...state,
        adhans: {
          ...state.adhans,
          [action.payload.key]: action.payload.value,
        },
      };
    case SET_REMINDER:
      return {
        ...state,
        reminders: {
          ...state.reminders,
          [action.payload.key]: action.payload.value,
        },
      };

    case RESTORE_NOTIFICATIONS:
      return { ...action.payload };

    default:
      return state;
  }
};

error stack points at  src\screens\Home.tsx:127:14 in RestoreState.
Following is the relevant code for Home.tsx
import AsyncStorage from "@react-native-async-storage/async-storage";
import * as actionTypes from "../store/constants";
import { initialState as notifInitState } from "../store/reducers/notifications";
...

 const updatedNotificationsstate = { ...notifInitState };
 const adhanKeys = Object.keys(notifInitState.adhans);

const keysArray = [
       ...adhanKeys,
      ...//other state keys
];

 const Home = ({ navigation }) => {
  const dispatch = useAppDispatch();

  //When component mounts on start, Restore the redux state
  React.useEffect(() => {
    const RestoreState = async () => {

         const savedState = await AsyncStorage.multiGet(keysArray);

         savedState.forEach(([key, value]) => {
         ...

         if(value){

          //notifications
          if (adhanKeys.includes(key))
            return (updatedNotificationsstate.adhans[key] = JSON.parse(value));

          ...
        }
      });

      dispatch({
        type: actionTypes.RESTORE_NOTIFICATIONS,
        payload: updatedNotificationsstate,
      });

    };
    RestoreState();

  }, []);

  ---

  return (
    <Layout>
    ..
    </Layout>
  );
};

export default Home;

what am i doing wrong here???
Please note I have removed typesrcipt types for javascript coders convenience.

A: updatedNotificationsstate.adhans[key] = JSON.parse(value) looks to be a mutation.
You've correctly created a shallow copy of updatedNotificationsstate but all the elements are still references to the originals in state, i.e. updatedNotificationsstate.adhans is a reference to the previous state. You must also shallow copy any nested state properties that are being updated.
if (adhanKeys.includes(key)) {
  return (updatedNotificationsstate.adhans = { // <-- new object reference
    ...updatedNotificationsstate.adhans,       // <-- shallow copy previous
    [key]: JSON.parse(value)                   // <-- update property
  });
}


text: Q: wave equation for a homegeneous prism object Are there  any textbooks showing how to get the solution to Maxwell's equation of a uniform prism object with refractive index n? I'm asking because I want to see the explicit connection between wave equation and refraction.


text:
Q: mysql triggers - limiting the amount of values stored in a column Database name: Library
Clients table:
ID_number | Surname | Forename ...

Loans table:
Loan_ID | Borrower | Book | Date

Clients ID_Number is a foreign key in Loans.Borrower
I want to limit the amount of loans per client to <= 5
So if in Borrower column an ID_Number repeats > 5 times do not insert.
How would I implement this using a TRIGGER?
So far I have :
CREATE TRIGGER limit_borrows BEFORE INSERT

ON Loans

FOR EACH ROW

BEGIN

[NO IDEA WHAT GOES HERE]

IF value in borrow column repeated > 5
Do not insert

[NO IDEA WHAT GOES HERE]

END IF;

END //

A: Here's one idea...
DROP TABLE IF EXISTS loans;

CREATE TABLE loans
(loan_id SERIAL PRIMARY KEY
,user_id INT NOT NULL
);
INSERT INTO loans (user_id)
SELECT 128
  FROM (SELECT 1) x
  LEFT
  JOIN
     ( SELECT user_id
            , COUNT(*) total
         FROM loans
        GROUP
           BY user_id
     )  y
    ON y.user_id = 128
   AND y.total >= 5
 WHERE y.user_id IS NULL;

A: You need to count the number of id's in your if statement and trigger an error so that the row is not inserted:
CREATE TRIGGER limit_borrows BEFORE INSERT

ON Loans

FOR EACH ROW

BEGIN
DECLARE _id (borrower id data type here)

SELECT borrower from loans where loan_ID = new.loan_ID into _id;

SET @count = (select count(1) from loans where borrower_id = _id ;
IF @count > 5
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'your error message';

END IF;

END //


text:
Q: D: Understanding the output of 'n' th derivative of a function involving Exp[1] I am trying to find the $n^{th$ derivate of a function involving Exp[1] as given below.
w = (a* Exp[-t Subscript[n, 1]] +
     b)/((a* Exp[-t Subscript[n, 1]] + b) + drift\[Gamma]);
D[w, {Subscript[n, 1], n}]

I get the following output after running the above code:
Inactive[Sum][a E^(-t Subscript[n, 1]) (-t)^K[1] Binomial[n, K[1]] \!\(
\*SubscriptBox[\(\[PartialD]\), \({
\*SubscriptBox[\(n\), \(1\)], n - K[1]}\)]
\*FractionBox[\(1\), \(b + drift\[Gamma] + a\
\*SuperscriptBox[\(E\), \(\(-t\)\
\*SubscriptBox[\(n\), \(1\)]\)]\)]\), {K[1], 0, n}]

Posting the picture of the output since the question is more about understanding the output than the code:

It looks like a sum of n terms with Binomial coefficients. But what does the partial derivative symbol represent?

A: Whenver output is confusing, a good place to start is to look at the InputForm or FullForm:
% // InputForm

(* Inactive[Sum][(a*(-t)^K[1]*Binomial[n, K[1]]*
  D[(b + drift\[Gamma] + a/E^(t*Subscript[n, 1]))^(-1), {Subscript[n, 1], n - K[1]}])/
  E^(t*Subscript[n, 1]), {K[1], 0, n}]*)

So, the subscript on the \[PartialD] corresponds to the 2nd argument of D, exactly, and you're taking the n-K[1]'th derivative of the expression.  You're essentially getting the generalized product rule, which is a sum with binomial coefficients.
BTW, the information about the meaning of the subscript, and related useful information, is in the Details and Options section of ref/D, near the top.


text:
Q: Multiple inheritance with same parameter names I try to use multiple inheritance. Tank is both Vehicle and Weapon:
class Weapon:
    def __init__(self, name, strength, *args, **kwargs):
        super().__init__(*args, **kwargs)

class Vehicle:
    def __init__(self, name, average_speed, *args, **kwargs):
        super().__init__(*args, **kwargs)

class Tank(Weapon, Vehicle):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

Tank(name="Moshe", average_speed=68, weight=62.5, strength=17.7)

So the Tank's MRO is [__main__.Tank, __main__.Weapon, __main__.Vehicle, object].
Unfortunately, both Weapon and Vehicle have the name parameter, so currently the following error happens:
TypeError: __init__() missing 1 required positional argument: 'name'

Is there a non-artificial way to pass it through all the superclasses?

A: I'm guessing you intend for name to mean essentially the same thing in either constructor. The first thing that comes to mind is to make a superclass that consumes it only once:
class Named:
    def __init__(self, name, *args, **kwargs):
        pass

class Weapon(Named):
    def __init__(self, strength, *args, **kwargs):
        super().__init__(*args, **kwargs)


text:
Q: I don´t understand this C program made with pointers I saw this C program that copies the first string into the second one using pointers.
void copy(char const *s1, char *s2)
{
    for(;(*s2=*s1);++s1,++s2){};
}

I don´t understand the condition that stops the for loop, because I could have written (*s2=*s1)!='\0'and it works, but if I don´t write the !='\0' it works too. How does the for loop know when to stop?

A: A character between single quotes is a char. The char \0 has a value of 0 thus
char a = '\0`;

is equal to
char a = 0;

And thus if (x != '\0') is equal to if (x != 0), which is equal to if (x) similar in the condition as part of for.

A: The parentheses are indicating that the test criteria is the result of the assignment to the location pointed to by s1 (the left operand). In other words, the loop runs until the value of *s2 is false.
(*s2=*s1)!='\0' is equivalent to (*s2=*s1)!=0, which is equivalent to (*s2=*s1); or (*s2=*s1)==true if you prefer. Obviously a non-zero value is evaluated as true, so the loop runs until the second string has a nul terminator.

A: This gets at the heart of how C distinguishes between true and false.
True is any non-zero value (any bit on in an integer). While the condition tests like == and > produce a value of 1 any non-zero value works for true.
False is a value of zero (all bits off in an integer), which includes NULL in pointers.
The value of '\0' is of course a binary zero so the (*s2++=*s1++)  in the condition part of the for does an implicit test for non-zero so this works up, and until, the \0 is copied. The \0 returns false and exits the loop.  Adding your own !='\0' is adding an explicit test for the same.
Beware: If you just used an incorrect *s1++ = *s2++ != '\0' without the parenthesis it would be treated as a very buggy *s1++ = (*s2++ != '\0') which would assign a series of 1's to *s1 followed by a '\0' to terminate the "string". Oops.


text:
Q: Find all continuous functions $f(x)^2=x^2$ Find all functions $f$ which are continuous on $\mathbb R$ and which satisfy the equation $f(x)^2=x^2$ for all $x \in \mathbb R$.
Clearly $f(x)=x, -x, |x|, -|x|$ all satisfy the condition. However, how can I show that these must be the only possible choices? The condition guarantees that $|f(x)|=|x|$, for all $x$ so I think it's quite obvious that these four choices are the only possibilities. But I don't see why continuity is necessary. If $f$ does not need to be continuous, are there other possibilities? Then how can I use continuity to guarantee that these are the only choices?

A: From $f(x)^2 = x^2$ follows "only" that $f(x) = x$ or $f(x) = -x$ for each $x \in \mathbb R$. Without the continuity requirement, you could choose from both
possibilities for each $x$ independently. For example,
$f(x)=x$ if $x$ is rational and $f(x)=−x$ if $x$ is irrational.
So what you need to show is that either
$$
  f(x) = x \text{ for all } x > 0
$$
or
$$
  f(x) = -x \text{ for all } x > 0 \, .
$$
and this follows from the continuity: If there were $x_1, x_2 > 0$ such that
$f(x_1) = x_1 > 0$ and $f(x_2) = -x_2 < 0$ then because of the Intermediate Value Theorem
there would be a $x_3 > 0$ such that $f(x_3) = 0$, contradicting
the requirement $f(x_3)^2 = x_3^2$.
For the same reason you have either
$$
  f(x) = x \text{ for all } x < 0
$$
or
$$
  f(x) = -x \text{ for all } x < 0 \, .
$$
This gives the four possible functions $f(x)=x, -x, |x|, -|x|$.

A: As you mention, for any $x\in \mathbb{R}$, $f(x) = \pm x$. Let $S$ denote the set on which $f(x) = x$, and $T$ be the set where $f(x) = -x$, then $S$ and $T$ are both closed and $S\cap T = \{0\}$.
Suppose $0 < x\in S$, then $f(x) > 0$, so by continuity, $f$ must be positive on a neighbourhood of $x$. Since $f(y) = \pm y$ on that neighbourhood, it follows that $f(y) = y$. Hence, $S\setminus \{0\}$ is an open set. Similarly, $T\setminus\{0\}$ is an open set.
By connectedness of $(-\infty,0)$, it follows that either $(-\infty,0) \subset S$ or $(-\infty,0) \subset T$. Similarly, for $(0,\infty)$, which gives the four different possibilities.


text:
Q: Erlang Phash implementation I'm trying to reproduce the exact behavior of Erlang phash in another language (Ruby for example). Does anyone know the details of its implementation?
Basically, if in Erlang :
erlang:phash(X, n) -> Y
I want that
phash(X,n) = Y  in Ruby.

A: To see how it works, check the original code: https://github.com/erlang/otp/blob/cbd1378ee1fde835e55614bac9290b281bafe49a/erts/emulator/beam/utils.c#L644
But you cannot have "exact" behaviour of phash in another language - simply because you don't have erlang's datatypes available there. (unless you create your own mappings of course)


text:
Q: Drop Down List (in Update Panel) causing FULL PostBack! I have a problem with my AJAX and ASP.NET 3.5 :(
Problem is really weird, as I'm using the same thing on different page and it works fine in there, but on this specific page, this is not working.
Here's what I have:
    <asp:UpdatePanel ID="upMain" runat="server" UpdateMode="Conditional" Visible="true" RenderMode="Inline">
                <ContentTemplate>
<asp:DropDownList ID="ddlNewService_PortTelco" runat="server" Width="250" CssClass="dropdown" AutoPostBack="true" OnSelectedIndexChanged="Provision_PortedTelcoChanged"></asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>

On the way before the DropDown there is one DIV (html one), and then few asp:Panels.
I do not understand why this is causing a FULL POST BACK ?!
Any ideas ? Thanks

A: You have your drop down list with an AutoPostBack set to true. That's why you have it post back instead of AsyncPostBack, if that is what you wanted.
Remove the AutoPostBack=true from the dropdownlist
and set an Async trigger for your UpdatePanel set to the dropdownlist and its eventname="SelectedIndexChanged"

A: Me having the same problem...
CHECK your WEB.CONFIG
<xhtmlConformance mode="Legacy"/>

for this line.. and JUST REMOVE IT!!
Worked for me. Thanks http://andrew-murphy.co.uk/?p=152

A: i had the same problem... altho it's not showing in the copied code here, check to make sure you don't have any controls with ClientIDMode=Static within the updatepanel .... make them inherit
at least any controls that may trigger a postback

A: Excuse my lack of programing skills :| It all worked all the time, but because one of the actions page "looked" like it's POST BACKED, when it wasn't. What a shame!!!
Sorry for waisting Your time!

A: Setting the AutoPostBack attribute to true should be enough to cause a partial postback but it's not what happens and a full postback is triggered instead as you correctly described.
The following workaround works for me:

*

*Drop the AutoPostBack attribute.

*Trigger the postback using the "onchange" client side event.

This is how the original DropDownList should look like:
<asp:DropDownList ID="ddlNewService_PortTelco" runat="server" Width="250" CssClass="dropdown" OnChange="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(this.name, '', true, '', '', false, true))" OnSelectedIndexChanged="Provision_PortedTelcoChanged"></asp:DropDownList>

For more details regarding the WebForm_PostBackOptions parameters see below:
function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit)

http://msdn.microsoft.com/en-us/library/system.web.ui.postbackoptions_members(v=VS.90).aspx

A: If you have some asp component with Autopostback="true" and ClientIdMode="Static", you have to use the trigger.
Like this:
<asp:UpdatePanel ID="upPrinceOffuce" runat="server">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ddlPrintOffice" EventName="SelectedIndexChanged" />
    </Triggers>
    <ContentTemplate>
         <asp:DropDownList ID="ddlPrintOffice" runat="server" ClientIDMode="Static" AutoPostBack="true" ...blah blah
</asp:DropDownList>
    </ContentTemplate>
</asp:UpdatePanel>

A: How do you bind your DropDown? The code that you have provided works on my side with static items. Perhaps it is something in the other controls that is causing the problem.
I have noticed that your UpdatePanel has its UpdateMode property set to conditional, however you haven't defined any triggers.You can try to explicitly set that the update panel should perform async postback when your dropdown triggers its selectedIndexChanged event. You can use something like the following markup:
<asp:UpdatePanel ID="upMain" runat="server" UpdateMode="Conditional" Visible="true"
    RenderMode="Inline">
    <ContentTemplate>
        <asp:DropDownList ID="ddlNewService_PortTelco" runat="server" Width="250"
            AutoPostBack="true" OnSelectedIndexChanged="Provision_PortedTelcoChanged">
        </asp:DropDownList>
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ddlNewService_PortTelco" EventName="SelectedIndexChanged" />
    </Triggers>
</asp:UpdatePanel>

A: Set AutoID value to ClientIDMode property. It worked for me. I have had different behaviour in different browsers (i.e. Google chrome and Firefox).

A: Had the same problem when the Dropdownlist Autopostback attribute was set to true
and fixed the problem by adding the dropdownlist ID to the updatepanel trigger

A: I had this problem. My Dropdownlist was inside of an HTML table and I had my Update Panel wrapped around two individual rows. I fixed the problem by wrapping the Update Panel around the entire table rather than just the two rows.

A: One alternative to fix this issue is:
Declare the library
using AjaxControlToolkit;

Then you can do something on these lines
private void InitControl()
{
            //FIX - DROP DOWN
            ToolkitScriptManager scrManager = (ToolkitScriptManager)Page.Master.Controls[0].Controls[0].FindControl("manScript");
            scrManager.RegisterAsyncPostBackControl(ddlNewService_PortTelco);
}


text:
Q: Firebase Remote Config crashing when getting value. Not key value coding-compliant I'm following the documentation for setting up Firebase for iOS.
remoteConfig = RemoteConfig.remoteConfig()
remoteConfig.setDefaults(fromPlist: "FirebaseRemoteConfigDefaults")
let settings = RemoteConfigSettings()
settings.minimumFetchInterval = 0
remoteConfig.configSettings = settings
print("Remote Config Response:\(self.remoteConfig.value(forKey: "OnboardingGroup"))")

Then it crashes when trying to get the value saying "this class is not key value coding-compliant for the key OnboardingGroup.'"
Not really sure where I might be going wrong. Would appreciate any help with this.
Here is my FirebaseRemoteConfigDefaults.plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>OnboardingGroup</key>
    <string>group-1</string>
</dict>
</plist>

but it also crashes when setting the value manually.

A: Turns out I needed to use configValue(for: key) instead of value(for: key). Leaving this here in case anybody else runs into this.


text:
Q: How to set the ispell dictionary for all files below a specific directory How do I (automatically) set the dictionary (e.g. through an automated call to ispell-change-dictionary) to a specific language for every file below a particular directory?
Example: I'd prefer my standard directory language to be American English (e.g. by setting (setq ispell-dictionary "en_US-wo_accents") in my .emacs file) but I'd like to use British English for all files below (or: under) the directory /home/werner/dissertation/. And perhaps to Dutch for all files under /home/werner/letters/.
I am aware of the solution that prescribes to use -*- ispell-dictionary: "english" -*- at the first line of a file to set the dictionary for that particular file (described at EmacsWiki.org). I'd like to prevent to have to put this line on top of every new file that I make.

A: You can use something like (but this approach is more useful when you want to make something complex for given files):
(defun set-dictionary-hook ()
  (when (and (stringp buffer-file-name)
     (string-match "/dissertation/" buffer-file-name))
    (setq ispell-local-dictionary "ru")))
(add-hook 'find-file-hook 'set-dictionary-hook)

or you can specify it in .dir-locals.el as described in Emacs Manual - I think, that this will simpler than first approach, something like:
((tex-mode . ((ispell-local-dictionary . "english"))))

for files with specific modes, or
((nil . ((ispell-local-dictionary . "english"))))

for all files


text:
Q: Route domain to mac address I have router running OpenWrt 21.02.3. I also have a server that connects to this router via Ethernet. Other machines connect via Wifi.
The server is internal, so it's only meant to be accessible from inside my home LAN. Typing IP addresses is annoying, so I decided to give it a domain, say example.com. I've been adding 192.168.1.100 example.com to hosts files of each machine for the domain to work. That example.com happens to resolve in public DNS is irrelevant to me, I would like all requests to example.com on my LAN to effectively be hijacked and sent to my server.
I have found that OpenWRT actually has a feature where I can assign a static lease to this machine. This is nice since now I don't have to configure the server to request a specific IP. But it is still annoying that there has to be the one static IP reserved fo rit.
Instead I would like OpenWRT to automatically send example.com requests to this machine, regardless of what IP it happens to have. I can see how this would be possible by identifying the machine on the basis of its MAC address, or its hostname. Is there a simple way to accomplish this?


text:
Q: JS array recursion Please help, I have an array of objects, and when create new object I need to check if field "mandalority" not equal "id" and does not exist Objects which "id = 'mandalority of previous\parent objects'" and "mandalority = ID previous\parent objbjects".
In this example: if first obj(id5) mandatory "5" - an error,
if third obj(id3) mandatory "5" - an error,
if fourth obj(id1) mandatory "5" or "3" - an error.

[{
    id: 5,
    mandatory: 3
  },
  {
    id: 4,
    mandatory: 3
  },
  {
    id: 3,
    mandatory: 1
  },
  {
    id: 1,
    mandatory: null
  },
]

Sorry if the question is not clear, this is my first one, this picture will help explain
[1]: https://i.stack.imgur.com/rwR90.png

A: Could you describe what end result you are trying to achieve.
Let's say we add object { id: 3, mandatory: null }.
You want this to throw an error since id: 3 exists right?
Object { id: 5, mandatory: 5 } is also a bad example because mandatory equals or is greater than id right?
so the mandatory field has to be an existing id before creation, it cannot point to itself (first check) and the id has to be unique.
This extra check to see if the id and mandatory are not creating an infinite loop is wasted since this is not possible to create when we do our first check.
const arr = [{
  id: 5,
  mandatory: 3
},
{
  id: 4,
  mandatory: 3
},
{
  id: 3,
  mandatory: 1
},
{
  id: 1,
  mandatory: null
}]

function addItem(id, mandatory) {
  const entry = {
    id,
    mandatory
  }

  // check if id does not already exist, and the mandatory feld is an existing id
  if (arr.some(e => e.id === id)) {
    console.log(`The following entry ${JSON.stringify(entry)} contains a duplicate id field: ${id}`)
    return false
  }
  // check if mandatory field is an existing id
  if (!arr.some(e => e.id === mandatory)) {
    console.log(`The following entry ${JSON.stringify(entry)} contains an invalid mandatory field: ${mandatory}`)
    return false
  }

  console.log('pusing entry ', entry)
  arr.push(entry)
  return true
}

console.log(arr);

addItem(5, 3) // duplicate id
addItem(6, 7) // invalid mandatory > id
addItem(6, 4) // correct

console.log(arr);

Output:
[
  { id: 5, mandatory: 3 },
  { id: 4, mandatory: 3 },
  { id: 3, mandatory: 1 },
  { id: 1, mandatory: null }
]
The following entry {"id":5,"mandatory":3} contains a duplicate id field: 5
The following entry {"id":6,"mandatory":7} contains an invalid mandatory field: 7
pusing entry  { id: 6, mandatory: 4 }
[
  { id: 5, mandatory: 3 },
  { id: 4, mandatory: 3 },
  { id: 3, mandatory: 1 },
  { id: 1, mandatory: null },
  { id: 6, mandatory: 4 }
]

Updated code after remarks:
const arr = [{
  id: 5,
  mandatory: 3
},
{
  id: 4,
  mandatory: 3
},
{
  id: 3,
  mandatory: 1
},
{
  id: 1,
  mandatory: null
}]

function updateMandatory(id, mandatory) {
  // get entry form arr
  const entry = arr.find(e => e.id === id)

  if (entry) {
    // check if mandatory field is an existing id
    let mandatoryEntry = arr.find(e => e.id === mandatory)
    if (!mandatoryEntry) {
      console.log(`The following entry ${JSON.stringify(entry)} contains an invalid mandatory field: ${mandatory}`)
      return false
    }
    // check recursion
    var endSearch = mandatoryEntry.mandatory === null
    while (!endSearch) {
      if (mandatoryEntry.mandatory === id) {
        console.log(`Loop detected for entry ${JSON.stringify(mandatoryEntry)}`)
        return false
      }
      mandatoryEntry = arr.find(e => e.id === mandatoryEntry.mandatory)
      var endSearch = mandatoryEntry.mandatory === null
    }

    entry.mandatory = mandatory
    return true
  }

  console.log(`The entry with id: ${id} does not exist!`)
  return false
}

function addItem() {
  const lastId = Math.max(...arr.map(e => e.id))
  const entry = {
    id: lastId + 1,
    mandatory: null
  }

  console.log('pusing entry ', entry)
  arr.unshift(entry)
  return true
}

console.log(arr)

addItem()
updateMandatory(6, 5)
updateMandatory(5, 6)

console.log(arr)

Updated output:
[
  { id: 5, mandatory: 3 },
  { id: 4, mandatory: 3 },
  { id: 3, mandatory: 1 },
  { id: 1, mandatory: null }
]
pusing entry  { id: 6, mandatory: null }
Loop detected for entry {"id":6,"mandatory":5}
[
  { id: 6, mandatory: 5 },
  { id: 5, mandatory: 3 },
  { id: 4, mandatory: 3 },
  { id: 3, mandatory: 1 },
  { id: 1, mandatory: null }
]

A: You should make two variables, one for id and one for mandatory.
Each time you create an object you set the id and mandatory as the variables you made and  increase the variables by 1 so the next time you make an object it will have a unique I'd.


text:
Q: Oracle.ManagedDataAccess.Client is already defined - Updates may only occur at the configuration level where it is defined I have written an app that uses Oracle.ManagedDataAccess and sent the app (the bin/Debug folder to be precise) to another company. Now, when they start the app they get the following error:

System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Section or group name 'oracle.manageddataaccess.client' is already defined. Updates to this may only occur at the configuration level where it is defined.

There seems to be something very basic about those NuGet packages or the Oracle package in particular that I do not understand. The Oracle.ManagedDataAccess.dll is in the folder I sent to the other company. My understanding was that once an appropriate .NET version is installed on their computers, my app must run regardless of what else is installed on the machine. But the error message sounds to me like some other app also works with Oracle.ManagedDataAccess and is somehow considered the master for it and doesn't allow my app to run? This must be a misunderstanding on my part, but what what else could that message mean?
Sorry for sounding stupid. I know, it is most likely that I made some mistake myself, for how could Windows allow another app to rule mine? Could someone please explain what the error message means and what I can do to make my app run on any company's computers?


text:
Q: Angular 6 project with libraries using rxjs5 I'm trying to my project to newer Angular version. Newer Angular use rxjs 6, but my project uses some third party's libraries which still use rxjs5. How to deal with this case?
Many thanks!

A: I recommend you that when update your angular version you also do it with the rxjs version separately to see if that works.
npm update rxjs@version

In version, you should choose any version, for example:
npm update rxjs@6.0.0

Let me know if its work


text:
Q: Reduce flickering in vlc i am doing vlc integration in my Xcodeproject(Objective c). I used MobileVlcKit.framework version 2.2.0-git Weatherwax.
It can be seems that some flickering during play.
How to avoid flickering in vlc??  Can you suggest any parameter that can be changed in order to reduce flickering??


text:
Q: Update Wiki pages to display SharePoint Fields and not break Site Definition I have a requirement to display SharePoint fields as a footer on only certain pages, so this rules out a master page change, and I haven't had any success with plain-old HTML.
What I'm trying to display is the following code:
<SharePoint:DeveloperDashboard runat="server"/>

<SharePoint:CreatedModifiedInfo ControlMode="Display" runat="server">
<CustomTemplate>

Page Contact: <SharePoint:FormField FieldName="Page Contact" runat="server" ControlMode="Display" DisableInputFieldLabel="True" />

Last modified on <SharePoint:FieldValue FieldName="Modified" runat="server" ControlMode="Display" DisableInputFieldLabel="True" />
        by <SharePoint:FormField FieldName="Author" runat="server" ControlMode="Display" DisableInputFieldLabel="True" />

Comments: <SharePoint:FormField FieldName="Check In Comment" runat="server" ControlMode="Display" DisableInputFieldLabel="True" />
        </CustomTemplate>
        </SharePoint:CreatedModifiedInfo>

When editing the page in Advanced Mode, no matter where I place the code, I break site definition. Is there a good place to insert this code in the page? Or does the Site Definition need to be changed.

A: Breaking the Site Definition may not be what you are thinking. It is just saying to you that the page is not one of the 'defaults' anymore, as a way to identify what have been customized on the site.
Every edit you make on those pages are like that, so it is OK to get that message. You may also "reset to site definition" when you want to, but this is not usually very stable on my experience.


text:
Q: Express-Session, Passport application not sending cookies to browser My front-end is react, and my backend is express, using passport, mongoose, express-session, and cors.
I'm able to authenticate using a passport local strategy, but the session data isn't being sent to my browser. When I login, the api from the backend is able to recognize the user object, as when I console log req.session, the data appears. As soon as I change routes, I'm unable to access the req.user in my backend however. I've tried rearranging the middleware, but I don't seem able to get a browser cookie from my backend. They use separate ports on my localhost
server.js:
    //code needed to make express application
const express=require('express');
const app= express();
//required to read from .env file(env variable, holds mongo_uri and port number as process.env.PORT)
require('dotenv').config();
//connects to our mongodb using link from .env file
const mongoose= require('mongoose');
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
//our session storage, basically lets us do other things when we are logged in, rather than us being insta logged out. it uses cookies to do so
const session=require('express-session');
//our user authentication package
const passport=require('passport');
//cors is middleware, allows us to develop with server and localhost
const cors= require('cors');
app.use(cors({
    origin:"http://localhost:3000",
    credentials: true,
    methods:"GET,POST"
}))

const MongoStore=require('connect-mongo')(session);
const store=new MongoStore({url:process.env.MONGO_URI});
//parses anything that comes out of req.body as json
app.use(express.json());
app.use(express.urlencoded({extended: true}));

//boilerplate used by socket.io. better than websockets bc it can reconnect, long-polling fallback, packets are buffered
const http=require('http').createServer(app);
const io= require('socket.io')(http);

const cookieParser=require('cookie-parser');
app.use(cookieParser(process.env.SESSION_SECRET));

app.set('trust proxy', 1)
app.use(session({
    secret: process.env.SESSION_SECRET,
    resave:false,
    saveUninitialized:false,
    key:'express.sid',
    store:store,
}))

app.use(passport.initialize());
app.use(passport.session());

//the routes.js file, this is where the client gets data from
var routes=require('./routes.js');
app.use('/',routes);
require('./auth')(passport);

const PORT=process.env.PORT||5000;

http.listen(PORT,()=>{
    console.log(`Server started on ${PORT}`);
});

front end code from port 3000:
const response= await fetch("http://localhost:5000/api/profile",{
    method:"POST",
    credentials:'include',
    headers:{
      'accepts':'application/json',
    },
  })
  const data=await response.json();
  setProfileName(data.username);
  console.log(data.username);
  }

routes.js:
    const express=require('express');
    var router=express.Router();
    const passport=require('passport');
    const bcrypt=require('bcrypt');
    //our usermodel, its used to connect to mongo, and post/ update user info like registering, finding a user w/ those credentials, etc
    const userModel = require('./models/userModel');
    const ensureAuthenticated=(req,res,next)=>{
        if(req.isAuthenticated){
            return next();
        }
        res.redirect("/");
    }
    //register
    router.post('/api/register',async (req,res)=>{
        const User=await userModel.findOne({
            username: req.body.username,
        })
        if(User){
            res.json({status:"already has a user w/ that name"})
        }
        else{
            const hashedPassword=await bcrypt.hash(req.body.password,12);
            const newUser= await userModel.create({
                username: req.body.username,
                password: hashedPassword
            })
            res.json({status:"created"})
        }
    });
    //login
    router.post('/api/', async(req,res, next)=>{
        passport.authenticate("local",(err,user,info)=>{
            if(err){
                throw err;
            }
            if(!user){
                res.json({status:"no user with those credentials found"});
            }
            else{
                req.logIn(user,err=>{
                    if(err){
                        throw err;
                    }
                    req.session.user=user;
                    console.log(req.session);
                    console.log(user);
                    res.json({status:"successfully authenticated",user:user, requestSessionId:req.session.id});
                })
            }
        })(req,res,next);
    });

    router.post('/api/profile', ensureAuthenticated, async(req,res)=>{
        console.log(req.user);
        console.log(req.session.user);
        res.json({user:req.user});
    })

    module.exports=router;
auth.js
//all of our authentication stuff is in here
const LocalStrategy=require('passport-local').Strategy;
const userModel=require('./models/userModel');
const bcrypt=require('bcrypt');

module.exports=(passport)=>{
    passport.serializeUser((user,done)=>{
        done(null, user.id);
    })
    passport.deserializeUser((_id,done)=>{
        userModel.findById(_id,(err,user)=>{
            done(err,user);
        })
    })
    passport.use(
        new LocalStrategy((username,password,done)=>{
            userModel.findOne({username:username}, (err,user)=>{
                if(err){
                    throw err;
                }
                if(!user){
                    return done(null,false);
                }
                bcrypt.compare(password,user.password,(error,result)=>{
                    if(error){
                        throw(error)
                    }
                    if(result){
                        return done(null,user);
                    }
                    return done(null,false);
                })
            })
        })
    );
}


text:
Q: finding the surface where curve is given as geodesics the parametric equation of the following curves can be given by
(1) Astroid :-$(a \cos^3 t , a \sin^3 t)$
(2) Cardioid:- $(a(2\cos t-\cos 2t), a(2\sin t-\sin 2t))$
(3) Deltoid :- $(2a\cos t+a\cos 2t , 2a\sin t-asin 2t)$
Can someone tell are there any surfaces in which they becomes geodesics of the surfaces. thanks for your precious time.

A: HINT:
a) All cylindrical  surfaces "vertically extruded" by parameter $u$ are  (trivial) examples .
(1) Astroid cylinder :-$(a \cos^3 t , a \sin^3 t, b u ) = ( X(t),Y(t), b u ) $
(2) Cardioid cylinder :- $(a(2\cos t-\cos 2t), a(2\sin t-\sin 2t, b u ))$
(3) Deltoid cylinder :- $(2a\cos t+a\cos 2t , 2a\sin t-a \sin 2t, b u)$
b) All surfaces of revolution obtained by rotating through angle $u$ on one of above axes $X(t),Y(t)$  which make up the meridians.
$$ (X(t) \cos u, X(t) \sin u, Y(t) ) $$
and to it we may also add helices
$$ (X(t) \cos u, X(t) \sin u, b u  ) $$


text:
Q: Sessions connected to a pluggable database in Oracle 12c Is there a way of identifying the connections made to a pluggable Oracle database? I can use the v$sessions and v$process views, but this seems to show all sessions within the container and all pluggable databases (with no indication on those views as to which database the session is linked to).
Any ideas?

A: You can use the column SERVICE_NAME of v$session to identify to which service a session is connected to. Each PDB has at least one service name.
You can set more than one service name for a PDB but this might still help.


text:
Q: Properly mocking libraries/methods with Jest I'm trying to write a unit test for a method and I'm having some trouble getting things to run smoothly.
I need to test the only public method in this class, AuthenticateAdminService.authAdmin, which makes calls to the private methods, which make calls to third party libraries like jsonwebtoken and bcrypt. The prolem I'm running into is when I try to compare passwords with bcrypt it returns as false during automated-tests but true during manual-testing.
How am I supposed to reliably mock these private methods and libraries? I found a few posts here on SO that did nothing for me, perhaps I just didn't understand the answers. I found this post on mocking libraries which really helped for a moment until I realized that any library I'm using is wrapped inside a private method which does me no good in my tests as I'm not directly calling the mocked library.
I think I'm supposed to create a mock of the AuthenticateAdminService class private methods. Test the actual public method, authAdmin, and somehow get the mocked private methods called instead of the real versions. Any help?
AuthenticateAdminService
class AuthenticateAdminService {

  public static async authAdmin(reqBody: RequestBody, AdminModel: AdminModel): Promise<object> {
    const { username, password } = reqBody
    const adminRow: AdminRow = await AdminModel.findOne({ where: { username } })
    let token: { token?: string } = {}
    if (adminRow !== null) {
      token = await AuthenticateAdminService.checkIfPasswordsMatch(password, adminRow)
    }
    return token
  }

  private static async checkIfPasswordsMatch(plainPassword: string, adminRow: AdminRow): Promise<object> {
    const isPasswordsMatch = await Promise.resolve(bcrypt.compare(plainPassword, adminRow.password))
    let token: object = {}
    if (isPasswordsMatch) {
      const admin: object = AuthenticateAdminService.removePasswordPropFromAdminRow(adminRow)
      token = { token: await AuthenticateAdminService.createToken(admin) }
    }
    return token
  }

  private static removePasswordPropFromAdminRow(adminRow: AdminRow): object {
    const { password, ...admin } = adminRow.dataValues
    return admin
  }

  private static async createToken(admin: object): Promise<string> {
    const token: string = await Promise.resolve(jwt.sign({ admin }, 'expressadminarea'))
    return token
  }

}

AuthenticateAdminService.test.js (fails)
import { AuthenticateAdminService } from '../../src/services/AuthenticateAdminService/AuthenticateAdminService'

type AdminModel = {
  findOne(where: object): AdminRow
}

type AdminRow = {
  password: string
  dataValues: { password: string }
}

test('authAdmin', async () => {
  const reqBody: { username: string, password: string } = { username: 'foo', password: 'foo' }
  const adminModel: AdminModel = { findOne: (_where) => <AdminRow>{ password: 'foo', dataValues: { password: 'foo' } } }
  const token: { token?: string } = await AuthenticateAdminService.authAdmin(reqBody, adminModel)

  expect(typeof token).toBe('object')
  expect(typeof token.token).toBe('string')  // token.token is undefined
  expect(token.token.length).toBeGreaterThan(0)
})

A: Looks like you just need to mock your adminModel with a password hash instead of the plaintext password:
test('authAdmin', async () => {
  const reqBody: { username: string, password: string } = { username: 'foo', password: 'foo' }
  const hash = await bcrypt.hash('foo', 10);  // create a hash
  const adminModel: AdminModel = { findOne: (_where) => <AdminRow>{ password: hash, dataValues: { password: hash } } }  // use the hash
  const token: { token?: string } = await AuthenticateAdminService.authAdmin(reqBody, adminModel)

  expect(typeof token).toBe('object')
  expect(typeof token.token).toBe('string')  // Success!
  expect(token.token.length).toBeGreaterThan(0)
})

Also, bcrypt.compare returns a Promise so you can simplify that line:
const isPasswordsMatch = await bcrypt.compare(plainPassword, adminRow.password);