text:
Q: Java Hibernate / Spring, doing partial match query ("contains")? I'm still fairly new to hibernate and can't seem to find how to do this, maybe I'm searching using the wrong terminology. I am passing in a user provided value from my UI, in the example below this is the variable testvalue. It is for doing a search so if what the user enters is contained anywhere in an entry e.filenametxt I want it to return that row as a match.
For example, testvalue = "file1", I would want it to be able to find a row where e.filenametxt = "file1/someotherinfo/"
String SQL_QUERY = "from EdrmTest e where e.filenametxt is :foreignkeytest ";
Query query = session.createQuery(SQL_QUERY);
query.setParameter("foreignkeytest", testvalue);

Any advice is appreciated.

A: String SQL_QUERY = "from EdrmTest e where e.filenametxt LIKE :foreignkeytest ";
Query query = session.createQuery(SQL_QUERY);
query.setParameter("foreignkeytest", "%" + testvalue + "%");\

Try that.  The wild cards need to be in the variable (for some reason).

A: You can also use the Criteria API to set these types of clauses programatically; sometimes it can be much nicer to handle queries with this API as opposed to a HQL/String based query if you need to add any sort of dynamic logic (i.e. include certain clauses based on a condition).
Criteria crit = session.createCriteria(EdrmTest.class); //the persistent class goes here
crit.add( Restrictions.like("filenametxt", testvalue + "%") );
//execute the query:
List<EdrmTest> results = (List<EdrmTest>) crit.list();


text:
Q: UITableViewHeaderFooterView contentView is not setting to transparent I've a ViewController with a background image which as a TableVC as its subview.
I want the table view to be transparent and have accomplished that, also the tableviewcell's are transparent. But I'm facing a difficulty in getting the tableviewheaderfooterview to be transparent, as when i set it's contentview backgroundcolor to clearColor - it shows a gray color.
I'm using Xcode 7.3.1
private let collapsibleTableView : UITableView = {
   let tv = UITableView()
    tv.translatesAutoresizingMaskIntoConstraints = false
    tv.backgroundColor = .clearColor()
    tv.backgroundView = nil
    tv.separatorStyle = .None
    return tv
}()

Also, I've subclassed UITableViewHeaderFooterView to my custom class and where I also tried setting the contentView background color to clearColor
override func layoutSubviews() {
        super.layoutSubviews()
        contentView.backgroundColor = .clearColor()
}

Also, I've tried to set it again in my VC file
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier("header") as? CustomTableViewHeader ?? CustomTableViewHeader(reuseIdentifier: "header")
        header.contentView.backgroundColor = .clearColor()
        header.titleLabel.text = "custom-text"
        header.delegate = self
        return header
    }

Also, I've set the tableviewcell's background to transparent too
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

            cell.backgroundColor = .clearColor()
            cell.contentView.backgroundColor = .clearColor()
}

But no matter what I do, the background of the headerview will not be transparent.

EDIT: I also found this post about the same problem here on SO, but implementing the proposed solution, isn't working
 header.contentView.layer.backgroundColor = UIColor.clearColor().CGColor

A: Try this, change the background color to your headerView directly instead of change the color of your headerView.contentView, for me works this example
 public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50))
        view.backgroundColor = UIColor.clear
        return view
    }

So change your code in the  public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? method to this
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier("header") as? CustomTableViewHeader ?? CustomTableViewHeader(reuseIdentifier: "header")
        header.backgroundColor = UIColor.clearColor()
        header.titleLabel.text = "custom-text"
        header.delegate = self
        return header
    }

I hope this helps you

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ ICU Add Break Rule for Khmer I am trying to add better functionality to the ICU break iterator for Khmer (it uses a dictionary just like Thai).
I have a character that I always want the breakiterator to break after - but I can't figure out how to add a "rule" to the code to make it work.
The character I want to always break after is U+17CB
The U+17CB character is already contained in fEndWordSet = fKhmerWordSet; but the problem is, in the fEndWordSet it is only a possible end of a word. I need to change it to always break after the character rather than just as a possibility.
I am not very experienced, so any direction you can give would be very much appreciated!
Here's the current break iterator for Khmer (contained in dictbe.cpp - the whole source can be viewed here):
// How many words in a row are "good enough"?
#define KHMER_LOOKAHEAD 3

// Will not combine a non-word with a preceding dictionary word longer than this
#define KHMER_ROOT_COMBINE_THRESHOLD 3

// Will not combine a non-word that shares at least this much prefix with a
// dictionary word, with a preceding word
#define KHMER_PREFIX_COMBINE_THRESHOLD 3

// Minimum word size
#define KHMER_MIN_WORD 2

// Minimum number of characters for two words
#define KHMER_MIN_WORD_SPAN (KHMER_MIN_WORD * 2)

KhmerBreakEngine::KhmerBreakEngine(const TrieWordDictionary *adoptDictionary, UErrorCode &status)
    : DictionaryBreakEngine((1<<UBRK_WORD) | (1<<UBRK_LINE)),
      fDictionary(adoptDictionary)
{
    fKhmerWordSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Khmr:]&[:LineBreak=SA:]]"), status);
    if (U_SUCCESS(status)) {
        setCharacters(fKhmerWordSet);
    }
    fMarkSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Khmr:]&[:LineBreak=SA:]&[:M:]]"), status);
    fMarkSet.add(0x0020);
    fEndWordSet = fKhmerWordSet;
    fBeginWordSet.add(0x1780, 0x17B3);
    //fBeginWordSet.add(0x17A3, 0x17A4);      // deprecated vowels
    //fEndWordSet.remove(0x17A5, 0x17A9);     // Khmer independent vowels that can't end a word
    //fEndWordSet.remove(0x17B2);             // Khmer independent vowel that can't end a word
    fEndWordSet.remove(0x17D2);             // KHMER SIGN COENG that combines some following characters
    //fEndWordSet.remove(0x17B6, 0x17C5);     // Remove dependent vowels
//    fEndWordSet.remove(0x0E31);             // MAI HAN-AKAT
//    fEndWordSet.remove(0x0E40, 0x0E44);     // SARA E through SARA AI MAIMALAI
//    fBeginWordSet.add(0x0E01, 0x0E2E);      // KO KAI through HO NOKHUK
//    fBeginWordSet.add(0x0E40, 0x0E44);      // SARA E through SARA AI MAIMALAI
//    fSuffixSet.add(THAI_PAIYANNOI);
//    fSuffixSet.add(THAI_MAIYAMOK);

// Compact for caching.
fMarkSet.compact();
fEndWordSet.compact();
fBeginWordSet.compact();
//    fSuffixSet.compact();
}

KhmerBreakEngine::~KhmerBreakEngine() {
delete fDictionary;
}

int32_t
KhmerBreakEngine::divideUpDictionaryRange( UText *text,
                                            int32_t rangeStart,
                                            int32_t rangeEnd,
                                            UStack &foundBreaks ) const {
if ((rangeEnd - rangeStart) < KHMER_MIN_WORD_SPAN) {
    return 0;       // Not enough characters for two words
}

uint32_t wordsFound = 0;
int32_t wordLength;
int32_t current;
UErrorCode status = U_ZERO_ERROR;
PossibleWord words[KHMER_LOOKAHEAD];
UChar32 uc;

utext_setNativeIndex(text, rangeStart);

while (U_SUCCESS(status) && (current = (int32_t)utext_getNativeIndex(text)) < rangeEnd) {
    wordLength = 0;

    // Look for candidate words at the current position
    int candidates = words[wordsFound%KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);

    // If we found exactly one, use that
    if (candidates == 1) {
        wordLength = words[wordsFound%KHMER_LOOKAHEAD].acceptMarked(text);
        wordsFound += 1;
    }

    // If there was more than one, see which one can take us forward the most words
    else if (candidates > 1) {
        // If we're already at the end of the range, we're done
        if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
            goto foundBest;
        }
        do {
            int wordsMatched = 1;
            if (words[(wordsFound+1)%KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) > 0) {
                if (wordsMatched < 2) {
                    // Followed by another dictionary word; mark first word as a good candidate
                    words[wordsFound%KHMER_LOOKAHEAD].markCurrent();
                    wordsMatched = 2;
                }

                // If we're already at the end of the range, we're done
                if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
                    goto foundBest;
                }

                // See if any of the possible second words is followed by a third word
                do {
                    // If we find a third word, stop right away
                    if (words[(wordsFound+2)%KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd)) {
                        words[wordsFound%KHMER_LOOKAHEAD].markCurrent();
                        goto foundBest;
                    }
                }
                while (words[(wordsFound+1)%KHMER_LOOKAHEAD].backUp(text));
            }
        }
        while (words[wordsFound%KHMER_LOOKAHEAD].backUp(text));
foundBest:
        wordLength = words[wordsFound%KHMER_LOOKAHEAD].acceptMarked(text);
        wordsFound += 1;
    }

    // We come here after having either found a word or not. We look ahead to the
    // next word. If it's not a dictionary word, we will combine it with the word we
    // just found (if there is one), but only if the preceding word does not exceed
    // the threshold.
    // The text iterator should now be positioned at the end of the word we found.
    if ((int32_t)utext_getNativeIndex(text) < rangeEnd && wordLength < KHMER_ROOT_COMBINE_THRESHOLD) {
        // if it is a dictionary word, do nothing. If it isn't, then if there is
        // no preceding word, or the non-word shares less than the minimum threshold
        // of characters with a dictionary word, then scan to resynchronize
        if (words[wordsFound%KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0
              && (wordLength == 0
                  || words[wordsFound%KHMER_LOOKAHEAD].longestPrefix() < KHMER_PREFIX_COMBINE_THRESHOLD)) {
            // Look for a plausible word boundary
            //TODO: This section will need a rework for UText.
            int32_t remaining = rangeEnd - (current+wordLength);
            UChar32 pc = utext_current32(text);
            int32_t chars = 0;
            for (;;) {
                utext_next32(text);
                uc = utext_current32(text);
                // TODO: Here we're counting on the fact that the SA languages are all
                // in the BMP. This should get fixed with the UText rework.
                chars += 1;
                if (--remaining <= 0) {
                    break;
                }
                if (fEndWordSet.contains(pc) && fBeginWordSet.contains(uc)) {
                    // Maybe. See if it's in the dictionary.
                    int candidates = words[(wordsFound+1)%KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
                    utext_setNativeIndex(text, current+wordLength+chars);
                    if (candidates > 0) {
                        break;
                    }
                }
                pc = uc;
            }

            // Bump the word count if there wasn't already one
            if (wordLength <= 0) {
                wordsFound += 1;
            }

            // Update the length with the passed-over characters
            wordLength += chars;
        }
        else {
            // Back up to where we were for next iteration
            utext_setNativeIndex(text, current+wordLength);
        }
    }

    // Never stop before a combining mark.
    int32_t currPos;
    while ((currPos = (int32_t)utext_getNativeIndex(text)) < rangeEnd && fMarkSet.contains(utext_current32(text))) {
        utext_next32(text);
        wordLength += (int32_t)utext_getNativeIndex(text) - currPos;
    }

    // Did we find a word on this iteration? If so, push it on the break stack
    if (wordLength > 0) {
        foundBreaks.push((current+wordLength), status);
    }
}

// Don't return a break for the end of the dictionary range if there is one there.
if (foundBreaks.peeki() >= rangeEnd) {
    (void) foundBreaks.popi();
    wordsFound -= 1;
}

return wordsFound;
}


text:
Q: Responsive images and video in intro page I am designing an intro page. I place a background and video piece on that page and also I want to get the view of desktop in mobile also. i tried the following code:
css:
.trailer-content {
    max-width: 75%;
    width: 600px;
    margin-left: auto;
    margin-right: auto;

}
.video-container {
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 30px;
    height: 0;
}
.video-container iframe,
.video-container object,
.video-container embed {
    position: fixed;
    bottom:40px !important;
    width: 50%;
    height: 50%;
    margin-left: auto !important;
    margin-right: auto !important;
}
#background {
    width: 100%;
    height: 100%;
    position: fixed;
    left: 0px;
    top: 0px;
    z-index: -1; /* Ensure div tag stays behind content; -999 might work, too. */
}
.stretch {
    width:100%;
    height:100%;
}

html :

Output result

*

*the background appears stretched

*the video is normal in desktop but in mobile view, the video is also stretched to some size.

A: Responsive background image:
html {
  background: url(https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSvctt0I--skoKQVfuVt-i4Et6vQ5ve7lXPkLy9sTElCWLKh1Ps) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

See demo
Responsive video:
HTML:

CSS:
.videoWrapper {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 */
    padding-top: 25px;
    height: 0;
}
.videoWrapper iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

See demo

A: And again I must notice never use ID for styling
To resolve your case properly
Easiest way is to use @media rule w3school link
In that case you'll have any number of diffirent rules that applies to the same class but in diffirent situations.
That way is much better than just stretch video or backgrounds, because you'll have full control of all elements. They'll behave as you want them to behave at diffirent devices.

A: remove height:100% from #background... so the image will stretch 100% in width, but keep the right dimensions.
However, I think is better you put it as a background in the body like this:
body{background:url(img/bg.jpg);
background-repeat:no-repeat;
background-size:100% auto;}

For the video frame tags that holds videos, remeoving the height might scale the video properly as well.
You can also set specific width, height etc by using meidatypes, see more information about responsive webdesign (RWD) here http://www.hongkiat.com/blog/responsive-web-tutorials/


text:
Q: Make tabs appear when bars icon is clicked(responsive navbar) I created a navbar and all the tabs are inline. When the window size is reduced, a bars icon appears and the tabs display vertically instead of horizontally. I want the output so that when the window size is reduced, the bars icon appears but the tabs disappear and can only be seen (vertically) and unseen when the bars icon is clicked.
I tried jquery, but it didn't work. I'm not sure how to do this, can you help me?

body {
  margin: 0;
  padding: 0;
  font-family: Sans-Serif;
}

nav {
  margin-left: 45px;
  ;
  width: 90%;
  background: #D1D0D3;
}

ul {
  list-style-type: none;
  width: 80%;
  margin: 0 auto;
  color: black;
  padding: 0;
}

ul a {
  color: black;
  text-decoration: none;
}

ul li {
  display: inline-block;
  padding: 20px;
}

ul li:hover {
  background-color: yellow;
}

.toggle {
  width: 100%;
  padding: 10px 20px 0px 20px;
  background-color: #C2ABF1;
  text-align: right;
  box-sizing: border-box;
  color: white;
  font-size: 30px;
  display: none;
}

@media (max-width: 800px) {
  .toggle {
    display: block;
  }
  .block {
    display: block;
  }
}

Home

About

Makeup

Hairstyle

Contact

A: Add this jquery code
$(".menu").on("click", function() {
  $("nav .ul").toggle(500);
})

And this CSS in media query
.ul {
    display: none;
  }
  nav {
      margin-left: 0;
      width: 100%;
  }

$(".menu").on("click", function() {
  $("nav .ul").toggle(500);
})
body {
  margin: 0;
  padding: 0;
  font-family: Sans-Serif;
}

nav {
  margin-left: 45px;
  ;
  width: 90%;
  background: #D1D0D3;
}

ul {
  list-style-type: none;
  width: 80%;
  margin: 0 auto;
  color: black;
  padding: 0;
}

ul a {
  color: black;
  text-decoration: none;
}

ul li {
  display: inline-block;
  padding: 20px;
}

ul li:hover {
  background-color: yellow;
}

.toggle {
  width: 100%;
  padding: 10px 20px 0px 20px;
  background-color: #C2ABF1;
  text-align: right;
  box-sizing: border-box;
  color: white;
  font-size: 30px;
  display: none;
}

@media (max-width: 800px) {
  .toggle {
    display: block;
  }
  .block {
    display: block;
  }
  .ul {
    display: none;
  }
  nav {
    margin-left: 0;
    width: 100%;
  }
}

Home

About

Makeup

Hairstyle

Contact

A: Your code should be like this:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel='stylesheet' href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

Home

About

Makeup

Hairstyle

Contact


text:
Q: Maven doesn't see Spring dependencies I have a problem with Maven refusing to recognize any Spring dependencies. Even though in the POM, everything seems to be correct (nothing highlighted), if I try to compile the app, it throws an error with a message:
java: package org.springframework.boot does not exist

Also, no annotations work, my IDE simply does not see any dependency it's given and if I try to resolve it by "add dependency"... literally nothing happens. POM itself is fine, because the rest of my team encounter no problems. I have environment variables set with correct paths and options found at Settings -> Build -> Build Tools -> Maven are also set as they should be.
This is my POM (chosen fragments):
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-binder-kafka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>

A: Did you try running mvn clean package. After that reload/reimport the maven project based upon your ide settings.


text:
Q: $a_1=2$ and $a_{n+1}=2+\frac{1}{a_n}\implies |a_{n+1}-a_n|\leq\frac14|a_{n-1}-a_n|$
Let $(a_n)_{n\in\mathbb{N}}$ satisfy that $a_1=2$ and $a_{n+1}=2+\frac{1}{a_n}$. Show that
  for all $n\in\mathbb{N}$ with $n\geq 2$,
  $$
|a_{n+1}-a_n|\leq\frac14|a_{n-1}-a_n|
$$

So I can show the base case to be true, but I can't see how to show the inductive step.

A: $$\forall i\in \mathbb{N} \qquad a_{i}=2+\frac{1}{a_{i-1}}\geq2$$
$$a_{n+1}=2+\frac{1}{a_n}...(1)$$
$$a_{n}=2+\frac{1}{a_{n-1}}...(2)$$
Subtracting (2) fom (1),
$$ |a_n-a_{n-1}|=|\frac{a_n-a_{n-1}}{a_na_{n-1}}|=\frac{|a_n-a_{n-1}|}{|a_na_{n-1|}}\leq\frac{|a_n-a_{n-1}|}{2\times 2}=\frac{|a_n-a_{n-1}|}{4}$$


text:
Q: Compute the expected number of records by time n This is a problem of my homework.
An asset price is modeled by using a sequence of independent and identically distributed continuous random variables $X_1,X_2,...$, with common density function $f(x)$. We say that a record price occurs at time $n$ if $Xn >
\max(X_1,X_2,...,X_{n-1})$.
Compute $P[a\ record\ price\ occurs\ at\ time\ n]$.
Next, consider the variable $Y_i$ defined as:
$Y_i = 1$ if a record occurs at time $i$.
$Y_i = 0$ otherwise.
Give the expected number of records by time n.
I already know the probability of a record price occurs at time $n$ is $\frac{1}{n}$. And let $Z_n$ be the number of records by time n. Then $Z_n = Y_1 + Y_2 + Y_3 +...+ Y_n$. Then the expected value of $Z_n$ should be $1 + 1/2 + 1/3 +...+ 1/n$. But in my homework, my professor suggested that "do not attempt to calculate the sum". Is calculating the sum here wrong? Or there is a better way to do the problem?
Thank you!

A: You have said correctly that the expected value of $Z_n$ is the $n^{th}$ harmonic number.  You can't sum the series to infinity because it diverges, but for finite $n$ it is close to $\log n + \gamma$ where $\gamma$ is the Euler-Mascheroni constant, about $0.577$


text:
Q: Can I log SEVERE exceptions thrown by org.springframwork.jdbc? I was wondering if there is a way to tell log4j to save this kind of exceptions.
At the moment, I am seeing this errors on my Tomcat Log, but due the error level is SEVERE and log4j has no such level of errors, I am not sure if I can capture it and save it on a different file...
So far at my log4.properties I have this
log4j.rootLogger=WARN, myLog
log4j.logger.org.springframework = WARN, myLog

the exception I am seeing on my tomcat log is being thrown by this class:
org.springframework.jdbc.UncategorizedSQLException

Any idea how to capture them?

A: Log4j does not have severe but it does have fatal. Perhaps adding this to your logger will make it work?
Check this out for more:
https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Category.html#fatal(java.lang.Object)


text:
Q: Disadvantages of First-class functions Are there any disadvantages to having first class functions in a language?
Joel in this entry says

Object-oriented programming languages aren't completely convinced that
  you should be allowed to do anything with functions.

I might be naïve here, but why don't all languages support first class functions if there aren't much issues

A: In an ideal world where there was never a cost associated with developing new features, the only downside I can see to including functional programming techniques would be confusion to developers who are not familiar with functional techniques (and I don't really see that as much of a downside).
In reality, treating functions as first-class typically requires significant rewrites to the compiler itself.  The cost of doing this has to be weighed against the long-term gain.

A: Adding this feature might be a disadvantage if introducing the change requires a costly re-write of language compilers, interpreters, and other tools. It might also be a disadvantage if the language's culture is not familiar enough with the advantages provided by this feature in which case adding the feature is a waste of effort.

A: Additionally, first class functions require runtime interpretation of code and some form of garbage collection. Both of these add overhead that might not be suitable for certain problems and languages.


text:
Q: Escape New line character in Spark CSV read I'm working on Spark 2.2.1 version and using the below python code, I can able to escape special characters like @ :
I want to escape the special characters like newline(\n) and carriage return(\r). I replaced the @ which \n, however it didn't worked. Any suggestions please.
Working:
spark_df = spark.read.csv(file.csv,mode="DROPMALFORMED",inferSchema=True,header =True,escape="@")

Not Working:
spark_df = spark.read.csv(file.csv,mode="DROPMALFORMED",inferSchema=True,header =True,escape="\n")

A: If your goal is to read csv having textual content with multiple newlines in it, then the way to go is using the spark multiline option.
I recently posted some code for scala there.
val df = spark.read
.option("wholeFile", true)
.option("multiline",true)
.option("header", true)
.option("inferSchema", "true")
.option("dateFormat", "yyyy-MM-dd")
.option("timestampFormat", "yyyy-MM-dd HH:mm:ss")
.csv("test.csv")

The python syntax will be slightly different but shoud work well.

A: You can achieve this using pandas.
Sample Code:
pandas_df = pd.read_csv("file.csv")
pandas_df = pandas_df.replace({r'\\r': ''}, regex=True)
pandas_df = pandas_df.replace({r'\\n': ''}, regex=True)

You can replace any special character with the above code snippet.
Later on you can convert the pandas_df to spark_df as needed.
spark_df = sqlContext.createDataFrame(pandas_df)


text:
Q: nativescript sidedrawer doesn't work I've been trying to implement sidedrawer for a week now, I followed everything in the documentation, when i slide the screen it throws this unfriendly exception. but the problem might be ViewChild because this.sidedrawer is undefined. (the problem issued in the GitHub and there is a solution but neither of them works)
i'm using angular, so this is the component i have:
<ActionBar class="action-bar">

  <button text="List Mode" (tap)="enableListMode()"></button>
</ActionBar>

<RadSideDrawer tkExampleTitle tkToggleNavButton >
  <StackLayout tkDrawerContent class="sideStackLayout" >
    <StackLayout class="sideTitleStackLayout">

    </StackLayout>
    <StackLayout class="sideStackLayout">

    </StackLayout>

</StackLayout>
<StackLayout tkMainContent class="page">
    <MapView></MapView>
  </StackLayout>
</RadSideDrawer>

and the code:
import { Component, OnInit, ChangeDetectorRef,ViewChild } from '@angular/core';
import {registerElement} from "nativescript-angular/element-registry";
import { Router } from "@angular/router";
registerElement("MapView", () => require("nativescript-google-maps-sdk").MapView);
import { RadSideDrawerComponent, SideDrawerType } from "nativescript-ui-sidedrawer/angular";
import { RadSideDrawer } from 'nativescript-ui-sidedrawer';

@Component({
  selector: 'app-map-mode',
  moduleId: module.id,
  templateUrl: './map-mode.component.html',
  styleUrls: ['./map-mode.component.css']
})
export class MapModeComponent implements OnInit {

  private _mainContentText: string;

  constructor(private _changeDetectionRef: ChangeDetectorRef,
    private router: Router) { }

  @ViewChild(RadSideDrawerComponent) public drawerComponent: RadSideDrawerComponent;
  private drawer: RadSideDrawer;

  ngAfterViewInit() {
      //fairly certain this statement is never entered
      this.drawer = this.drawerComponent.sideDrawer;
      this._changeDetectionRef.detectChanges();
  }

  ngOnInit() {

   }

   public openDrawer() {
       console.log("Drawer method reached");
       console.log(this.drawer); //returns undefined
       this.drawer.showDrawer();
   }

   public onCloseDrawerTap() {
       this.drawer.closeDrawer();
   }
  enableListMode()
  {
    this.router.navigate(["resList"])

  }
}

the exception:

JS: Angular is running in the development mode. Call enableProdMode()
  to enable the production mode. System.err:
  java.lang.NullPointerException: Attempt to invoke virtual method 'void
  android.widget.FrameLayout.setVisibility(int)' on a null object
  reference System.err:     at
  com.telerik.android.primitives.widget.sidedrawer.RadSideDrawer.handleOnDown(RadSideDrawer.java:452)
  System.err:     at
  com.telerik.android.primitives.widget.sidedrawer.RadSideDrawer.onGesture(RadSideDrawer.java:430)
  System.err:     at
  com.telerik.android.primitives.widget.sidedrawer.RadSideDrawer.onInterceptTouchEvent(RadSideDrawer.java:420)
  System.err:     at
  android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2108)
  System.err:     at
  android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
  System.err:     at
  android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2197)
  System.err:     at
  android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
  System.err:     at
  android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2197)
  System.err:     at
  android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
  System.err:     at
  android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2197)
  System.err:     at
  android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
  System.err:     at
  android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2197)
  System.err:     at
  android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
  System.err:     at
  android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2197)
  System.err:     at
  com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2403)
  System.err:     at
  com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1737)
  System.err:     at
  android.app.Activity.dispatchTouchEvent(Activity.java:2812)
  System.err:     at
  com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2364)
  System.err:     at
  android.view.View.dispatchPointerEvent(View.java:9520) System.err:
  at
  android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4242)
  System.err:     at
  android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4095)
  System.err:     at
  android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3641)
  System.err:     at
  android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3694)
  System.err:     at
  android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3660)
  System.err:     at
  android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3786)
  System.err:     at
  android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3668)
  System.err:     at
  android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3843)
  System.err:     at
  android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3641)
  System.err:     at
  android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3694)
  System.err:     at
  android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3660)
  System.err:     at
  android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3668)
  System.err:     at
  android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3641)
  System.err:     at
  android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5938)
  System.err:     at
  android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5912)
  System.err:     at
  android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5873)
  System.err:     at
  android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6041)
  System.err:     at
  android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
  System.err:     at android.os.MessageQueue.nativePollOnce(Native
  Method) System.err:     at
  android.os.MessageQueue.next(MessageQueue.java:323) System.err:     at
  android.os.Looper.loop(Looper.java:135) System.err:     at
  android.app.ActivityThread.main(ActivityThread.java:5480) System.err:
  at java.lang.reflect.Method.invoke(Native Method) System.err:     at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
  System.err:     at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
  ActivityManager: Process org.nativescript.rest (pid 1096) has died
  ActivityManager: cleanUpApplicationRecord -- 1096


text:
Q: Create multiple background using SASS mixin I'm trying to create a mixin in Sass to generate multiple background, problem is the number of background is unknow, it's can be 3, 4 or even 5. Here what I try and fail.
@mixin multiBg($page: index, $sec: sec01,$from: 1, $to: 3, $type: jpg){
    $url: (); // i'm try to create a empty array first
    $newUrl: null; // and an empty variable
    @for $i from $from through $to {
        $newUrl: append($url, url(../img/#{$page}/#{$sec}_bg0#{$i}.#{$type})); // then append value to variable;
    }
    background: $newUrl;
}

#sec05 {
   @include multiBg(index,sec05);
}

current output:
background: url(../img/index/sec05_bg03.jpg);

expected output:
background: url(../img/sec05_bg01.jpg),url(../img/sec05_bg02.jpg), url(../img/sec05_bg03.jpg);

I don't know how to fix this problem since i'm still learing SASS. Can someone enlighten me please.

A: You're on the right track! But your syntax and logic are slightly off. Here's what I came up with:
@mixin multiBg($page: index, $sec: sec01, $from: 1, $to: 5, $type: jpg) {

  $url_list: ();

  @for $i from $from through $to {

    // I broke constructing the url and adding it to the set into two steps here.
    // We could do this all at once, but separating it can make it easier to read.

    // First, generate the url.
    $url_string: url(../img/#{$page}/#{$sec}_bg0#{$i}.#{$type});

    // Then add it to the list (the 'comma' part is important)
    $url_list: append($url_list, $url_string, comma);
  }

  // Done looping? Output the final list!
  background-image: $url_list;
}

That seems to return what you're looking for. Here are the official docs on list functions - I always forget one or two, may be useful for you too.
Also, since you mentioned you're new to sass - check out Sassmeister if you haven't already. It's a handy little sandbox for quickly prototyping and trying things out in sass; similar to Codepen but a bit more specialized. It's what I used to experiment with this question.

A: This is a cleaner answer, I believe.
@mixin image-resolve($image) {
  $images: ();

   @each $i in $image {
     $path: ();

     $images: append($images, $path, comma);
   }

 background-image: $images;
}


text:
Q: how to efficiently shorten javascript code DOM selector I'm changing the script in my project from jquery into plain js.. currently I'm doing it like this
jquery script (original)
$('.class1').show();

into vanilla javascript
const elems = document.querySelectorAll('.class1');
elems.forEach(elem => {
  elem.style.display = 'inline-block';
});

is there a more efficient and/or elegant way (but still easily understood and readable) to do this in vanilla javascript?

A: Without changing anything else, the best you could probably do is
for (const elm of document.querySelectorAll('.class1'))  {
  elem.style.display = 'inline-block';
}

Another possibility that one might prefer would be to toggle a class on a parent element and use CSS rules so that .class1 descendants get display: inline-block when that parent class is active, eg
parent.classList.add('show-children');

A: You could also create a mini-jquery drop in replacement :p
You add enough methods, you could get away with not needing to change all your jquery at once :p

const $ = (selector, root=document) => Object.assign({selected: root.querySelectorAll(selector)}, {
    show() { this.selected.forEach(e=>e.style.display='inline-block'); return this; },
    hide() { this.selected.forEach(e=>e.style.display='none'); return this; }
});
setTimeout(() => { // timeout for dramatic effect :p
  $('.class1').show();
}, 1000);
.class1 {
  display: none;
}

Hidden 1

Hidden 2


text:
Q: Make elements fixed when their bottom edge scrolls into view This one might seem complicated, I'll do my best to explain!
I'm trying to make a continuous scrolling article display along the same lines of Bloomberg Politics (http://www.bloomberg.com/politics/articles/2015-07-02/fact-checking-rick-perry-s-economic-speech), but in a slightly different format.
Instead of the next article being static until the last has scrolled away, I would like the current articles bottom edge to become sticky/fixed to the bottom of the viewport and the new article to scroll in over the top of it.
I have attempted a jsfiddle to try and illustrate where I've got to and what I mean.....

        Text text text text text text text text text

        Text text text text text text text text text

.wrapper {
    padding: 8px;
    position: relative;
}

.article {
    width: calc(100% - 48px);
    min-height: 1200px;
    background: #ddd;
    padding: 24px;
}

.article--two {
    background: #f5f5f5;
}

.scroll {
    position: relative !important;
    top: auto !important;
    margin-top: 1248px !important;
    float: left !important;
    left: 0 !important;
    right: 0 !important;
}

$(window).scroll( function() {
    $('.article').each( function(i) {
        var bottom_of_object = $(this).position().top + $(this).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();
        var height = $(this).outerHeight();
        var secondheight = $('.article--two').outerHeight();
        var down = bottom_of_object;

        if (bottom_of_window > bottom_of_object) {
            $(this).css({
                'position': 'fixed',
                'bottom': '0',
                'left': '16px',
                'right': '16px'
            });
            $('.article--two').addClass('scroll');
        }
    });
});

JsFiddle
Any help would be gratefully appreciated! Ask away of this seems a little complicated!
Cheer!

A: Not optimised, nor will it work fantastic in mobile, but it does the trick.

$window = $(window).on('scroll', function () {
    var scroll = $window.scrollTop() + $window.height();

    $('li').each(function (i) {
       var $el = $(this),
           offset = scroll - $el.offset().top - $el.height();
       $el.children().css('top', offset>0 ? offset : 0);
    });
});
body {
  margin: 0;
}
ul {
  position: relative;
  display: block;
  text-align: center;
  counter-reset: page;
  padding: 0;
  margin: 0;
}
li {
  height: 150vh;
  list-style: none;
  background: green;
  position: relative;
  margin: 0;
  padding: 0;
}
li:nth-child(even) {
  background: blue;
}
article {
  position: relative;
  height: 100%;
  width: 100%;
  background: inherit;
}
article:before {
  counter-increment: page;
  content: "Page " counter(page);
  font-size: 1.6em;
  color: white;
  top: 50%;
  margin-top: -0.5em;
  position: relative;
}


text:
Q: Convert CHAR to NUMERIC in SQL I am trying to set up a database that has the following columns, "number", "full names", "card no", "status". In the last column status there are many types of status, which I would like to have them converted to 0 or 1 to another column within the table, depending on the statuses. The database then, is to be pulled to another application and will use the binary column to give access to a facility.
I have not tried any code on this, still learning.
SELECT TOP 1000 [MemberNo]
      ,[FirstName]
      ,[LastName]
      ,[CardNo]
      ,[Status]
  FROM [GateAccess].[dbo].[GateProxy]

A: Not sure why ask a question when you havent tried anything...
First you are trying to create a table with following columns not a database.
Here is a link of how to create a table http://www.mysqltutorial.org/mysql-create-table/
Second you dont really need to to convert char to numeric I would personally use CASE
here is a link on case https://www.techonthenet.com/mysql/functions/case.php
Regarding to your 'application and will use the binary column to give access to a facility' it depends on what application is pulling the data.

A: This may help ...
DECLARE  @sampletext VARCHAR(100) = '123456';
SELECT TRY_CONVERT(INT, @sampletext); -- 123456
SELECT TRY_CAST(@sampletext AS INT); -- 123456

SELECT TOP 1000 [MemberNo]
      ,[FirstName]
      ,[LastName]
      ,[CardNo]
      ,[Status]
      -- Try like this for new derived column
      ,CASE WHEN [Status] = 'yourValue'THEN 1
            WHEN  [Status] = 'yourOtherValue' THEN 0
       END
  FROM [GateAccess].[dbo].[GateProxy]


text:
Q: Searching documents tagged with underscore "_" metadata Is there any such restrictions in SharePoint 2013 online for search?
I am trying to Search documents tagged with underscore "_" metadata , for example :- "A_ABC" (GenType).
Query I input in my searchbox ,
GenType = "A_ABC" , but I am not getting any results from my document library.
But for another metadata ABC(without any underscore),
GenType = "ABC"  , I see the relevant documents in the search results.
Aren't we allowed to enter "_" in the search queries?


text:
Q: Rendered model disappears at some asymptote I've been trying to render a simple teapot with PyOpenGL, but have been running into strange issues. I can't seem to figure out exactly where the error originates from, despite the simplicity of the code.
Main.py
import pygame
from pygame.locals import *
from MV import *
import ctypes
from OpenGL.GL import *
from OpenGL.GL import shaders
from OpenGL.GLU import *
import teapot as tp

vertex_shader = '''
#version 420

in vec3 vpos_modelspace;
in vec3 vnorm_modelspace;
uniform mat4 mvp;
out vec4 vertcolor;

void main(){
    vertcolor = vec4(vnorm_modelspace, 1.0);
    gl_Position = mvp * vec4(vpos_modelspace, 1.0);
}
'''

fragment_shader = '''
#version 420

in vec4 vertcolor;
out vec4 fragcolor;

void main(){
    fragcolor = vertcolor;
}
'''

model = tp.teapot

pygame.init()
canvas = pygame.display.set_mode((800, 600), DOUBLEBUF|OPENGL)
pygame.display.set_caption('Test')
glClearColor(.5, .5, .5, 1)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LESS)
glDisable(GL_CULL_FACE)
VERTEXSHADER = shaders.compileShader(vertex_shader, GL_VERTEX_SHADER)
FRAGMENTSHADER = shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)
program = shaders.compileProgram(VERTEXSHADER, FRAGMENTSHADER)
glUseProgram(program)

vpos_loc = glGetAttribLocation(program, 'vpos_modelspace')
vnorm_loc = glGetAttribLocation(program, 'vnorm_modelspace')
mvp_loc = glGetUniformLocation(program, 'mvp')

eye = numpy.array([0, 0, 1], dtype=numpy.float32)
at = numpy.array([0, 0, 0], dtype=numpy.float32)
up = numpy.array([0, 1, 0], dtype=numpy.float32)

mvp = frustum(-1, 1, 1, -1, .1, 1000)@lookAt(eye, at, up)

vao = glGenVertexArrays(1)
glBindVertexArray(vao)

vbo_pos = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, vbo_pos)

vbo_norm = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, vbo_norm)

verts = []
normals = []
for i in range(0, len(model.faces), 3):
    index = model.faces[i:i+3]
    verts.extend(model.vertices[3*index[0]:3*index[0]+3])
    verts.extend(model.vertices[3*index[1]:3*index[1]+3])
    verts.extend(model.vertices[3*index[2]:3*index[2]+3])
    normals.extend(model.normals[3*index[0]:3*index[0]+3])
    normals.extend(model.normals[3*index[1]:3*index[1]+3])
    normals.extend(model.normals[3*index[2]:3*index[2]+3])

verts = numpy.array(verts, dtype=numpy.float32)
normals = numpy.array(normals, dtype=numpy.float32)

glBindBuffer(GL_ARRAY_BUFFER, vbo_pos)
glBufferData(GL_ARRAY_BUFFER, verts.size * verts.itemsize, verts, GL_STATIC_DRAW)

glVertexAttribPointer(vpos_loc, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0))
glEnableVertexAttribArray(vpos_loc)

glBindBuffer(GL_ARRAY_BUFFER, vbo_norm)
glBufferData(GL_ARRAY_BUFFER, normals.size * normals.itemsize, normals, GL_STATIC_DRAW)

glVertexAttribPointer(vnorm_loc, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0))
glEnableVertexAttribArray(vnorm_loc)

glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindVertexArray(0)

while(True):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
    glUseProgram(program)
    rotation_matrix = rotate(.01, [0, 1, 0])
    mvp =  mvp @ rotation_matrix
    glUniformMatrix4fv(mvp_loc, 1, GL_FALSE, mvp.flatten())
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

    glBindVertexArray(vao)
    glDrawArrays(GL_TRIANGLES, 0, int(verts.size/3))
    glBindVertexArray(0)
    glUseProgram(0)
    pygame.display.flip()

main()

MV.py
import numpy

def normalize(vector):
    return vector/numpy.linalg.norm(vector)

def translate(pos):
    return numpy.array([[1, 0, 0, pos[0]],
                        [0, 1, 0, pos[1]],
                        [0, 0, 1, pos[2]],
                        [0, 0, 0, 1]], dtype=numpy.float32)

def rotate(angle, axis):
    rads = angle * numpy.pi/180
    v = normalize(axis)
    c = numpy.cos(rads)
    omc = 1-c
    s = numpy.sin(rads)
    return numpy.array([[v[0]*v[0]*omc + c,   v[0]*v[1]*omc - v[2]*s, v[0]*v[2]*omc + v[1]*s, 0],
                        [v[0]*v[1]*omc + v[2]*s, v[1]*v[1]*omc + c,   v[1]*v[2]*omc - v[0]*s, 0],
                        [v[0]*v[2]*omc - v[1]*s, v[1]*v[2]*omc + v[0]*s, v[2]*v[2]*omc + c,   0],
                        [0, 0, 0, 1]], dtype=numpy.float32)

def lookAt(eye, at, up):
    n = normalize(at-eye)
    u = normalize(numpy.cross(n, up))
    v = normalize(numpy.cross(u, n))

    rotate = numpy.array([[u[0], v[0], -n[0], 0],
                          [u[1], v[1], -n[1], 0],
                          [u[2], v[2], -n[2], 0],
                          [0,    0,    0,    1]], dtype=numpy.float32).transpose()
    return rotate@translate(-eye)

def frustum(left, right, top, bottom, near, far):
    rl = right-left
    tb = top-bottom
    fn = far-near

    return numpy.array([[2*near/rl, 0,         (right+left)/rl, 0],
                        [0,         2*near/tb, (top+bottom)/tb, 0],
                        [0,         0,        -(far+near)/fn,   -(2*far*near)/fn],
                        [0,         0,        -1,               0]], dtype=numpy.float32)

The output shows the teapot being rotated (though not about the axis that I expected) and sort of shrinking and disappearing at rotations of 0, pi, 2pi, etc. I believe the teapot vertices are being processed correctly, as it does show up when rotated and is correctly shaded with normal values.
Output at 5 degrees - Model is 'growing'

Output at 30 degrees - Strange culling?

Output at 60 degrees - Relatively normal

Output at 170 degrees - Model is 'shrinking'

Output at 190 degrees - Model is 'growing' on the other side of the plane

At rotations 0, pi, 2pi, etc the model is completely invisible/too small to see.


text:
Q: How to draw the input into the VCC net/bus in a circuit diagram? I am currently drawing the circuit diagram for a device. To simplify the diagram I already using the ground symbol for all pins which are connected to ground. This makes the diagram much more readable.
But now there is a special power source (USB LiIon charger/power source) in the schema. It has various outputs, so I am currently draw all connections from the 5V output to the different components.
If I would use the symbol for VCC, it would simplify the diagram. But...
How do I show that the 5V output of the power source provides the power for all elements connected to the VCC (symbol)?
See this minimal example diagram:

A: Just connect the source to a Vcc symbol. Make sure the name is exactly the same.
Here's a simple example from this webpage where the source is a USB connector and it goes to a chip and another connector.


text:
Q: Fully transparent DMZ I'm trying to configure an openwrt router so that I get two wan IP addresses by dhcp - one for the router itself and one for a DMZ host. I followed the DMZ howto. It appears that the host on the DMZ interface sends a request for a IP but does not receive one.
Config files are here.

A: WANs are usually point-to-point connections. In this way, they are not going to assign two IP addresses to a router. Instead, a local LAN is configured for DMZ and externally connections are masked as if they were coming from/to the router IP.
This forwarding is what is achieved for port 80 with the following lines of howto:
# Make 192.168.2.2:80 publicly accessible
config 'redirect'
   option '_name' 'http'
   option 'src' 'wan'
   option 'proto' 'tcp'
   option 'src_dport' '80'
   option 'dest_ip' '192.168.2.2'

I think you can get a fully transparent DMZ if you remove lines with proto and src_dport, then your DMZ server would look to the external networks as having the IP of the router.


text:
Q: htaccess redirect non www to www URL I am running Magento site and in my .htaccess file I use this peace of code to redirect non www to www URL but it does nothing.
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP_HOST} !^$
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

My URL also contains HTTPS with it.

A:
Try This....

<IfModule mod_rewrite.c>
 RewriteEngine On
 Rewritecond %{HTTP_HOST} !^www\.example\.com [NC]
 Rewriterule (.*) http://www.example.com/$1 [R=301,,L]
</IfModule>

A: For dynamic domains:
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,QSA,NC,L]


text:
Q: Getting a JDBC connection from EclipseLink using EclipseLink as JPA 2.0 provider, I can obtain a JDBC connection by simply calling
Connection con = entityManager.unwrap(Connection.class);

But I'm unsure what I'm responsible for. Do I have to close the connection after submitting my queries? Or are I'm not allowed to close the connection, because EclipseLink also uses this connection internally. Or does it not care, because EclipseLink observes my behaviour and closes the connection automatically if I don't do it?

A: If you are in the context of a JPA transaction the connection will be managed by the provider (EclipseLink).  If you are outside of a transaction you are responsible for managing the connection yourself.
See the following link for additional information:
http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI#Getting_a_JDBC_Connection_from_an_EntityManager

A:
But I'm unsure what I'm responsible for. Do I have to close the
  connection after submitting my queries? Or are I'm not allowed to
  close the connection, because EclipseLink also uses this connection
  internally.

A good and valid question. It seems that the documentation is lacking the semantics of the unwrap() calls.
Regarding EclipseLink, according from what I got from the source:
EclipseLink gives you a reference to the currently active connection which it uses for the currently active client session transaction. If no transaction is active, a new will be created, associated with the session and returned from the unwrap() method.
As a result, IMHO, a commit/rollback of such a obtained Connection may lead to undefined behavior and/or exceptions. Same is true for executing DML which changed records have been previously cached by eclipselink internal caches or for which managed entities exist.
So when using this API, especially if the underlying transaction is dirty, be careful.
If you can refer to internal eclipselink classes, you can access eclipselink internal connection pool to get a Connection exclusively (have a look at org.eclipse.persistence.sessions.server.ServerSession.getConnectionPool(String) ).


text:
Q: RewriteCond with caret not working Here is an .htaccess file I am writing:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} ^api
RewriteRule (.+) test/$1.php [L]

Now, if I got to my browser and type in /api/asdf, I do not get /test/api/asdf. If I remove the caret, it works as expected. Also of interest, if I type /bapi/asdf in my browser, it does not work, which seems backwards because there is no caret.
Am I doing something wrong? How can I match the start of the REQUEST_FILENAME if caret does not work?

A: The %{REQUEST_FILENAME} variable isn't going to start with api. So the ^api expression will never match. The request filename is the local file system path of what the request should map to.
You can try this instead:
RewriteEngine On
RewriteRule ^(api.+) test/$1.php [L]

That matches requests that start with /api.


text:
Q: Is there any way to determine which series a given GraphDataItem comes from? I'm using AmCharts to plot two lines on a line chart. They have some great documentation on how to use a function to customize the "balloon" (tooltip) text. However, it's not clear how I would go about distinguishing between the two data series in this custom function. At first glance it doesn't seem like there's any property in the GraphDataItem object to identify which series the data comes from.
Here's some pseduo code, for visual people:
graph.balloonFunction = adjustBalloonText;

function adjustBalloonText(graphDataItem, graph) {
    if ( graphDataItem ...series?... == 1 ) {
        return "something";
    } else {
        return "something else";
    }
}

How do I do this?

A: Check GraphDataItem description:
http://docs.amcharts.com/3/javascriptcharts/GraphDataItem
It has a "category" property, also a reference to serialDataItem: http://docs.amcharts.com/3/javascriptcharts/SerialDataItem
Which contains all the information about series.
And finally, it has a reference to original data item from data provider (dataContext property). So you can store additional information in your data and then get it using dataContext.


text:
Q: Trouble with custom Sharepoint List views created in Visual Studio 2010 Probably something simple but i'm not sure what the problem is here.  I create several custom list views in my schema.xml for my list.  I deploy and go in sharepoint designer to make sure everything is ok.  I click on the list i created but only the FIRST view in from schema.xml is listed in the Views table.  Why are the other two not showing up?   If i delete the first list the next appears.  I want all three to be shown in the Views table.  here is the portion of schema.xml

  <View BaseViewID="1" Type="HTML" Hidden="FALSE" WebPartZoneID="Main" DisplayName="Management Users" OrderedView="TRUE" DefaultView="TRUE"  MobileView="TRUE" MobileDefaultView="TRUE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/images/generic.png" Url="AllItems.aspx">
    <Toolbar Type="Standard" />
    <XslLink Default="TRUE">main.xsl</XslLink>
    <RowLimit Paged="TRUE">10</RowLimit>
    <ViewFields>
      <FieldRef Name="Photo"></FieldRef>
      <FieldRef Name="Position"></FieldRef>
      <FieldRef Name="LastName"></FieldRef>
      <FieldRef Name="FirstName"></FieldRef>
      <FieldRef Name="Email"></FieldRef>
      <FieldRef Name="PhoneNumber"></FieldRef>
      <FieldRef Name="Info"></FieldRef>
    </ViewFields>
    <Query>
      <Where>
        <Eq>
          <FieldRef Name="Group"/>
          <Value Type="Choice">Management</Value>
        </Eq>
      </Where>
      <OrderBy>
        <FieldRef Name="LastName" Ascending="TRUE"></FieldRef>
      </OrderBy>
    </Query>
    <ParameterBindings>
      <ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
      <ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_DEFAULT)" />
    </ParameterBindings>
  </View>
  <View BaseViewID="2" Type="HTML" WebPartZoneID="Main" DisplayName="PPM Users" OrderedView="TRUE" DefaultView="FALSE"  MobileView="TRUE" MobileDefaultView="TRUE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/images/generic.png" Url="AllItems.aspx">
    <Toolbar Type="Standard" />
    <XslLink Default="TRUE">main.xsl</XslLink>
    <RowLimit Paged="TRUE">10</RowLimit>
    <ViewFields>
      <FieldRef Name="Photo"></FieldRef>
      <FieldRef Name="Position"></FieldRef>
      <FieldRef Name="LastName"></FieldRef>
      <FieldRef Name="FirstName"></FieldRef>
      <FieldRef Name="Email"></FieldRef>
      <FieldRef Name="PhoneNumber"></FieldRef>
      <FieldRef Name="Info"></FieldRef>
    </ViewFields>
    <Query>
      <Where>
        <Eq>
          <FieldRef Name="Group"/>
          <Value Type="Choice">PPM</Value>
        </Eq>
      </Where>
      <OrderBy>
        <FieldRef Name="LastName" Ascending="TRUE"></FieldRef>
      </OrderBy>
    </Query>
    <ParameterBindings>
      <ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
      <ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_DEFAULT)" />
    </ParameterBindings>
  </View>
  <View BaseViewID="3" Type="HTML" WebPartZoneID="Main" DisplayName="PCL Users" OrderedView="TRUE" DefaultView="FALSE"  MobileView="TRUE" MobileDefaultView="TRUE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/images/generic.png" Url="AllItems.aspx">
    <Toolbar Type="Standard" />
    <XslLink Default="TRUE">main.xsl</XslLink>
    <RowLimit Paged="TRUE">10</RowLimit>
    <ViewFields>
      <FieldRef Name="Photo"></FieldRef>
      <FieldRef Name="Position"></FieldRef>
      <FieldRef Name="LastName"></FieldRef>
      <FieldRef Name="FirstName"></FieldRef>
      <FieldRef Name="Email"></FieldRef>
      <FieldRef Name="PhoneNumber"></FieldRef>
      <FieldRef Name="Info"></FieldRef>
    </ViewFields>
    <Query>
      <Where>
        <Eq>
          <FieldRef Name="Group"/>
          <Value Type="Choice">PCL</Value>
        </Eq>
      </Where>
      <OrderBy>
        <FieldRef Name="LastName" Ascending="TRUE"></FieldRef>
      </OrderBy>
    </Query>
    <ParameterBindings>
      <ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
      <ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_DEFAULT)" />
    </ParameterBindings>
  </View>
</Views>

TIA

A: By just looking at your XML I noticed that you defined Url="AllItems.aspx" in all of your views. So every 'new' view is overwriting last one added and you end up with only one view.
You need to set different Url attribute for each view.


text:
Q: Calling multiple functions with names matching Regex I have some functions like these:

*

*function name_a(){}

*function name_b(){}

*function name_x(){}

*function name_n(){}
I want to call all functions start with name_ with regex in javascript.
How can I do that?

A: Just for the kicks, here's something you can use. ES5, so IE>9 is required (could be tweaked for older browsers support, though).
/**
 * Calls functions of given target object with names matching given regex.
 *
 * @param {any} targetObject
 * @param {RegExp} nameRegex
 * @param {...any} functionsArguments
 *
 * @returns {any[]} The values returned by each function called.
 */
function callFunctionsMatching(targetObject, nameRegex, functionsArguments) {
      // make arguments into array, then splice
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
    var functionsArgs = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)).splice(2);

    return Object.getOwnPropertyNames(targetObject).filter(function (propertyName) {
        return typeof targetObject[propertyName] == 'function' && nameRegex.test(propertyName);
    }).map(function (functionName) {
        return targetObject[functionName].apply(targetObject, functionsArgs);
    });
}

Usage (demo JSBin here)
Global functions (window target object):
// setup some functions
function a1(a, b, c, d) { console.log('a1->', a, b, c, d); }
function b1(arg) { console.log('b1->', arg); }
window.c1 = console.log

// call every function ending with 1
callFunctionsMatching(window, /1$/, 'stuff', 1, 3, 4);

Output:
a1-> stuff 1 3 4
b1-> stuff
stuff 1 3 4

Objects functions (any object as target):
var person = {
  aa: function(x) { console.log('person.aa called with', x); return 'this is the return value of person.aa'; },
  aaz: function(x) { console.log('I shouldn have been printed'); }
};

var valuesReturned = callFunctionsMatching(person, /aa$/, 'some argument');

console.log('valuesReturned were', valuesReturned);

Output:
person.aa called with some argument
valuesReturned were ["this is the return value of person.aa"]

Example from the question:
function name_a(){ console.log('name_a called'); }
function name_b(){ console.log('name_b called'); }
function name_x(){ console.log('name_x called'); }
function name_n(){ console.log('name_n called'); }

callFunctionsMatching(window, /^name_/, 'args');

Output:
function name_a called
function name_x called
function name_n called
function name_b called

A: This doesn't handle DOM objects, but if you have a plain object and simply want to search for all the functions matching a certain regex at one level, you could (optionally, showing executing each one in order):
function get_func_filter(obj, match) {
    var keys = Object.getOwnPropertyNames(obj);

    return keys.filter(function(func_name) {
        return typeof obj[func_name] === 'function'
               && match.test(func_name);
    });
}

var funcs = {
    'prop_a': 'value',
    'prop_b': 'value',
    'name_a': function(){console.log('name_a function called');},
    'name_b': function(){console.log('name_b function called');},
    'name_c': function(){console.log('name_c function called');},
    'not_name_a': function(){console.log('not_name_a function called');},
    'not_name_b': function(){console.log('not_name_b function called');},
};

// First, get the function names that match "starting with name_"
get_func_filter(funcs, /^name_/)
    // Then get each name
    .map(function(func_name) {
        // And execute it (the second)
        !funcs[func_name] || funcs[func_name]();
    }
);

https://jsfiddle.net/5vrfpmeq/


text:
Q: Create multidimentional array in swift with different datatypes this is my first question here so forgive me if it is not very clear.
I am trying to create an array in swift that will store either arrays of arrays or an integer number.
The array is supposed to be a simple representation of the data I will be using which is basically a tree kind of data structure like so...
Array = [ [[ [2, 3] ], [ 1, 4 ], [ 2 ]],
          [ 2 ], [[2, 5], [6, 1] ], 3 ]
In overall the arrays are the branches and the integers are the leaves
I've tried declaring them as optionals like so
var test2 = [[[Int]?]?]()

Or using typedef's but I still can't get it to work.
Also, it should be possible to add new leaves to any of the arrays

A: Here is a solution based on enum, first declare the enum:
enum Node
{
    case leaf(Int)
    case branch([Node])
}

You can now write things such as:
let x = Node.leaf(42)
let y = Node.branch([Node.leaf(42), Node.leaf(24)])

However this is going to become laborious very quickly. Fortunately Swift allows conversions from literals, so we add:
extension Node : ExpressibleByIntegerLiteral
{
    init(integerLiteral value: Int)
    {
        self = .leaf(value)
    }
}

extension Node : ExpressibleByArrayLiteral
{
    init(arrayLiteral elements: Node...)
    {
        self = .branch(elements)
    }
}

And with those added we can now write the above two let statements as:
let x : Node = 42
let y : Node = [42, 24]

which is nicer. However if we print(y) we get:
branch([Node.leaf(42), Node.leaf(24)])

If you wish to pretty print that you can add:
extension Node : CustomStringConvertible
{
    var description : String
    {
        switch self
        {
            case .leaf(let value):
                    return value.description
            case .branch(let branches):
                    return branches.description
        }
    }
}

And now print(y) gives you:
[42, 24]

Finally your example:
let w : Node = [[[[2, 3]], [1, 4], [2]], [2], [[2, 5], [6, 1]], 3]

which prints as:
[[[[2, 3]], [1, 4], [2]], [2], [[2, 5], [6, 1]], 3]

You'll want to complete the enum type, with predicates such as isLeaf etc., but that is the basic idea.
HTH


text:
Q: php date format regex check i am trying to valdiate the date field "YYYYMMDD" using PHP regex. I tried something like this
/([0-9]{4})([0-9]{2})([0-9]{2})/

but in this one, it's going to accept any two digits like 01-99 for MM or DD, but i am looking to have something for 01-12 for MM and 01-31 for DD. Any advise on doing this?
thanks

A: This should do the job:
function dateValidate($date) {
    $t = strtotime($date);
    return date('Ymd', $t) == $date;
}

edit: Worth noting that this won't be as fast as a regexp but in terms of noticeable performance will work fine.

A: Instead of regular expressions you can also split the string and use checkdate to see if the date is valid.

A: Regex doesn't seem very practical for date validation. Why not split it into pieces, then use checkdate()?

A: For the month, you could use:
(0[1-9]|1[012])

For days:
(0[1-9]| [12][0-9]|3[01])

Some good examples here.

A: DO NOT USE checkdate as checkdate('1\'', '1', '2000') validates TRUE.


text:
Q: RxJS extract data from stream on external condition Context: I have a logging library for an app and I want to use Rx Subject to write logs to database.
Problem: Logs are generated before the connection to database is established and the connection can become unavailable at any time, but I have and observable that either contains an object with methods for working with the database or an undefined. What I want to do is to keep the logs in the stream while database persistence is undefined and resume when it's available.
I think the code should look something like this:
logsSubject
           .takeWhen(/* test for database persistence */) // made up name because I don't know a Rx method that does what I want
           .subscribe(/* write data to database */);

I'm not sure however if this is actually possible for I've been using RxJS for a very short time

A: Following code is to simulate your scenario. The db will connect every 10s and disconnect every 5s after it connected. In real use case connect and disconnect should be both shared Observable or Subject. Instead of takeUntil operator I used a merge here because takeUntil will just completed the observable sequence and you won't be able to resume it. (repeatWhen operator should work but it seems missing in Rxjs 5)
//emit value every 1s
const logWrite = Rx.Observable.interval(1000)

const dbConnected = new Rx.Subject()
// make it fire every 10s
Rx.Observable.interval(10000).do(()=>dbConnected.next('db
connected')).subscribe()

const dbDisconnected = Rx.Observable.timer(3000)
.flatMap(()=>Rx.Observable.throw('db disconnected'))

const writeWhenConnected = logWrite.merge(dbDisconnected)
.retryWhen(function(errors) {
    return errors.switchMap(()=>dbConnected);
});

writeWhenConnected.subscribe(val => console.log(val),console.warn);

A: You can do it the other way around:
Observable.combineLatest(dbConnection, logsSubject, (db, logs) => {
    // whatever: db.save(...)
  })
  .do(/* or since it's a side effect it should probably go here instead */)

This way combineLatest will wait until both source Observable emit and will hold the dbConnection even though it emitted just one item.

A: What it seems that I needed was pausableBuffered from RxJS4 but since it's been removed in RxJS5 I ended up with the following solution:
let dbAvailability = dbSubject
         .switchMap((db) => db ? logSubject : Rx.Observable.never());

//get data only when dbAvailability emits, and that happens only when I have a connection
let bufferedLogs = logSubject.buffer(dbAvailability);

bufferedLogs
  .concatAll()
  .subscribe(/* save to database */);


text:
Q: How to print the output to same file you are reading from in perl? I have a perl script which reads a file, changes the required thing and then prints the output of the file on the console.
I want the output to be updated in the same file from where it is picking the data.
How can this be done?

A: You can use the -i switch, or the $^I special variable.
perl -i.backup -pe 's/change me/something else/'

or
#!/usr/bin/perl
use warnings;
use strict;

$^I = '.backup';
while (<>) {
    ...
    print;
}

Note that it only works for the special file handle *ARGV used by the diamond operator. It creates a new file behind the scenes, anyway.
See perlrun and perlvar.


text:
Q: Snowflake Automation Tasks in your current or previous organization Just curious to know the automations you have done in your snowflake job ( may be in your current organization or previous one ).
Automations or BI Related tasks.
Regards

A: You can automate almost anything. I have faced such tasks as:

*

*orchestration with ETL/ELT processes

*copying/moving files on External Stage

*direct loading of data from e-mail messages

*alarms and automatic notifications about Snowflake charge or costs

*automation of granting RBAC permissions

*creating new copies of environments

*database replication

*data backup on AWS S3 (customer requirement)

*CI/CD processes

*and much much more

If you are looking for a good automation tool, I strongly recommend AutomateNOW!.
AutomateNOW! enables you natively communicate with Snowflake. Thanks to that you can manage and monitor Snowflake processes such as stored procedures, queries, DMLs and so on. AutomateNOW! is also useful to reduce the cost of Snowflake usage because in a dynamic manner it is able to decide what size of Data Warehouse should be launched and once the process is finished it can dynamically resize the warehouse or make it suspended. In addition the output of the Explain Plan of SF queries can be used and parsed on the  fly in order to manage workload of Snowflake. I see the enormous potential when Snowflake is one of the components of a multi technology ecosystem and it is needed  to manage the whole process or chain  of the process.
Tool link: AutomateNOW!
Examples of AutomateNOW! screenshots:


text:
Q: Android styling action bar overflow menu? I am trying to style the overflow menu items on the action bar but so far I've had no luck. I am testing on Android API 21 but my minimum version is set to 17. I am using the theme DeviceDefault. I tried setting the theme to Holo but the action bar disappears completely then. Anyways, here are the styles I'm currently using for the action bar:
<style name="AppBaseTheme" parent="android:Theme.DeviceDefault">
    <item name="android:popupMenuStyle">@style/PopupMenu</item>
    <item name="android:actionBarStyle">@style/MyActionBar</item>
    <item name="actionBarStyle">@style/MyActionBar</item>
    <item name="android:displayOptions">showHome|useLogo|showTitle</item>
</style>

<style name="AppTheme" parent="AppBaseTheme">

</style>

<style name="MyActionBar">
    <item name="android:background">@drawable/gradient3</item>
    <item name="android:titleTextStyle">@style/MyActionBarTitleText</item>
    <item name="titleTextStyle">@style/MyActionBarTitleText</item>
</style>

<style name="PopupMenu" parent="android:Widget.DeviceDefault.ListPopupWindow">
    <item name="android:popupBackground">@drawable/gradient1</item>
    <item name="android:textColor">@color/ed</item>
</style>

<style name="MyActionBarTitleText" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:textColor">@color/ed</item>
    <item name="android:textSize">18sp</item>
</style>

So far popupMenuStyle seems to be ignored on API 21 but the action bar background takes effect. What is the correct way of styling the overflow menu for android versions 17 onwards? Also, is it recommended to use DeviceDefault as the theme and if not, is there a reason the Holo theme is making the action bar disappear?
Thank you. I appreciate any help.


text:
Q: Unexpected outputs from standalone class with preview and crop options I am designing a logo composed of two letters and am using the standalone class. I would expect the newer crop option to give me a "tighter" PDF output than the older preview option, but the reverse seems to be the case. Here is my MWE:
\documentclass[crop=true]{standalone}
\usepackage{fontspec}
\usepackage{xcolor}
\setmainfont{Noto Serif}
\setlength{\fboxrule}{0em}
\setlength{\fboxsep}{0em}
\begin{document}
\newbox{\Rx}
\newbox{\CRx}
\sbox{\Rx}{%
\fontsize{42pt}{50pt}\selectfont%
{R\hspace{-0.18em}{\raisebox{-0.22em}{\textcolor{gray}{x}}}}%
}
\fcolorbox{black}{lightgray}{\centering\usebox{\Rx}}
\end{document}

The result of the crop option is
Whereas, if I replace the class option to be previewI get the tighter PDF whose screenshot is
Why is there white space on the left of the crop image and how might it be avoided?
Thanks.

A: You have spurious spaces in your code:
\documentclass[crop=true]{standalone}
\usepackage{fontspec}
\usepackage{xcolor}
\setmainfont{Noto Serif}
\setlength{\fboxrule}{0em}
\setlength{\fboxsep}{0em}
\begin{document}
\newbox{\Rx}% <---
\newbox{\CRx}% <---
\sbox{\Rx}{%
\fontsize{42pt}{50pt}\selectfont%
{R\hspace{-0.18em}{\raisebox{-0.22em}{\textcolor{gray}{x}}}}%
}% <---
\fcolorbox{black}{lightgray}{\centering\usebox{\Rx}}
\end{document}


text:
Q: Cookie not set with Node + Express + Nginx I have a Node app using Express, and I try to set a cookie to my client. It works well on local environment (http). But once I put in production (https), I receive well the cookie (I can see it in the response), but it is not set. Any idea?
Nginx conf:
http {
  include mime.types;
  default_type application/octet-stream;
  sendfile on;
  keepalive_timeout 65;
  gzip on;

  server {
    listen 443 ssl default_server;
    listen [::]:443 default_server;
    server_name back.domain.com;

    ssl_certificate  /etc/letsencrypt/.../fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/.../privkey.pem;

    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }
  }
}

Node app:
const api = express()

api.enable('trust proxy')
api.use(cors({origin: 'https://front.domain.com', credentials: true}))

api.post('/login', (req, res) => {
  // validate credentials and generate token
  // set expires to 24h

  res
    .cookie('token', token, {expires, httpOnly: true, secure: true})
    .sendStatus(204)
})

Front:
// I use the axios lib
axios({
  baseURL: 'https://back.domain.com',
  url: '/login',
  withCredentials: true,
  method: 'POST'
}

A: I figured out after hours of research... I had to set the domain key to domain.com when I create the cookie:
res
  .cookie('token', token, {expires, httpOnly: true, secure: true, domain: 'domain.com'})
  .sendStatus(204)

A: Another possible reason for cookies not being set is having option:
secure: true

when protocol is http (not secure) instead of https.


text:
Q: How to dispose objects correctly (ASP.NET MVC + Entity Framework) I would like to know how to dispose objects correctly in the following situation. This is a ASP.NET MVC controller action. There is a repository which implements IDisposable. Attachment entity contains related entity Task. When I click on the attachment detail, it is displayed correctly. But when I click on the task, then the following exception is threw "The ObjectContext instance has been disposed...". I understand, that when the view is rendered it is disposed and the ObjectContext is closed.
public ActionResult Detail(Guid id)
{
    Attachment attachment = null;
    using (var attachmentRepository = IoC.Resolve<AttachmentRepository>())
    {
        attachment = attachmentRepository.SelectByKey(id);
        return View("Detail", attachment);
    }
}

My question is what is best practise in this scenario?
Is this a good solution? When will be the ObjectContext disposed in this situation? When the user go to another view? Or when the garbage collector will be executed?
public ActionResult Detail(Guid id)
{
    Attachment attachment = null;
    var attachmentRepository = IoC.Resolve<AttachmentRepository>();

    attachment = attachmentRepository.SelectByKey(id);
    return View("Detail", attachment);
}

thanks

A: Your Task entity was not retrieved as part of your original query, so EF is trying to lazy load it which fails since the context has been disposed. You should use an Include() query to retrieve the Task entity as part of your original query to avoid having to go back to the database later on (which also would mean that you would have to keep the context alive).
Also you are not really doing IoC here, you are using the Service locator (Anti-) pattern. You should have your IoC container pass in your repository as a constructor dependency to your controller. The IoC container in turn should be responsible for the lifetime management of your repository instances.


text:
Q: Copying single cell value from different closed workbooks in a sharepoint I have one master workbook and 20 other workbooks in a SharePoint.  Currently I am using the following code to retrive a single cell value from the closed workbook which is working very fine.
Sub Example()

Dim wbPath As String, wbName As String
Dim wsName As String, cellRef As String
Dim Ret As String

wbPath = "http://*****/2014/"

wbName = "overview 2014.xlsm"
wsName = "Sheet1"
cellRef = "E2"

Ret = "'" & wbPath & "[" & wbName & "]" & _
      wsName & "'!" & Range(cellRef).Address(True, True, -4150)

ActiveWorkbook.Worksheets("Sheet1").Range("A4").Value = ExecuteExcel4Macro(Ret)

End Sub

Now I actually wanted to get the same cell value which needs to be copied from all workbooks from the SharePoint into the Master workbook ranges A5, A6, A7, A8.... etc.
Can some one please help me or give me a hint on how to copy same cell values from different closed workbooks from the same sharepoint location?
I have actually tried with the following code for other workbooks and working fine, but just wanted to know is there any other smarter way to reduce number of lines in the code?
 wbPath = "http://*****/2014/"

 wbName = "overview 2014.xlsm"
 wsName = "Sheet1"
 cellRef = "E2"

 Ret = "'" & wbPath & "[" & wbName & "]" & _
      wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)

ActiveWorkbook.Worksheets("sheet1").Range("A4").Value = ExecuteExcel4Macro(Ret)

wbName = "workbook2.xlsm"
wsName = "sheet1"
cellRef = "E2"

Ret = "'" & wbPath & "[" & wbName & "]" & _
      wsName & "'!" & Range(cellRef).Address(True, True, -4150)

ActiveWorkbook.Worksheets("sheet1").Range("A5").Value = ExecuteExcel4Macro(Ret)

wbName = "workbook3.xlsm"
wsName = "sheet1"
cellRef = "E2"

Ret = "'" & wbPath & "[" & wbName & "]" & _
      wsName & "'!" & Range(cellRef).Address(True, True, -4150)

ActiveWorkbook.Worksheets("sheet1").Range("A6").Value = ExecuteExcel4Macro(Ret)

wbName = "workbook4.xlsm"
wsName = "sheet1"
cellRef = "E2"

Ret = "'" & wbPath & "[" & wbName & "]" & _
      wsName & "'!" & Range(cellRef).Address(True, True, -4150)

ActiveWorkbook.Worksheets("sheet1").Range("A7").Value = ExecuteExcel4Macro(Ret)

wbName = "workbook5.xlsm"
wsName = "sheet1"
cellRef = "E2"

Ret = "'" & wbPath & "[" & wbName & "]" & _
      wsName & "'!" & Range(cellRef).Address(True, True, -4150)

ActiveWorkbook.Worksheets("sheet1").Range("A8").Value = ExecuteExcel4Macro(Ret)

wbName = "workbook6.xlsm"
wsName = "sheet1"
cellRef = "E2"

Ret = "'" & wbPath & "[" & wbName & "]" & _
      wsName & "'!" & Range(cellRef).Address(True, True, -4150)

ActiveWorkbook.Worksheets("sheet1").Range("A9").Value = ExecuteExcel4Macro(Ret)

wbName = "Workbook7.xlsm"
wsName = "sheet1"
cellRef = "E2"

Ret = "'" & wbPath & "[" & wbName & "]" & _
      wsName & "'!" & Range(cellRef).Address(True, True, -4150)

ActiveWorkbook.Worksheets("sheet1").Range("A10").Value = ExecuteExcel4Macro(Ret)

wbName = "workbook8.xlsm"
wsName = "sheet1"
cellRef = "E2"

Ret = "'" & wbPath & "[" & wbName & "]" & _
      wsName & "'!" & Range(cellRef).Address(True, True, -4150)

ActiveWorkbook.Worksheets("sheet1").Range("A11").Value = ExecuteExcel4Macro(Ret)

wbName = "workbook9.xlsm"
wsName = "sheet1"
cellRef = "E2"

Ret = "'" & wbPath & "[" & wbName & "]" & _
      wsName & "'!" & Range(cellRef).Address(True, True, -4150)

ActiveWorkbook.Worksheets("sheet1").Range("A13").Value = ExecuteExcel4Macro(Ret)

wbName = "workbook10.xlsm"
wsName = "sheet1"
cellRef = "E2"

Ret = "'" & wbPath & "[" & wbName & "]" & _
      wsName & "'!" & Range(cellRef).Address(True, True, -4150)

ActiveWorkbook.Worksheets("sheet1").Range("A14").Value = ExecuteExcel4Macro(Ret)

A: To reduce the code I would use additional function:
Function getValue(wbPath As String, wbName As String, wsName As String, cellRef As String)
    Dim Ret As String
    Ret = "'" & wbPath & "[" & wbName & "]" & _
            wsName & "'!" & Range(cellRef).Address(True, True, -4150)
    getValue = ExecuteExcel4Macro(Ret)
End Function

and then call it like this:
Sub test()
    Dim i As Integer, wbs

    wbs = Array("overview 2014.xlsm", "workbook2.xlsm", _
                "workbook3.xlsm", "workbook4.xlsm", _
                "workbook5.xlsm", "workbook6.xlsm", _
                "workbook7.xlsm", "workbook8.xlsm", _
                "workbook9.xlsm", "workbook10.xlsm")
    ' LBound(wbs) = 0
    For i = LBound(wbs) To UBound(wbs)
        ActiveWorkbook.Worksheets("sheet1").Range("A4").Offset(i).Value = _
            getValue("http://*****/2014/", CStr(wbs(i)), "sheet1", "E2")
    Next i
End Sub


text:
Q: Is this error selection or conditional? (Java) I have an error, on the third IF statement. It checks to see if the user entered at number within a range (1-6) and the letter is a-f. I cant test my search algorithm because there seems to be an error in that line. I can't work it out. What seems to be wrong? Is it the answer.charAt(1)?
boolean wronganswer = true;
while (wronganswer == true){

    answer = (String)JOptionPane.showInputDialog(null, new JLabel(sb.toString()), "Battleships", JOptionPane.INFORMATION_MESSAGE, pic, null, "");
    if(answer.length() == 2){
        if ((Character.isLetter(answer.charAt(0))) && (Character.isDigit(answer.charAt(1)))){
            if ((answer.charAt(1) >= 0) && (answer.charAt(1) <= 6)){
                for (int k = 0; k < rows.length; k++){
                    if(rows[k] == (""+answer.charAt(0))){
                        wronganswer=false;
                    }
                }
                JOptionPane.showMessageDialog(null,"No! That letter is not on the grid!");
            }
            else{
                JOptionPane.showMessageDialog(null,"No! That number is not on the grid!");
                System.out.println(answer.charAt(1));
            }
        }
        else{
            JOptionPane.showMessageDialog(null,"No! Enter a letter, THEN a number!");
        }
    }
    else{
        JOptionPane.showMessageDialog(null,"No! Enter ONE letter and ONE number!");
    }

}

[EDIT] Fixed an indentation error when pasting to stack overflow

A: This is due to == comparing a reference with an anonymous temporary java.lang.String, which will always be false. The fix is simple; use
rows[k].equals("" + answer.charAt(0));
instead, which compares the string contents. You could use the flashier Yoda Expression
("" + answer.charAt(0)).equals(rows[k])
which will not throw a NullPointerException if rows[k] is null.

A: in your code:
if ((answer.charAt(1) >= 0) && (answer.charAt(1) <= 6)){

You get a char. Even if your character is a digit, its value is its ASCII value.
So your condition actually doesn't test if you input a digit between 0 and 6 but it tests if you character is either NUL, SOH, STX, ETX, EOT, ENQ or ACK.
If you want to check if you char is a digit in a range, you have to add single quote around your range limit numbers:
if ((answer.charAt(1) >= '0') && (answer.charAt(1) <= '6')){

Or replace the limits with their ASCII value:
if ((answer.charAt(1) >= 48) && (answer.charAt(1) <= 54)){


text:
Q: How to get disk ID using C# (not "SerialNumber")? I'd like to retrieve the Disk ID of my hard drive using C#.
I do not want "SerialNumber" as most articles talked since it's absent on my box.
To check this ID, you can run "cmd" on windows:
  diskpart
  list disk
  select disk 0
  detail disk

The output is like:
  HGST HTS725050A7E630
  Disk ID: 1033D54D
  ...

On my virtual box the output is
VBOX HARDDISK
Disk ID: 22452244

The disk ID seems to be a 32bit integer.
Is there anyway to get the same thing using C# (using API instead of parsing cmd output)?

A: This value is stored as the 'Signature'.  You get this the same place that you get the Serial Number.
ManagementObjectSearcher win32DiskDrives = new ManagementObjectSearcher("select * from Win32_DiskDrive");
foreach (ManagementObject win32DiskDrive in win32DiskDrives.Get())
{
    Console.WriteLine("{0:X}", win32DiskDrive.Properties["Signature"].Value);
}

A: You could use WMI and the Win32_DiskDrive class. There are both a DeviceID and a SerialNumber properties, you might want to check if it contains the value you're looking for.


text:
Q: Remove duplicate rows from joined table I have following sql query
SELECT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode

Which provide following result
School| avgscore
xyz   |  5
xyz   |  5
xyz   |  5
abc   |  3
abc   |  3
kkk   |  1

My question is how to remove those duplicates and get only following.
 School| avgscore
    xyz   |  5
    abc   |  3
    kkk   |  1

I tried with
   SELECT m.School, c.avgscore
   FROM postswithratings c
   join ZEntrycriteria on c.fk_postID= m.schoolcode
   group by m.School

But it gives me following error

"Column 'postswithratings.avgscore' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause."

A: No need to make things complicated.  Just go with:
SELECT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode
group by m.School, c.avgscore

or
SELECT DISTINCT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode

A: You have to only add distinct keyword like this :-
 SELECT DISTINCT  m.School, c.avgscore
  FROM postswithratings c
 join ZEntrycriteria on c.fk_postID= m.schoolcode

A: This will delete the Duplicate rows (Only Duplicate)
Schema:
CREATE TABLE #TAB (School varchar(5) , avgscore int)
INSERT INTO #TAB
SELECT 'xyz', 5
UNION ALL
SELECT 'xyz', 5
UNION ALL
SELECT 'xyz', 5
UNION ALL
SELECT 'abc', 3
UNION ALL
SELECT 'abc', 3
UNION ALL
SELECT 'kkk', 1

Now use CTE as your Tempprary View and delete the data.
;WITH CTE AS(
SELECT ROW_NUMBER() OVER (PARTITION BY School,avgscore  ORDER BY (SELECT 1)) DUP_C,
School,  avgscore FROM #TAB
)

DELETE FROM CTE WHERE DUP_C>1

Now do check #TAB, the data will be
+--------+----------+
| School | avgscore |
+--------+----------+
| xyz    |        5 |
| abc    |        3 |
| kkk    |        1 |
+--------+----------+

A: CREATE TABLE #Table2
    ([School] varchar(3), [avgscore] int)

INSERT INTO #Table2
    ([School], [avgscore])
VALUES
    ('xyz', 5),
    ('xyz', 5),
    ('xyz', 5),
    ('abc', 3),
    ('abc', 3),
    ('kkk', 1)
;
SELECT  SCHOOL,AVGSCORE FROM (SELECT *,ROW_NUMBER() OVER( PARTITION BY [AVGSCORE] ORDER BY (SELECT NULL)) AS RN FROM #TABLE2)A
WHERE RN=1
ORDER BY AVGSCORE
-------
;WITH CTE AS
(SELECT *,ROW_NUMBER() OVER( PARTITION BY [AVGSCORE] ORDER BY (SELECT NULL)) AS RN FROM #TABLE2)
SELECT SCHOOL,AVGSCORE  FROM CTE WHERE RN=1

output
SCHOOL  AVGSCORE
kkk      1
abc      3
xyz      5

A: Using the DISTINCT keyword will make sql use sets instead of multisets. So values only appear once

A: you only use group by if you're using aggregated function, eg. max. sum, avg
in that case,
SELECT Distinct(m.School), c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode


text:
Q: Getting error when trying to add user as a Tester on a Facebook App I have an App on developers.facebook.com portal where I have set up some users as administrator and others as tester roles. Now, I am trying to add a new user as a tester role but I get the following error:

Not long time ago, I could add users with tester roles with no problem but I can't now. Has something changed on Facebook's portal or is there something wrong on my App?

A: I just ran into this and rather than finding a proper solution, flipped the app to Live and added users that way.

A: I did just try now and finally managed to add the user as a tester on that App! No change has been made on the App so I wonder something has been fixed on Facebook developers portal.


text:
Q: how translate web.config into .htaccess file I have a Laravel web application hosted on an IIS8, this application has a web.config into the root of the project and another web.confing into the /public dir.
They are differents.
I no have an .htaccess file into the root but I have an .htaccess into my /public dir.
So I should transform this web.config into an .htaccess
How I can do it?
This is the web.config into root project

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
        <rewrite>
            <rules>
                <rule name="Imported Rule 4">
                    <match url=".*" ignoreCase="false" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="/public/{R:0}" />
    </rule>
                <rule name="Imported Rule 3" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="/public/index.php" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

the web.confing into /public dir is

<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Imported Rule 1" enabled="true" stopProcessing="true">
          <match url="^(.*)/$" ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
          </conditions>
          <action type="Redirect" redirectType="Permanent" url="/{R:1}" />
        </rule>
        <rule name="Imported Rule 2" enabled="true" stopProcessing="true">
          <match url="^" ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
          </conditions>
          <action type="Rewrite" url="index.php" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

I posted both beacuse I don't know which of these is the correct file.
I already have an .htaccess into my /public dir and it contains

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

So what is my problem? My problem is that this app on my local machine (I use xampp - apache and mysql) doesn't work very well.
Thanks to all for the answers!


text:
Q: NonNull local variables Is there a way to use @NonNull for local variables in Java? I am using Spring with @NonNullApi and @NonNullFields annotated in package-info.java but I don't seem to get the same warnings in my IDE for local variables as I do for fields, methods, and parameters.

A: Not really. You could make your variable final. This will have the effect of it not being allowed to be null, but this is a compile time feature, as opposed to validating parameters at Runtime, so they are two different concepts. Kotlin has the Nullable concept, but in Java there is only really Optional, which isn't the same.
If you want to add request parameter validation to functions and or variables at runtime, this is a classic example of Aspect Oriented Programming, and in Java you would need to rely on some sort of special magic such as Spring to do this (or AspectJ etc.), but behind the scenes will be using simple design patterns such as Proxy, or whatever it is there are many ways to skin a cat.
Annotations are just meta-data at the end of the day, and rely on something else reading and interpreting them appropriately, if you use a Spring annotation, it probably needs to be used on a method/field in a Spring bean.

A: To get the behavior I was looking for, I ended up creating an annotation and dropping @NonNullFields and @NonNullApi.
Here's the annotation I used:
    import javax.annotation.Nonnull;
    import javax.annotation.meta.TypeQualifierDefault;
    import java.lang.annotation.Documented;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;

    /**
     * This annotation can be applied to a package, class or method to indicate that the class fields,
     * method return types and parameters in that element are not null by default unless there is:
     * The method overrides a method in a superclass (in which
     * case the annotation of the corresponding parameter in the superclass applies) there is a
     * default parameter annotation applied to a more tightly nested element.
     */
    @Documented
    @Nonnull
    @TypeQualifierDefault(
            {
                    ElementType.ANNOTATION_TYPE,
                    ElementType.CONSTRUCTOR,
                    ElementType.FIELD,
                    ElementType.LOCAL_VARIABLE,
                    ElementType.METHOD,
                    ElementType.PACKAGE,
                    ElementType.PARAMETER,
                    ElementType.TYPE
            })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface NonNullByDefault {

    }


text:
Q: We are having trouble with absorption of two elements. Java Script We are korean students who are working for a project at school. We are having trouble on the absorption on two elements. We want to absorpt "carepage-navlink" and "carepage-text19" and then make them to run a function(predict()) that we made.

      다음

A: i think the problem is that you just forgot to close your first  ?
you can also add an onclick on the  tag so it looks like
<a onclick="function(predict)" ...


text:
Q: Hold row for 4 minutes then delete if no action is taken I'm building a reservation system using php/mysql and I'm trying to figure out how to hold a row for 4 minutes while the end user inputs their detailed information for the reservation to avoid people reserving the same ticket at the same time. If they leave the page, the record "holding" that ticket will be deleted once the 4 minute timer ends.
I've been thinking about scheduling an event to run 4 minutes after they hit the initial page, but when they complete the information page and finalize their reservation that event should be cancelled. I've searched a lot on this issue and only found ways to schedule future events not "hold" a record.
I also thought maybe create a unique temporary value that I could have an event look for at the end of 4 minutes (i.e. a varchar with 'DELETE4MINS' in a name column). However, I feel like there should be a better way to do this and none of the rows dealing with reserved tickets have varchar elements.
I have the following tables holding ticket reservation info:
CREATE TABLE reservations(
    rid int NOT NULL AUTO_INCREMENT,
    aid int NOT NULL,
    approval tinyint(1) NOT NULL,
    creationTime TIMESTAMP
        DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (rid),
    CONSTRAINT UQ_RESERVATION_COMPOSITE UNIQUE(rid, approval),
    FOREIGN KEY (aid) REFERENCES accounts (aid)
        ON DELETE CASCADE
);

CREATE TABLE reservedTickets(
    rid int NOT NULL,
    tid int NOT NULL,
    hid int NOT NULL,
    approval tinyint(1) NOT NULL,
    PRIMARY KEY (tid),
    FOREIGN KEY (rid, approval) REFERENCES reservations (rid, approval)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    FOREIGN KEY (tid) REFERENCES tickets (tid)
        ON DELETE CASCADE,
    FOREIGN KEY (hid) REFERENCES people (hid)
        ON DELETE CASCADE
);

A: I totally do not see any reason for actually deleting the entry. Basically all you have to do is create a reservation in the DB with the current time stamp when the user asks for one. Upon success you will present them some kind of a timer (using JS) that will show them the remaining time. And when the user submits the form the only thing you have to do is to compare current time to the time stamp in the DB and throw an error in case it has already been more than 4 minutes. If, for some reason, you do want to delete the entry, you will probably need to run a CRON job that will run every n minutes and delete all the "expired" rows. Or, in the very worst case, you can perform that operation every time someone accesses the service (and it will be part of the page code), although it's a bad idea.
EDIT: You can perform the delete query on the page that displays all the tickets. The flow will be as follows: as soon as someone accesses the page with the list of tickets, all the expired entries get deleted and you show them unreserved tickets only. This will ensure that people can only see those that are accessible, yet not expired