text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
R-Index
</TITLE>

<META NAME="date" CONTENT="2011-11-10">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A C D E F G H I L M N O P Q R S T V

R

RegisterDescriptor - Class in compiler.code
Class for the Register Descriptors.
RegisterDescriptor() -
Constructor for class compiler.code.RegisterDescriptor

Constructor for RegisterDescriptor.

RegisterDescriptorIF - Interface in es.uned.lsi.compiler.code

removeDataHolder(String, OperandIF) -
Method in class compiler.code.RegisterDescriptor

Remove a data holder from a register.

removeDataHolder(String, OperandIF) -
Method in interface es.uned.lsi.compiler.code.RegisterDescriptorIF

Remove a data holder from a register.

removePlace(String, String) -
Method in class compiler.code.MemoryDescriptor

Removes a place for the data holder.

removePlace(String, String) -
Method in interface es.uned.lsi.compiler.code.MemoryDescriptorIF

Removes a place for the data holder.

      Overview
      Package
      Class
      Use
      Tree
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A C D E F G H I L M N O P Q R S T V

redpajama_set_name: RedPajamaGithub


text:
001
017    package org.apache.commons.lang;
018
019    import java.io.IOException;
020    import java.io.StringWriter;
021    import java.io.Writer;
022    import java.util.Locale;
023
024    import org.apache.commons.lang.exception.NestableRuntimeException;
025    import org.apache.commons.lang.text.StrBuilder;
026
027    /**
028     * <p>Escapes and unescapes <code>String</code>s for
029     * Java, Java Script, HTML, XML, and SQL.</p>
030     *
031     * <p>#ThreadSafe#</p>
032     * @author Apache Software Foundation
033     * @author Apache Jakarta Turbine
034     * @author Purple Technology
035     * @author <a href="mailto:alex@purpletech.com">Alexander Day Chaffee</a>
036     * @author Antony Riley
037     * @author Helge Tesgaard
038     * @author <a href="sean@boohai.com">Sean Brown</a>
039     * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a>
040     * @author Phil Steitz
041     * @author Pete Gieser
042     * @since 2.0
043     * @version $Id: StringEscapeUtils.java 1057072 2011-01-10 01:55:57Z niallp $
044     */
045    public class StringEscapeUtils {
046
047        private static final char CSV_DELIMITER = ',';
048        private static final char CSV_QUOTE = '"';
049        private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE);
050        private static final char[] CSV_SEARCH_CHARS = new char[] {CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF};
051
052        /**
053         * <p><code>StringEscapeUtils</code> instances should NOT be constructed in
054         * standard programming.</p>
055         *
056         * <p>Instead, the class should be used as:
057         * <pre>StringEscapeUtils.escapeJava("foo");</pre></p>
058         *
059         * <p>This constructor is public to permit tools that require a JavaBean
060         * instance to operate.</p>
061         */
062        public StringEscapeUtils() {
063          super();
064        }
065
066        // Java and JavaScript
067        //--------------------------------------------------------------------------
068        /**
069         * <p>Escapes the characters in a <code>String</code> using Java String rules.</p>
070         *
071         * <p>Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) </p>
072         *
073         * <p>So a tab becomes the characters <code>'\\'</code> and
074         * <code>'t'</code>.</p>
075         *
076         * <p>The only difference between Java strings and JavaScript strings
077         * is that in JavaScript, a single quote must be escaped.</p>
078         *
079         * <p>Example:
080         * <pre>
081         * input string: He didn't say, "Stop!"
082         * output string: He didn't say, \"Stop!\"
083         * </pre>
084         * </p>
085         *
086         * @param str  String to escape values in, may be null
087         * @return String with escaped values, <code>null</code> if null string input
088         */
089        public static String escapeJava(String str) {
090            return escapeJavaStyleString(str, false, false);
091        }
092
093        /**
094         * <p>Escapes the characters in a <code>String</code> using Java String rules to
095         * a <code>Writer</code>.</p>
096         *
097         * <p>A <code>null</code> string input has no effect.</p>
098         *
099         * @see #escapeJava(java.lang.String)
100         * @param out  Writer to write escaped string into
101         * @param str  String to escape values in, may be null
102         * @throws IllegalArgumentException if the Writer is <code>null</code>
103         * @throws IOException if error occurs on underlying Writer
104         */
105        public static void escapeJava(Writer out, String str) throws IOException {
106            escapeJavaStyleString(out, str, false, false);
107        }
108
109        /**
110         * <p>Escapes the characters in a <code>String</code> using JavaScript String rules.</p>
111         * <p>Escapes any values it finds into their JavaScript String form.
112         * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) </p>
113         *
114         * <p>So a tab becomes the characters <code>'\\'</code> and
115         * <code>'t'</code>.</p>
116         *
117         * <p>The only difference between Java strings and JavaScript strings
118         * is that in JavaScript, a single quote must be escaped.</p>
119         *
120         * <p>Example:
121         * <pre>
122         * input string: He didn't say, "Stop!"
123         * output string: He didn\'t say, \"Stop!\"
124         * </pre>
125         * </p>
126         *
127         * @param str  String to escape values in, may be null
128         * @return String with escaped values, <code>null</code> if null string input
129         */
130        public static String escapeJavaScript(String str) {
131            return escapeJavaStyleString(str, true, true);
132        }
133
134        /**
135         * <p>Escapes the characters in a <code>String</code> using JavaScript String rules
136         * to a <code>Writer</code>.</p>
137         *
138         * <p>A <code>null</code> string input has no effect.</p>
139         *
140         * @see #escapeJavaScript(java.lang.String)
141         * @param out  Writer to write escaped string into
142         * @param str  String to escape values in, may be null
143         * @throws IllegalArgumentException if the Writer is <code>null</code>
144         * @throws IOException if error occurs on underlying Writer
145         **/
146        public static void escapeJavaScript(Writer out, String str) throws IOException {
147            escapeJavaStyleString(out, str, true, true);
148        }
149
150        /**
151         * <p>Worker method for the {@link #escapeJavaScript(String)} method.</p>
152         *
153         * @param str String to escape values in, may be null
154         * @param escapeSingleQuotes escapes single quotes if <code>true</code>
155         * @param escapeForwardSlash TODO
156         * @return the escaped string
157         */
158        private static String escapeJavaStyleString(String str, boolean escapeSingleQuotes, boolean escapeForwardSlash) {
159            if (str == null) {
160                return null;
161            }
162            try {
163                StringWriter writer = new StringWriter(str.length() * 2);
164                escapeJavaStyleString(writer, str, escapeSingleQuotes, escapeForwardSlash);
165                return writer.toString();
166            } catch (IOException ioe) {
167                // this should never ever happen while writing to a StringWriter
168                throw new UnhandledException(ioe);
169            }
170        }
171
172        /**
173         * <p>Worker method for the {@link #escapeJavaScript(String)} method.</p>
174         *
175         * @param out write to receieve the escaped string
176         * @param str String to escape values in, may be null
177         * @param escapeSingleQuote escapes single quotes if <code>true</code>
178         * @param escapeForwardSlash TODO
179         * @throws IOException if an IOException occurs
180         */
181        private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote,
182                boolean escapeForwardSlash) throws IOException {
183            if (out == null) {
184                throw new IllegalArgumentException("The Writer must not be null");
185            }
186            if (str == null) {
187                return;
188            }
189            int sz;
190            sz = str.length();
191            for (int i = 0; i < sz; i++) {
192                char ch = str.charAt(i);
193
194                // handle unicode
195                if (ch > 0xfff) {
196                    out.write("\\u" + hex(ch));
197                } else if (ch > 0xff) {
198                    out.write("\\u0" + hex(ch));
199                } else if (ch > 0x7f) {
200                    out.write("\\u00" + hex(ch));
201                } else if (ch < 32) {
202                    switch (ch) {
203                        case '\b' :
204                            out.write('\\');
205                            out.write('b');
206                            break;
207                        case '\n' :
208                            out.write('\\');
209                            out.write('n');
210                            break;
211                        case '\t' :
212                            out.write('\\');
213                            out.write('t');
214                            break;
215                        case '\f' :
216                            out.write('\\');
217                            out.write('f');
218                            break;
219                        case '\r' :
220                            out.write('\\');
221                            out.write('r');
222                            break;
223                        default :
224                            if (ch > 0xf) {
225                                out.write("\\u00" + hex(ch));
226                            } else {
227                                out.write("\\u000" + hex(ch));
228                            }
229                            break;
230                    }
231                } else {
232                    switch (ch) {
233                        case '\'' :
234                            if (escapeSingleQuote) {
235                                out.write('\\');
236                            }
237                            out.write('\'');
238                            break;
239                        case '"' :
240                            out.write('\\');
241                            out.write('"');
242                            break;
243                        case '\\' :
244                            out.write('\\');
245                            out.write('\\');
246                            break;
247                        case '/' :
248                            if (escapeForwardSlash) {
249                                out.write('\\');
250                            }
251                            out.write('/');
252                            break;
253                        default :
254                            out.write(ch);
255                            break;
256                    }
257                }
258            }
259        }
260
261        /**
262         * <p>Returns an upper case hexadecimal <code>String</code> for the given
263         * character.</p>
264         *
265         * @param ch The character to convert.
266         * @return An upper case hexadecimal <code>String</code>
267         */
268        private static String hex(char ch) {
269            return Integer.toHexString(ch).toUpperCase(Locale.ENGLISH);
270        }
271
272        /**
273         * <p>Unescapes any Java literals found in the <code>String</code>.
274         * For example, it will turn a sequence of <code>'\'</code> and
275         * <code>'n'</code> into a newline character, unless the <code>'\'</code>
276         * is preceded by another <code>'\'</code>.</p>
277         *
278         * @param str  the <code>String</code> to unescape, may be null
279         * @return a new unescaped <code>String</code>, <code>null</code> if null string input
280         */
281        public static String unescapeJava(String str) {
282            if (str == null) {
283                return null;
284            }
285            try {
286                StringWriter writer = new StringWriter(str.length());
287                unescapeJava(writer, str);
288                return writer.toString();
289            } catch (IOException ioe) {
290                // this should never ever happen while writing to a StringWriter
291                throw new UnhandledException(ioe);
292            }
293        }
294
295        /**
296         * <p>Unescapes any Java literals found in the <code>String</code> to a
297         * <code>Writer</code>.</p>
298         *
299         * <p>For example, it will turn a sequence of <code>'\'</code> and
300         * <code>'n'</code> into a newline character, unless the <code>'\'</code>
301         * is preceded by another <code>'\'</code>.</p>
302         *
303         * <p>A <code>null</code> string input has no effect.</p>
304         *
305         * @param out  the <code>Writer</code> used to output unescaped characters
306         * @param str  the <code>String</code> to unescape, may be null
307         * @throws IllegalArgumentException if the Writer is <code>null</code>
308         * @throws IOException if error occurs on underlying Writer
309         */
310        public static void unescapeJava(Writer out, String str) throws IOException {
311            if (out == null) {
312                throw new IllegalArgumentException("The Writer must not be null");
313            }
314            if (str == null) {
315                return;
316            }
317            int sz = str.length();
318            StrBuilder unicode = new StrBuilder(4);
319            boolean hadSlash = false;
320            boolean inUnicode = false;
321            for (int i = 0; i < sz; i++) {
322                char ch = str.charAt(i);
323                if (inUnicode) {
324                    // if in unicode, then we're reading unicode
325                    // values in somehow
326                    unicode.append(ch);
327                    if (unicode.length() == 4) {
328                        // unicode now contains the four hex digits
329                        // which represents our unicode character
330                        try {
331                            int value = Integer.parseInt(unicode.toString(), 16);
332                            out.write((char) value);
333                            unicode.setLength(0);
334                            inUnicode = false;
335                            hadSlash = false;
336                        } catch (NumberFormatException nfe) {
337                            throw new NestableRuntimeException("Unable to parse unicode value: " + unicode, nfe);
338                        }
339                    }
340                    continue;
341                }
342                if (hadSlash) {
343                    // handle an escaped value
344                    hadSlash = false;
345                    switch (ch) {
346                        case '\\':
347                            out.write('\\');
348                            break;
349                        case '\'':
350                            out.write('\'');
351                            break;
352                        case '\"':
353                            out.write('"');
354                            break;
355                        case 'r':
356                            out.write('\r');
357                            break;
358                        case 'f':
359                            out.write('\f');
360                            break;
361                        case 't':
362                            out.write('\t');
363                            break;
364                        case 'n':
365                            out.write('\n');
366                            break;
367                        case 'b':
368                            out.write('\b');
369                            break;
370                        case 'u':
371                            {
372                                // uh-oh, we're in unicode country....
373                                inUnicode = true;
374                                break;
375                            }
376                        default :
377                            out.write(ch);
378                            break;
379                    }
380                    continue;
381                } else if (ch == '\\') {
382                    hadSlash = true;
383                    continue;
384                }
385                out.write(ch);
386            }
387            if (hadSlash) {
388                // then we're in the weird case of a \ at the end of the
389                // string, let's output it anyway.
390                out.write('\\');
391            }
392        }
393
394        /**
395         * <p>Unescapes any JavaScript literals found in the <code>String</code>.</p>
396         *
397         * <p>For example, it will turn a sequence of <code>'\'</code> and <code>'n'</code>
398         * into a newline character, unless the <code>'\'</code> is preceded by another
399         * <code>'\'</code>.</p>
400         *
401         * @see #unescapeJava(String)
402         * @param str  the <code>String</code> to unescape, may be null
403         * @return A new unescaped <code>String</code>, <code>null</code> if null string input
404         */
405        public static String unescapeJavaScript(String str) {
406            return unescapeJava(str);
407        }
408
409        /**
410         * <p>Unescapes any JavaScript literals found in the <code>String</code> to a
411         * <code>Writer</code>.</p>
412         *
413         * <p>For example, it will turn a sequence of <code>'\'</code> and <code>'n'</code>
414         * into a newline character, unless the <code>'\'</code> is preceded by another
415         * <code>'\'</code>.</p>
416         *
417         * <p>A <code>null</code> string input has no effect.</p>
418         *
419         * @see #unescapeJava(Writer,String)
420         * @param out  the <code>Writer</code> used to output unescaped characters
421         * @param str  the <code>String</code> to unescape, may be null
422         * @throws IllegalArgumentException if the Writer is <code>null</code>
423         * @throws IOException if error occurs on underlying Writer
424         */
425        public static void unescapeJavaScript(Writer out, String str) throws IOException {
426            unescapeJava(out, str);
427        }
428
429        // HTML and XML
430        //--------------------------------------------------------------------------
431        /**
432         * <p>Escapes the characters in a <code>String</code> using HTML entities.</p>
433         *
434         * <p>
435         * For example:
436         * </p>
437         * <p><code>"bread" & "butter"</code></p>
438         * becomes:
439         * <p>
440         * <code>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</code>.
441         * </p>
442         *
443         * <p>Supports all known HTML 4.0 entities, including funky accents.
444         * Note that the commonly used apostrophe escape character (&amp;apos;)
445         * is not a legal entity and so is not supported). </p>
446         *
447         * @param str  the <code>String</code> to escape, may be null
448         * @return a new escaped <code>String</code>, <code>null</code> if null string input
449         *
450         * @see #unescapeHtml(String)
451         * @see <a href="http://hotwired.lycos.com/webmonkey/reference/special_characters/">ISO Entities</a>
452         * @see <a href="http://www.w3.org/TR/REC-html32#latin1">HTML 3.2 Character Entities for ISO Latin-1</a>
453         * @see <a href="http://www.w3.org/TR/REC-html40/sgml/entities.html">HTML 4.0 Character entity references</a>
454         * @see <a href="http://www.w3.org/TR/html401/charset.html#h-5.3">HTML 4.01 Character References</a>
455         * @see <a href="http://www.w3.org/TR/html401/charset.html#code-position">HTML 4.01 Code positions</a>
456         */
457        public static String escapeHtml(String str) {
458            if (str == null) {
459                return null;
460            }
461            try {
462                StringWriter writer = new StringWriter ((int)(str.length() * 1.5));
463                escapeHtml(writer, str);
464                return writer.toString();
465            } catch (IOException ioe) {
466                //should be impossible
467                throw new UnhandledException(ioe);
468            }
469        }
470
471        /**
472         * <p>Escapes the characters in a <code>String</code> using HTML entities and writes
473         * them to a <code>Writer</code>.</p>
474         *
475         * <p>
476         * For example:
477         * </p>
478         * <code>"bread" & "butter"</code>
479         * <p>becomes:</p>
480         * <code>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</code>.
481         *
482         * <p>Supports all known HTML 4.0 entities, including funky accents.
483         * Note that the commonly used apostrophe escape character (&amp;apos;)
484         * is not a legal entity and so is not supported). </p>
485         *
486         * @param writer  the writer receiving the escaped string, not null
487         * @param string  the <code>String</code> to escape, may be null
488         * @throws IllegalArgumentException if the writer is null
489         * @throws IOException when <code>Writer</code> passed throws the exception from
490         *                                       calls to the {@link Writer#write(int)} methods.
491         *
492         * @see #escapeHtml(String)
493         * @see #unescapeHtml(String)
494         * @see <a href="http://hotwired.lycos.com/webmonkey/reference/special_characters/">ISO Entities</a>
495         * @see <a href="http://www.w3.org/TR/REC-html32#latin1">HTML 3.2 Character Entities for ISO Latin-1</a>
496         * @see <a href="http://www.w3.org/TR/REC-html40/sgml/entities.html">HTML 4.0 Character entity references</a>
497         * @see <a href="http://www.w3.org/TR/html401/charset.html#h-5.3">HTML 4.01 Character References</a>
498         * @see <a href="http://www.w3.org/TR/html401/charset.html#code-position">HTML 4.01 Code positions</a>
499         */
500        public static void escapeHtml(Writer writer, String string) throws IOException {
501            if (writer == null ) {
502                throw new IllegalArgumentException ("The Writer must not be null.");
503            }
504            if (string == null) {
505                return;
506            }
507            Entities.HTML40.escape(writer, string);
508        }
509
510        //-----------------------------------------------------------------------
511        /**
512         * <p>Unescapes a string containing entity escapes to a string
513         * containing the actual Unicode characters corresponding to the
514         * escapes. Supports HTML 4.0 entities.</p>
515         *
516         * <p>For example, the string "&amp;lt;Fran&amp;ccedil;ais&amp;gt;"
517         * will become "&lt;Fran&ccedil;ais&gt;"</p>
518         *
519         * <p>If an entity is unrecognized, it is left alone, and inserted
520         * verbatim into the result string. e.g. "&amp;gt;&amp;zzzz;x" will
521         * become "&gt;&amp;zzzz;x".</p>
522         *
523         * @param str  the <code>String</code> to unescape, may be null
524         * @return a new unescaped <code>String</code>, <code>null</code> if null string input
525         * @see #escapeHtml(Writer, String)
526         */
527        public static String unescapeHtml(String str) {
528            if (str == null) {
529                return null;
530            }
531            try {
532                StringWriter writer = new StringWriter ((int)(str.length() * 1.5));
533                unescapeHtml(writer, str);
534                return writer.toString();
535            } catch (IOException ioe) {
536                //should be impossible
537                throw new UnhandledException(ioe);
538            }
539        }
540
541        /**
542         * <p>Unescapes a string containing entity escapes to a string
543         * containing the actual Unicode characters corresponding to the
544         * escapes. Supports HTML 4.0 entities.</p>
545         *
546         * <p>For example, the string "&amp;lt;Fran&amp;ccedil;ais&amp;gt;"
547         * will become "&lt;Fran&ccedil;ais&gt;"</p>
548         *
549         * <p>If an entity is unrecognized, it is left alone, and inserted
550         * verbatim into the result string. e.g. "&amp;gt;&amp;zzzz;x" will
551         * become "&gt;&amp;zzzz;x".</p>
552         *
553         * @param writer  the writer receiving the unescaped string, not null
554         * @param string  the <code>String</code> to unescape, may be null
555         * @throws IllegalArgumentException if the writer is null
556         * @throws IOException if an IOException occurs
557         * @see #escapeHtml(String)
558         */
559        public static void unescapeHtml(Writer writer, String string) throws IOException {
560            if (writer == null ) {
561                throw new IllegalArgumentException ("The Writer must not be null.");
562            }
563            if (string == null) {
564                return;
565            }
566            Entities.HTML40.unescape(writer, string);
567        }
568
569        //-----------------------------------------------------------------------
570        /**
571         * <p>Escapes the characters in a <code>String</code> using XML entities.</p>
572         *
573         * <p>For example: <tt>"bread" & "butter"</tt> =>
574         * <tt>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</tt>.
575         * </p>
576         *
577         * <p>Supports only the five basic XML entities (gt, lt, quot, amp, apos).
578         * Does not support DTDs or external entities.</p>
579         *
580         * <p>Note that unicode characters greater than 0x7f are currently escaped to
581         *    their numerical \\u equivalent. This may change in future releases. </p>
582         *
583         * @param writer  the writer receiving the unescaped string, not null
584         * @param str  the <code>String</code> to escape, may be null
585         * @throws IllegalArgumentException if the writer is null
586         * @throws IOException if there is a problem writing
587         * @see #unescapeXml(java.lang.String)
588         */
589        public static void escapeXml(Writer writer, String str) throws IOException {
590            if (writer == null ) {
591                throw new IllegalArgumentException ("The Writer must not be null.");
592            }
593            if (str == null) {
594                return;
595            }
596            Entities.XML.escape(writer, str);
597        }
598
599        /**
600         * <p>Escapes the characters in a <code>String</code> using XML entities.</p>
601         *
602         * <p>For example: <tt>"bread" & "butter"</tt> =>
603         * <tt>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</tt>.
604         * </p>
605         *
606         * <p>Supports only the five basic XML entities (gt, lt, quot, amp, apos).
607         * Does not support DTDs or external entities.</p>
608         *
609         * <p>Note that unicode characters greater than 0x7f are currently escaped to
610         *    their numerical \\u equivalent. This may change in future releases. </p>
611         *
612         * @param str  the <code>String</code> to escape, may be null
613         * @return a new escaped <code>String</code>, <code>null</code> if null string input
614         * @see #unescapeXml(java.lang.String)
615         */
616        public static String escapeXml(String str) {
617            if (str == null) {
618                return null;
619            }
620            return Entities.XML.escape(str);
621        }
622
623        //-----------------------------------------------------------------------
624        /**
625         * <p>Unescapes a string containing XML entity escapes to a string
626         * containing the actual Unicode characters corresponding to the
627         * escapes.</p>
628         *
629         * <p>Supports only the five basic XML entities (gt, lt, quot, amp, apos).
630         * Does not support DTDs or external entities.</p>
631         *
632         * <p>Note that numerical \\u unicode codes are unescaped to their respective
633         *    unicode characters. This may change in future releases. </p>
634         *
635         * @param writer  the writer receiving the unescaped string, not null
636         * @param str  the <code>String</code> to unescape, may be null
637         * @throws IllegalArgumentException if the writer is null
638         * @throws IOException if there is a problem writing
639         * @see #escapeXml(String)
640         */
641        public static void unescapeXml(Writer writer, String str) throws IOException {
642            if (writer == null ) {
643                throw new IllegalArgumentException ("The Writer must not be null.");
644            }
645            if (str == null) {
646                return;
647            }
648            Entities.XML.unescape(writer, str);
649        }
650
651        /**
652         * <p>Unescapes a string containing XML entity escapes to a string
653         * containing the actual Unicode characters corresponding to the
654         * escapes.</p>
655         *
656         * <p>Supports only the five basic XML entities (gt, lt, quot, amp, apos).
657         * Does not support DTDs or external entities.</p>
658         *
659         * <p>Note that numerical \\u unicode codes are unescaped to their respective
660         *    unicode characters. This may change in future releases. </p>
661         *
662         * @param str  the <code>String</code> to unescape, may be null
663         * @return a new unescaped <code>String</code>, <code>null</code> if null string input
664         * @see #escapeXml(String)
665         */
666        public static String unescapeXml(String str) {
667            if (str == null) {
668                return null;
669            }
670            return Entities.XML.unescape(str);
671        }
672
673        //-----------------------------------------------------------------------
674        /**
675         * <p>Escapes the characters in a <code>String</code> to be suitable to pass to
676         * an SQL query.</p>
677         *
678         * <p>For example,
679         * <pre>statement.executeQuery("SELECT * FROM MOVIES WHERE TITLE='" +
680         *   StringEscapeUtils.escapeSql("McHale's Navy") +
681         *   "'");</pre>
682         * </p>
683         *
684         * <p>At present, this method only turns single-quotes into doubled single-quotes
685         * (<code>"McHale's Navy"</code> => <code>"McHale''s Navy"</code>). It does not
686         * handle the cases of percent (%) or underscore (_) for use in LIKE clauses.</p>
687         *
688         * see http://www.jguru.com/faq/view.jsp?EID=8881
689         * @param str  the string to escape, may be null
690         * @return a new String, escaped for SQL, <code>null</code> if null string input
691         */
692        public static String escapeSql(String str) {
693            if (str == null) {
694                return null;
695            }
696            return StringUtils.replace(str, "'", "''");
697        }
698
699        //-----------------------------------------------------------------------
700
701        /**
702         * <p>Returns a <code>String</code> value for a CSV column enclosed in double quotes,
703         * if required.</p>
704         *
705         * <p>If the value contains a comma, newline or double quote, then the
706         *    String value is returned enclosed in double quotes.</p>
707         * </p>
708         *
709         * <p>Any double quote characters in the value are escaped with another double quote.</p>
710         *
711         * <p>If the value does not contain a comma, newline or double quote, then the
712         *    String value is returned unchanged.</p>
713         * </p>
714         *
715         * see <a href="http://en.wikipedia.org/wiki/Comma-separated_values">Wikipedia</a> and
716         * <a href="http://tools.ietf.org/html/rfc4180">RFC 4180</a>.
717         *
718         * @param str the input CSV column String, may be null
719         * @return the input String, enclosed in double quotes if the value contains a comma,
720         * newline or double quote, <code>null</code> if null string input
721         * @since 2.4
722         */
723        public static String escapeCsv(String str) {
724            if (StringUtils.containsNone(str, CSV_SEARCH_CHARS)) {
725                return str;
726            }
727            try {
728                StringWriter writer = new StringWriter();
729                escapeCsv(writer, str);
730                return writer.toString();
731            } catch (IOException ioe) {
732                // this should never ever happen while writing to a StringWriter
733                throw new UnhandledException(ioe);
734            }
735        }
736
737        /**
738         * <p>Writes a <code>String</code> value for a CSV column enclosed in double quotes,
739         * if required.</p>
740         *
741         * <p>If the value contains a comma, newline or double quote, then the
742         *    String value is written enclosed in double quotes.</p>
743         * </p>
744         *
745         * <p>Any double quote characters in the value are escaped with another double quote.</p>
746         *
747         * <p>If the value does not contain a comma, newline or double quote, then the
748         *    String value is written unchanged (null values are ignored).</p>
749         * </p>
750         *
751         * see <a href="http://en.wikipedia.org/wiki/Comma-separated_values">Wikipedia</a> and
752         * <a href="http://tools.ietf.org/html/rfc4180">RFC 4180</a>.
753         *
754         * @param str the input CSV column String, may be null
755         * @param out Writer to write input string to, enclosed in double quotes if it contains
756         * a comma, newline or double quote
757         * @throws IOException if error occurs on underlying Writer
758         * @since 2.4
759         */
760        public static void escapeCsv(Writer out, String str) throws IOException {
761            if (StringUtils.containsNone(str, CSV_SEARCH_CHARS)) {
762                if (str != null) {
763                    out.write(str);
764                }
765                return;
766            }
767            out.write(CSV_QUOTE);
768            for (int i = 0; i < str.length(); i++) {
769                char c = str.charAt(i);
770                if (c == CSV_QUOTE) {
771                    out.write(CSV_QUOTE); // escape double quote
772                }
773                out.write(c);
774            }
775            out.write(CSV_QUOTE);
776        }
777
778        /**
779         * <p>Returns a <code>String</code> value for an unescaped CSV column. </p>
780         *
781         * <p>If the value is enclosed in double quotes, and contains a comma, newline
782         *    or double quote, then quotes are removed.
783         * </p>
784         *
785         * <p>Any double quote escaped characters (a pair of double quotes) are unescaped
786         *    to just one double quote. </p>
787         *
788         * <p>If the value is not enclosed in double quotes, or is and does not contain a
789         *    comma, newline or double quote, then the String value is returned unchanged.</p>
790         * </p>
791         *
792         * see <a href="http://en.wikipedia.org/wiki/Comma-separated_values">Wikipedia</a> and
793         * <a href="http://tools.ietf.org/html/rfc4180">RFC 4180</a>.
794         *
795         * @param str the input CSV column String, may be null
796         * @return the input String, with enclosing double quotes removed and embedded double
797         * quotes unescaped, <code>null</code> if null string input
798         * @since 2.4
799         */
800        public static String unescapeCsv(String str) {
801            if (str == null) {
802                return null;
803            }
804            try {
805                StringWriter writer = new StringWriter();
806                unescapeCsv(writer, str);
807                return writer.toString();
808            } catch (IOException ioe) {
809                // this should never ever happen while writing to a StringWriter
810                throw new UnhandledException(ioe);
811            }
812        }
813
814        /**
815         * <p>Returns a <code>String</code> value for an unescaped CSV column. </p>
816         *
817         * <p>If the value is enclosed in double quotes, and contains a comma, newline
818         *    or double quote, then quotes are removed.
819         * </p>
820         *
821         * <p>Any double quote escaped characters (a pair of double quotes) are unescaped
822         *    to just one double quote. </p>
823         *
824         * <p>If the value is not enclosed in double quotes, or is and does not contain a
825         *    comma, newline or double quote, then the String value is returned unchanged.</p>
826         * </p>
827         *
828         * see <a href="http://en.wikipedia.org/wiki/Comma-separated_values">Wikipedia</a> and
829         * <a href="http://tools.ietf.org/html/rfc4180">RFC 4180</a>.
830         *
831         * @param str the input CSV column String, may be null
832         * @param out Writer to write the input String to, with enclosing double quotes
833         * removed and embedded double quotes unescaped, <code>null</code> if null string input
834         * @throws IOException if error occurs on underlying Writer
835         * @since 2.4
836         */
837        public static void unescapeCsv(Writer out, String str) throws IOException {
838            if (str == null) {
839                return;
840            }
841            if (str.length() < 2) {
842                out.write(str);
843                return;
844            }
845            if ( str.charAt(0) != CSV_QUOTE || str.charAt(str.length() - 1) != CSV_QUOTE ) {
846                out.write(str);
847                return;
848            }
849
850            // strip quotes
851            String quoteless = str.substring(1, str.length() - 1);
852
853            if ( StringUtils.containsAny(quoteless, CSV_SEARCH_CHARS) ) {
854                // deal with escaped quotes; ie) ""
855                str = StringUtils.replace(quoteless, CSV_QUOTE_STR + CSV_QUOTE_STR, CSV_QUOTE_STR);
856            }
857
858            out.write(str);
859        }
860
861    }


text:
#include "ProtocolHelper/ProtocolParse/ProtocolParse.h"
#include "AquariusCore/Logger/AquariusLogger.h"

int main()
{
    // 1. Init log.
    if (!CAquariusLogger::Initialize(nullptr, "ParseProtocol"))
    {
        CAquariusLogger::Logger(LL_ERROR_FUN, "Init Logger Failed");
        return -1;
    }
    // 2. Parse protocol.
    CProtocolParse::Initialize();
    CProtocolParse::ParseProtocolGroup();
    CProtocolParse::Destroy();
}


text:
package main

import (
	"flag"
	"io"
	"io/ioutil"
	"log"
	"os"
	"sync"

	"github.com/explicite/quartz/bh1750"
	"github.com/explicite/quartz/lps331ap"
	"github.com/explicite/quartz/si7021"
	"github.com/influxdata/influxdb/client/v2"
)

var (
	logTrace   *log.Logger
	logInfo    *log.Logger
	logWarning *log.Logger
	logError   *log.Logger
)

func logging(
	traceHandle io.Writer,
	infoHandle io.Writer,
	warningHandle io.Writer,
	errorHandle io.Writer) {

	logTrace = log.New(traceHandle,
		"TRACE: ",
		log.Ldate|log.Ltime|log.Lshortfile)

	logInfo = log.New(infoHandle,
		"INFO: ",
		log.Ldate|log.Ltime|log.Lshortfile)

	logWarning = log.New(warningHandle,
		"WARNING: ",
		log.Ldate|log.Ltime|log.Lshortfile)

	logError = log.New(errorHandle,
		"ERROR: ",
		log.Ldate|log.Ltime|log.Lshortfile)
}

var addr = flag.String("addr", "", "database addr")
var db = flag.String("db", "", "database name")
var user = flag.String("user", "", "database user")
var pass = flag.String("pass", "", "database password")

func init() {
	flag.Parse()
	if *addr == "" {
		panic("set database addr")
	}

	if *db == "" {
		panic("set database name")
	}

	if *user == "" {
		panic("set database user")
	}

	if *pass == "" {
		panic("set database pass")
	}
}

func merge(cs ...<-chan client.Point) <-chan client.Point {
	var wg sync.WaitGroup
	out := make(chan client.Point)

	output := func(c <-chan client.Point) {
		for n := range c {
			out <- n
		}
		wg.Done()
	}
	wg.Add(len(cs))
	for _, c := range cs {
		go output(c)
	}

	go func() {
		wg.Wait()
		close(out)
	}()
	return out
}

func main() {
	logging(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)

	sampling := 60.0 //sec

	// Setup influxdb udp connection
	// Make client
	c, cErr := client.NewHTTPClient(client.HTTPConfig{
		Addr:     *addr,
		Username: *user,
		Password: *pass,
	})

	if cErr != nil {
		panic(cErr)
	}

	logInfo.Printf("influxdb connection established (%s, %s)\n", *addr, *user)

	logInfo.Println("lps331AP initialization")
	l := lps331ap.New(0x5d, 0x01, sampling)

	logInfo.Println("bh1750 initialization")
	b := bh1750.New(0x23, 0x01, sampling)

	logInfo.Println("si7021 initialization")
	s := si7021.New(0x40, 0x01, sampling)

	points := merge(l, b, s)
	batchSize := 30

	for {
		// Create a new point batch
		bp, bpErr := client.NewBatchPoints(client.BatchPointsConfig{
			Database:  *db,
			Precision: "s",
		})

		if bpErr != nil {
			panic(bpErr)
		}

		for i := 0; i < batchSize; i++ {
			p := <-points
			bp.AddPoint(&p)
		}

		writeErr := c.Write(bp)
		if writeErr != nil {
			logInfo.Printf("Write batch points with error: %v", writeErr)
		}
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class wah.giovann.csvhandler.CSVRecord (CSV Handler 1.0.8-SNAPSHOT API)</title>
<meta name="date" content="2017-10-11">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
wah.giovann.csvhandler.CSVRecord

Packages that use CSVRecord

Package
Description

wah.giovann.csvhandler

wah.giovann.csvhandler.error

Uses of CSVRecord in wah.giovann.csvhandler

Methods in wah.giovann.csvhandler that return CSVRecord

Modifier and Type
Method and Description

CSVRecord
CSVArray.insertData(ArrayList<String> data)

Creates and inserts a new CSVRecord data item into the array.

CSVRecord
CSVArray.insertData(ArrayList<String> data,
          int index)

Creates and inserts a new CSVRecord data item into the array, at the specified index.

Constructors in wah.giovann.csvhandler with parameters of type CSVRecord

Constructor and Description

CSVRecord(CSVRecord other)

Uses of CSVRecord in wah.giovann.csvhandler.error

Constructors in wah.giovann.csvhandler.error with parameters of type CSVRecord

Constructor and Description

ValueConversionException(int err,
                        int i,
                        CSVRecord r)

ValueConversionException(int err,
                        String k,
                        CSVRecord r)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2017. All rights reserved.


text:
namespace flutter_runner {

typedef void (*ThreadEntry)(Thread*);

namespace {

size_t NextPageSizeMultiple(size_t size) {
  const size_t page_size = sysconf(_SC_PAGE_SIZE);
  FML_CHECK(page_size != 0);

  size = std::max<size_t>(size, page_size);

  size_t rem = size % page_size;

  if (rem == 0) {
    return size;
  }

  return size + page_size - rem;
}

bool CreateThread(pthread_t* thread,
                  ThreadEntry main,
                  Thread* argument,
                  size_t stack_size) {
  pthread_attr_t thread_attributes;

  if (pthread_attr_init(&thread_attributes) != 0) {
    return false;
  }

  stack_size = std::max<size_t>(NextPageSizeMultiple(PTHREAD_STACK_MIN),
                                NextPageSizeMultiple(stack_size));

  if (pthread_attr_setstacksize(&thread_attributes, stack_size) != 0) {
    return false;
  }

  auto result =
      pthread_create(thread, &thread_attributes,
                     reinterpret_cast<void* (*)(void*)>(main), argument);

  pthread_attr_destroy(&thread_attributes);

  return result == 0;
}

}  // anonymous namespace

Thread::Thread() {
  loop_.reset(MakeObservableLoop(false));
  valid_ = CreateThread(
      &thread_, [](Thread* thread) { thread->Main(); }, this, 1 << 20);
}

Thread::~Thread() {
  Join();
}

bool Thread::IsValid() const {
  return valid_;
}

async_dispatcher_t* Thread::dispatcher() const {
  return loop_->dispatcher();
}

void Thread::Main() {
  async_set_default_dispatcher(loop_->dispatcher());
  loop_->Run();
}

void Thread::Quit() {
  loop_->Quit();
}

bool Thread::Join() {
  if (!valid_) {
    return false;
  }

  bool result = pthread_join(thread_, nullptr) == 0;
  valid_ = false;
  return result;
}

}  // namespace flutter_runner


text:
namespace StockSharp.Algo.Storages.Binary.Snapshot
{
	using System;

	static class SnapshotVersions
	{
		public static readonly Version V20 = new(2, 0);
		public static readonly Version V21 = new(2, 1);
		public static readonly Version V22 = new(2, 2);
		public static readonly Version V23 = new(2, 3);
		public static readonly Version V24 = new(2, 4);
	}
}


text:
<?php

require_once(dirname(__FILE__)."/config.php");
include(DEDEDATA.'/mark/inc_photowatermark_config.php');
if(empty($activepath))
{
    $activepath = '';
}
if(empty($imgstick))
{
    $imgstick = '';
}
$noeditor = isset($noeditor)? $noeditor : '';
$activepath = str_replace('.', '', $activepath);
$activepath = preg_replace("#\/{1,}#", '/', $activepath);
if(strlen($activepath) < strlen($cfg_medias_dir))
{
    $activepath = $cfg_medias_dir;
}
$inpath = $cfg_basedir.$activepath;
$activeurl = '..'.$activepath;

if(empty($f))
{
    $f = 'form1.picname';
}
if(empty($v))
{
    $v = 'picview';
}
if(empty($comeback))
{
    $comeback = '';
}
$addparm = '';
if (!empty($CKEditor))
{
    $addparm = '&CKEditor='.$CKEditor;
    $f = $CKEditor;
}
if (!empty($CKEditorFuncNum))
{
    $addparm .= '&CKEditorFuncNum='.$CKEditorFuncNum;
}

if (!empty($noeditor))
{
    $addparm .= '&noeditor=yes';
}
?>

<meta http-equiv='Content-Type' content='text/html; charset=<?php echo $cfg_soft_lang; ?>'>
<title>图片浏览器</title>
<link href='../../plus/img/base.css' rel='stylesheet' type='text/css'>

预览
点击名称选择图片
文件大小
最后修改时间

点击"V"预览图片,点击图片名选择图片,显示图片后点击该图片关闭预览。

<?php
$dh = dir($inpath);
$ty1="";
$ty2="";
while($file = $dh->read()) {

    //-----计算文件大小和创建时间
    if($file!="." && $file!=".." && !is_dir("$inpath/$file")){
        $filesize = filesize("$inpath/$file");
        $filesize = $filesize / 1024;
        if($filesize != "")
        if($filesize < 0.1){
            @list($ty1, $ty2) = split("\.", $filesize);
            $filesize = $ty1.".".substr($ty2, 0, 2);
        }
        else{
            @list($ty1, $ty2) = split("\.", $filesize);
            $filesize = $ty1.".".substr($ty2, 0, 1);
        }
        $filetime = filemtime("$inpath/$file");
        $filetime = MyDate("Y-m-d H:i:s", $filetime);
    }

    if($file == ".") continue;
    else if($file == "..")
    {
        if($activepath == "") continue;
        $tmp = preg_replace("#[\/][^\/]*$#i", "", $activepath);
        $line = "\n

   上级目录
    当前目录:$activepath

   ";
        echo $line;
    }
    else if(is_dir("$inpath/$file"))
    {
        if(preg_match("#^_(.*)$#i", $file)) continue; #屏蔽FrontPage扩展目录和linux隐蔽目录
        if(preg_match("#^\.(.*)$#i", $file)) continue;
        $line = "\n

   $file

";
        echo "$line";
    }
    else if(preg_match("#\.(gif|png)#i", $file))
    {
        $reurl = "$activeurl/$file";
        $reurl = preg_replace("#^\.\.#", "", $reurl);
        if($cfg_remote_site=='Y' && $remoteuploads == 1)
         {
           $reurl  = $remoteupUrl.$reurl;
        }else{
            $reurl = $reurl;
        }

        if($file==$comeback) $lstyle = " style='color:red' ";
        else  $lstyle = "";

        $line = "\n

   $file
   $filesize KB
   $filetime

";
        echo "$line";
    }
    else if(preg_match("#\.(jpg)#i", $file))
    {
        $reurl = "$activeurl/$file";
        $reurl = preg_replace("#^\.\.#", "", $reurl);
        if($cfg_remote_site=='Y' && $remoteuploads == 1)
         {
           $reurl  = $remoteupUrl.$reurl;
        }else{
            $reurl = $reurl;
        }

        if($file==$comeback) $lstyle = " style='color:red' ";
        else  $lstyle = "";

        $line = "\n

   $file

   $filesize KB
   $filetime

";
        echo "$line";
    }
}//End Loop
$dh->close();
?>

<form action='select_images_post.php' method='POST' enctype="multipart/form-data" name='myform'>
<?php $noeditor = !empty($noeditor)?"<input type='hidden' name='noeditor' value='yes'>":''; echo $noeditor;//(2011.08.25 根据用户反馈修正图片上传回调 by:织梦的鱼)?>
<input type='hidden' name='activepath' value='<?php echo $activepath?>'>
<input type='hidden' name='f' value='<?php echo $f?>'>
<input type='hidden' name='v' value='<?php echo $v?>'>
<input type='hidden' name='imgstick' value='<?php echo $imgstick?>'>
<input type='hidden' name='CKEditorFuncNum' value='<?php echo isset($CKEditorFuncNum)? $CKEditorFuncNum : 1;?>'>
<input type='hidden' name='job' value='upload'>

   上 传: <input type='file' name='imgfile' style='width:250px'/>
  <input type='checkbox' name='needwatermark' value='1' class='np' <?php if($photo_markup=='1') echo "checked"; ?> />水印
  <input type='checkbox' name='resize' value='1' class='np' />缩小
  宽:<input type='text' style='width:30' name='iwidth' value='<?php echo $cfg_ddimg_width?>' />
  高:<input type='text' style='width:30' name='iheight' value='<?php echo $cfg_ddimg_height?>' />
  <input type='submit' name='sb1' value='确定' />

</form>


text:
<?php

namespace Fup\UnividaBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * ActaReunionRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ActaReunionRepository extends EntityRepository
{
}


text:
thinner:
	gcc -std=c99 thinner.c -o thinner -lIL -lm

clean:
	rm thinner

all: clean thinner


text:
bitstarter
==========

Coursera's Online Course "Startup Engineering" (by Balaji S. Srinivasan, Vijay S. Pande) | Class Project


text:
var fs = require("fs"),
    mergesort = require("./mergesort"),
    isBinaryFile = require("isbinaryfile");

function readPath(options, path, size) {
  var text = null;

  if (options.onFilepathSearchFn && (text = options.onFilepathSearchFn(path)))
    return text;

  var fd = fs.openSync(path, "r");
  try {
    var binaryBuffer = Buffer.alloc(512);
    var bytesRead = fs.readSync(fd, binaryBuffer, 0, 512);

    if (!isBinaryFile(binaryBuffer, bytesRead)) {
      var remainingBytes = size - bytesRead;
      if (remainingBytes > 0) {
        var textBuffer = Buffer.alloc(size);
        binaryBuffer.copy(textBuffer, 0, 0, bytesRead);
        bytesRead += fs.readSync(fd, textBuffer, bytesRead, remainingBytes);
        text = textBuffer.toString("utf8", 0, bytesRead);
      }
      else {
        text = binaryBuffer.toString("utf8", 0, bytesRead);
      }
    }
    return text;
  } finally {
    fs.closeSync(fd);
  }
}

function Finalizer(fpath, options, allPaths, allStats, printCb, done) {
  var dirKeys = mergesort(Object.keys(allPaths)), parent = "", d, dLength;

  if (options.list || !options.query) {
    var results = "";
    var joinChar = options.list ? "\n" : ":\n";
    for (d = 0, dLength = dirKeys.length; d < dLength; d++) {
      parent = allPaths[dirKeys[d]];
      results += fpath + mergesort(parent).join(joinChar + fpath) + joinChar;
    }

    printCb(results);
  }
  else {
    var allFiles = [], originalQuery = options.query, originalQueryClean = options.queryClean;

    for (d = 0, dLength = dirKeys.length; d < dLength; d++) {
      parent = allPaths[dirKeys[d]];
      allFiles = mergesort(parent);

      for (var m = 0, allFilesLength = allFiles.length; m < allFilesLength; m++) {
        var filepath = allFiles[m],
            strContents = readPath(options, fpath + filepath, allStats[filepath].size);
        if (originalQueryClean.test(strContents)) {
          var contentsSplit = strContents.split("\n"),
              lines = "",
              totalMatches = strContents.match(originalQuery).length,
              matchCount = totalMatches;

            if (typeof options.replacement == "string") {
              var replacedContents = strContents.replace(originalQuery, options.replacement);
              // TODO: could we be better here?
              fs.writeFileSync(fpath + filepath, replacedContents);
            }

            for (var i = 0, strLength = contentsSplit.length; matchCount; i++) {
              var matchLine = contentsSplit[i];
              if (originalQueryClean.test(matchLine)) {

                if (options.ackmate)
                  var strPos = [], lastMatchLength;

                // we're offsetting by just checking matchCount in the for conditional
                while ( originalQuery.test(matchLine) ) {
                  if (options.ackmate) {
                    lastMatchLength = RegExp.lastMatch.length;
                    strPos.push(originalQuery.lastIndex - lastMatchLength + " " + lastMatchLength);
                  }
                  matchCount--;
                }

                if (options.replacement)
                  matchLine = matchLine.replace(originalQuery, options.replacement);

                if (options.ackmate)
                  lines += (i+1) + ";" + strPos.join(",") + ":" + matchLine + "\n";
                else
                  lines += "\t" + (i+1) + ": " + matchLine + "\n";

                originalQuery.lastIndex = 0;
              }
            }

            printCb(options.ackmate
              ? ":" + fpath + filepath
              : fpath + filepath + ":", lines, totalMatches);
          }
      }
    }
    done();
  }
}

module.exports = Finalizer;


text:
package org.seasar.doma.jdbc.criteria.entity;

import java.io.Serializable;
import java.math.BigDecimal;
import org.seasar.doma.Entity;
import org.seasar.doma.Id;
import org.seasar.doma.OriginalStates;
import org.seasar.doma.Table;
import org.seasar.doma.Version;
import org.seasar.doma.jdbc.entity.NamingType;

@Entity(naming = NamingType.SNAKE_UPPER_CASE)
@Table(catalog = "CATA", quote = true)
public class Emp implements Serializable {

  private static final long serialVersionUID = -6511179565163144602L;

  @Id Integer id;

  String name;

  BigDecimal salary;

  @Version Integer version;

  @OriginalStates public Emp originalStates;

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public BigDecimal getSalary() {
    return salary;
  }

  public void setSalary(BigDecimal salary) {
    this.salary = salary;
  }

  public Integer getVersion() {
    return version;
  }

  public void setVersion(Integer version) {
    this.version = version;
  }
}


text:
package org.workcraft.plugins.plato.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Scanner;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.workcraft.Framework;
import org.workcraft.dom.visual.SizeHelper;
import org.workcraft.util.GUI;
import org.workcraft.util.DialogUtils;

@SuppressWarnings("serial")
public class PlatoWriterDialog extends JDialog {

    private static File lastFileUsed, lastDirUsed;

    private final JPanel content, btnPanel;
    private JTextArea conceptsText;
    private JCheckBox dotLayoutCheckBox;
    private boolean changed = false, translate = false;
    private final boolean fst;
    private static DefaultListModel<String> includeList = new DefaultListModel<String>();

    public PlatoWriterDialog(boolean fst) {
        super(Framework.getInstance().getMainWindow(), "Write and translate Concepts", ModalityType.APPLICATION_MODAL);

        this.fst = fst;

        content = new JPanel();
        content.setLayout(new BorderLayout());

        btnPanel = new JPanel();
        btnPanel.setLayout(new BorderLayout());

        createScrollPane();
        createFileBtnPanel();
        createFinalBtnPanel();

        content.add(btnPanel, BorderLayout.SOUTH);

        getRootPane().registerKeyboardAction(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);

        setContentPane(content);
        setMinimumSize(new Dimension(1000, 500));
        pack();
        this.setLocationRelativeTo(Framework.getInstance().getMainWindow());

    }

    private void createScrollPane() {
        JLabel conceptsLabel = new JLabel("Enter concepts: ");
        content.add(conceptsLabel, BorderLayout.NORTH);

        conceptsText = new JTextArea();
        conceptsText.setMargin(SizeHelper.getTextMargin());
        conceptsText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, SizeHelper.getMonospacedFontSize()));
        conceptsText.setText(getDefaultComponentText());
        if (lastFileUsed != null && lastFileUsed.exists()) {
            try {
                conceptsText.setText(readFile(lastFileUsed));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        conceptsText.addKeyListener(new KeyListener() {

            @Override
            public void keyTyped(KeyEvent e) {
                changed = true;
            }

            @Override
            public void keyPressed(KeyEvent e) {
                // Do nothing
            }

            @Override
            public void keyReleased(KeyEvent e) {
                // Do nothing
            }

        });

        JScrollPane scrollPane = new JScrollPane(conceptsText);

        content.add(scrollPane, BorderLayout.CENTER);
    }

    private void createFileBtnPanel() {
        JButton openFileBtn = GUI.createDialogButton("Open file");
        JButton saveFileBtn = GUI.createDialogButton("Save to file");
        JButton componentBtn = GUI.createDialogButton("New component");
        JButton systemBtn = GUI.createDialogButton("New system");
        JButton includeBtn = GUI.createDialogButton("Included files");
        dotLayoutCheckBox = new JCheckBox("Use dot layout");
        JPanel fileBtnPanel = new JPanel();
        fileBtnPanel.add(openFileBtn);
        fileBtnPanel.add(saveFileBtn);
        fileBtnPanel.add(componentBtn);
        fileBtnPanel.add(systemBtn);
        fileBtnPanel.add(includeBtn);
        if (!fst) {
            fileBtnPanel.add(dotLayoutCheckBox);
        }

        openFileBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser();
                chooser.setFileFilter(new FileNameExtensionFilter("Haskell/Concept file (.hs)", "hs"));
                chooser.setCurrentDirectory(lastDirUsed);
                if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                    File f = chooser.getSelectedFile();
                    try {
                        if (!f.exists()) {
                            throw new FileNotFoundException();
                        }

                        conceptsText.setText(readFile(f));
                        updateLastDirUsed();
                    } catch (FileNotFoundException e1) {
                        DialogUtils.showError(e1.getMessage());
                    }

                }
            }

        });

        saveFileBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser();
                chooser.setFileFilter(new FileNameExtensionFilter("Haskell/Concept file (.hs)", "hs"));
                chooser.setCurrentDirectory(lastDirUsed);
                if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
                    File file = chooser.getSelectedFile();
                    if (!file.getName().endsWith(".hs")) {
                        file = new File(file.getAbsolutePath() + ".hs");
                    }
                    PrintStream concepts;
                    try {
                        concepts = new PrintStream(file);
                        String text = conceptsText.getText();
                        concepts.print(text);
                        concepts.close();
                        lastFileUsed = file;
                        changed = false;
                        updateLastDirUsed();
                    } catch (FileNotFoundException ex) {
                    }
                }
            }

        });

        componentBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                conceptsText.setText(getDefaultComponentText());
                lastFileUsed = null;
                changed = false;
            }

        });

        systemBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                conceptsText.setText(getDefaultSystemText());
                lastFileUsed = null;
                changed = false;
            }

        });

        final PlatoIncludesDialog dialog = new PlatoIncludesDialog(this, lastDirUsed, includeList);

        includeBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                dialog.setVisible(true);
            }

        });

        btnPanel.add(fileBtnPanel, BorderLayout.WEST);
    }

    private void createFinalBtnPanel() {
        JButton translateBtn = GUI.createDialogButton("Translate");
        JButton cancelBtn = GUI.createDialogButton("Cancel");
        JPanel finalBtnPanel = new JPanel();

        translateBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                translate = true;
                setVisible(false);
            }

        });

        cancelBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                translate = false;
                setVisible(false);
            }

        });

        finalBtnPanel.add(translateBtn);
        finalBtnPanel.add(cancelBtn);

        btnPanel.add(finalBtnPanel, BorderLayout.EAST);
    }

    private void updateLastDirUsed() {
        if (lastFileUsed != null) {
            String lastFilePath = lastFileUsed.getAbsolutePath();
            String lastFileName = lastFileUsed.getName();
            String lastFileDir = lastFilePath.replace(lastFileName, "");
            lastDirUsed = new File(lastFileDir);
        } else {
            lastDirUsed = Framework.getInstance().getWorkingDirectory();
        }
    }

    private String getDefaultComponentText() {
        String result = "module Concept where\n" + "\n" + "import Tuura.Concept.";
        result = result + (fst ? "FSM" : "STG");
        result = result + "\n\n" + "component a b c = \n" + "  where";
        return result;
    }

    private String getDefaultSystemText() {
        String result = "module Concept where\n" + "\n" + "import Tuura.Concept.";
        result = result + (fst ? "FSM" : "STG") + "\n\n";
        result = result + "data Signal = A | B | C deriving (Bounded, Enum, Eq)";
        result = result + "\n\n" + "system = \n" + "  where";
        return result;
    }

    private String readFile(File file) throws FileNotFoundException {

        Scanner scanner = new Scanner(file);
        String fileText = new String();
        if (scanner.hasNextLine()) {
            do {
                fileText = fileText + scanner.nextLine() + "\n";
            } while (scanner.hasNextLine());
            scanner.close();
            conceptsText.setText(fileText);

            lastFileUsed = file;
            changed = false;
        }
        return fileText == "" ? "" : fileText;
    }

    public boolean getTranslate() {
        return translate;
    }

    public File getFile() {
        if (lastFileUsed != null && !changed) {
            return lastFileUsed;
        } else {
            try {
                lastFileUsed = File.createTempFile("plato-", ".hs");
                lastFileUsed.deleteOnExit();
                PrintWriter writer = new PrintWriter(lastFileUsed);
                writer.print(conceptsText.getText());
                writer.close();
            } catch (IOException e) {
            }
        }
        return lastFileUsed;
    }

    public boolean getDotLayoutState() {
        return dotLayoutCheckBox.isSelected();
    }

    public Object[] getIncludeList() {
        Object[] list = includeList.toArray();
        if ((list.length == 1) && (list[0].toString() == "")) {
            return new Object[0];
        }
        return list;
    }

    public Boolean isSystem() {
        if (conceptsText.getText().contains("system = ")) {
            return true;
        }
        return false;
    }

}


text:
echo build aurelia-bundle
node r.js -o name=aurelia-bundle-manifest baseUrl=. mainConfigFile=main-config.js exclude=core-js out=aurelia-bundle.js optimize=none

echo build aurelia-bundle-latest
node r.js -o name=aurelia-bundle-manifest baseUrl=. mainConfigFile=main-config-latest.js exclude=core-js out=aurelia-bundle-latest.js optimize=none

cp -f aurelia-bundle.js aurelia-bundle-latest.js scripts/aurelia
cp -f aurelia-latest/*/dist/amd/*.d.ts typings/aurelia


text:
Encapsulates a JSON object.

```csharp
public sealed class ServiceObject
```

## Public Members

| name | description |
| --- | --- |
| static [Create](ServiceObject/Create.md)(…) | Creates an instance from a `Newtonsoft.Json.Linq.JObject`. (2 methods) |
| [AsJObject](ServiceObject/AsJObject.md)() | Returns a `Newtonsoft.Json.Linq.JObject` that is temporarily associated with this `ServiceObject`. |
| [AsJsonObject](ServiceObject/AsJsonObject.md)() | Returns a `System.Text.Json.Nodes.JsonObject` that is temporarily associated with this `ServiceObject`. |
| [IsEquivalentTo](ServiceObject/IsEquivalentTo.md)(…) | Returns true if the JSON objects are equivalent. |
| [ToJObject](ServiceObject/ToJObject.md)() | Returns a new `Newtonsoft.Json.Linq.JObject` equivalent to this `ServiceObject`. |
| [ToJsonObject](ServiceObject/ToJsonObject.md)() | Returns a new `System.Text.Json.Nodes.JsonObject` equivalent to this `ServiceObject`. |
| override [ToString](ServiceObject/ToString.md)() | Returns a JSON string for the JSON object. |
| [implicit operator](ServiceObject/op_Implicit.md) |  (2 operators) |

## See Also

* namespace [Facility.Core](../Facility.Core.md)
* [ServiceObject.cs](https://github.com/FacilityApi/FacilityCSharp/tree/master/src/Facility.Core/ServiceObject.cs)

<!-- DO NOT EDIT: generated by xmldocmd for Facility.Core.dll -->


text:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/Delectable"/>


text:
package org.apache.kafka.streams.state.internals;

import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.streams.processor.ProcessorContext;
import org.apache.kafka.streams.processor.StateStoreContext;
import org.apache.kafka.streams.processor.internals.ProcessorContextImpl;
import org.apache.kafka.streams.query.Position;
import org.apache.kafka.streams.state.WindowStore;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static java.time.Instant.ofEpochMilli;
import static org.apache.kafka.common.utils.Utils.mkEntry;
import static org.apache.kafka.common.utils.Utils.mkMap;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class ChangeLoggingTimestampedWindowBytesStoreTest {

    private final byte[] value = {0};
    private final byte[] valueAndTimestamp = {0, 0, 0, 0, 0, 0, 0, 42, 0};
    private final Bytes bytesKey = Bytes.wrap(value);

    @Mock
    private WindowStore<Bytes, byte[]> inner;
    @Mock
    private ProcessorContextImpl context;
    private ChangeLoggingTimestampedWindowBytesStore store;

    private final static Position POSITION = Position.fromMap(mkMap(mkEntry("", mkMap(mkEntry(0, 1L)))));

    @Before
    public void setUp() {
        store = new ChangeLoggingTimestampedWindowBytesStore(inner, false);
        store.init((StateStoreContext) context, store);
    }

    @After
    public void tearDown() {
        verify(inner).init((StateStoreContext) context, store);
    }

    @SuppressWarnings("deprecation")
    @Test
    public void shouldDelegateDeprecatedInit() {
        store.init((ProcessorContext) context, store);

        verify(inner).init((ProcessorContext) context, store);
    }

    @Test
    public void shouldDelegateInit() {
        // testing the combination of setUp and tearDown
    }

    @Test
    @SuppressWarnings("deprecation")
    public void shouldLogPuts() {
        final Bytes key = WindowKeySchema.toStoreKeyBinary(bytesKey, 0, 0);
        when(inner.getPosition()).thenReturn(Position.emptyPosition());

        store.put(bytesKey, valueAndTimestamp, context.timestamp());

        verify(inner).put(bytesKey, valueAndTimestamp, 0);
        verify(context).logChange(store.name(), key, value, 42, Position.emptyPosition());
    }

    @Test
    public void shouldLogPutsWithPosition() {
        final Bytes key = WindowKeySchema.toStoreKeyBinary(bytesKey, 0, 0);
        when(inner.getPosition()).thenReturn(POSITION);

        store.put(bytesKey, valueAndTimestamp, context.timestamp());

        verify(inner).put(bytesKey, valueAndTimestamp, 0);
        verify(context).logChange(store.name(), key, value, 42, POSITION);
    }

    @Test
    public void shouldDelegateToUnderlyingStoreWhenFetching() {
        store.fetch(bytesKey, ofEpochMilli(0), ofEpochMilli(10));

        verify(inner).fetch(bytesKey, 0, 10);
    }

    @Test
    public void shouldDelegateToUnderlyingStoreWhenFetchingRange() {
        store.fetch(bytesKey, bytesKey, ofEpochMilli(0), ofEpochMilli(1));

        verify(inner).fetch(bytesKey, bytesKey, 0, 1);
    }

    @Test
    @SuppressWarnings("deprecation")
    public void shouldRetainDuplicatesWhenSet() {
        store = new ChangeLoggingTimestampedWindowBytesStore(inner, true);
        store.init((StateStoreContext) context, store);
        final Bytes key1 = WindowKeySchema.toStoreKeyBinary(bytesKey, 0, 1);
        final Bytes key2 = WindowKeySchema.toStoreKeyBinary(bytesKey, 0, 2);
        when(inner.getPosition()).thenReturn(Position.emptyPosition());

        store.put(bytesKey, valueAndTimestamp, context.timestamp());
        store.put(bytesKey, valueAndTimestamp, context.timestamp());

        verify(inner, times(2)).put(bytesKey, valueAndTimestamp, 0);
        verify(context).logChange(store.name(), key1, value, 42L, Position.emptyPosition());
        verify(context).logChange(store.name(), key2, value, 42L, Position.emptyPosition());
    }

}


text:
from docutils.parsers.rst import Directive, directives
from docutils import nodes

from acrylamid.lib.requests import get, HTTPError, URLError
from acrylamid import log

class Gist(Directive):
    """`GitHub:Gist <https://gist.github.com/>`__ embedding (file is optional).

  .. code-block:: rst

      .. gist:: 4145152
         :file: transmission.rb
    """

    required_arguments = 1
    optional_arguments = 1
    option_spec = {'file': directives.unchanged}
    final_argument_whitespace = True
    has_content = False

    def get_raw_gist_with_filename(self, gistID, filename):
        url = "https://raw.github.com/gist/%s/%s" % (gistID, filename)
        try:
            return get(url).read()
        except (URLError, HTTPError) as e:
            log.exception('Failed to access URL %s : %s' % (url, e))
        return ''

    def get_raw_gist(self, gistID):
        url = "https://raw.github.com/gist/%s" % (gistID)
        try:
            return get(url).read()
        except (URLError, HTTPError) as e:
            log.exception('Failed to access URL %s : %s' % (url, e))
        return ''

    def run(self):

        gistID = self.arguments[0].strip()

        if 'file' in self.options:
            filename = self.options['file']
            rawGist = (self.get_raw_gist_with_filename(gistID, filename))
            embedHTML = '<script src="https://gist.github.com/%s.js?file=%s"></script>' % \
                (gistID, filename)
        else:
            rawGist = (self.get_raw_gist(gistID))
            embedHTML = '<script src="https://gist.github.com/%s.js"></script>' % gistID

        return [nodes.raw('', embedHTML, format='html'),
                nodes.raw('', '<noscript>', format='html'),
                nodes.literal_block('', rawGist),
                nodes.raw('', '</noscript>', format='html')]

def register(roles, directives):
    directives.register_directive('gist', Gist)


text:
from __future__ import unicode_literals

from django.db import models, migrations

def create_timesheets(apps, schema_editor):
    import calendar
    from datetime import date, timedelta

    ClubJournalEntry    = apps.get_model('domecek', 'ClubJournalEntry')
    Timesheet           = apps.get_model('domecek', 'Timesheet')

    for club_entry in ClubJournalEntry.objects.all():
        start   = date(club_entry.start.year, club_entry.start.month, 1)
        end     = date(club_entry.start.year, club_entry.start.month, calendar.monthrange(club_entry.start.year, club_entry.start.month)[1])
        for leader in club_entry.leaders.all():
            ts = Timesheet.objects.get_or_create(
                leader      = leader,
                start       = start,
                end         = end,
            )[0]
    Timesheet.objects.filter(end__lt = date.today() - timedelta(10)).update(submitted=True)

class Migration(migrations.Migration):

    dependencies = [
        ('domecek', '0024_timesheets'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='timesheet',
            options={'ordering': ('-start',), 'verbose_name': 'timesheet', 'verbose_name_plural': 'timesheets'},
        ),
        migrations.RemoveField(
            model_name='timesheetentry',
            name='timesheet',
        ),
        migrations.AddField(
            model_name='timesheetentry',
            name='leader',
            field=models.ForeignKey(related_name='timesheet_entries', default=None, verbose_name='leader', to='domecek.Leader'),
            preserve_default=False,
        ),
        migrations.AlterUniqueTogether(
            name='timesheet',
            unique_together=set([('leader', 'start', 'end')]),
        ),
        migrations.RunPython(create_timesheets),
    ]


text:
package org.nkjmlab.gis.datum;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.nkjmlab.gis.datum.LatLon.Detum;
import org.nkjmlab.gis.datum.LatLon.Unit;

public class Basis {

  public static final Basis DEGREE_WGS;
  private final Unit unit;
  private final Detum detum;
  private static final Map<Detum, Map<Unit, Basis>> map = new HashMap<>();

  static {
    map.put(Detum.TOKYO, new HashMap<>());
    map.put(Detum.WGS84, new HashMap<>());
    DEGREE_WGS = of(Unit.DEGREE, Detum.WGS84);
  }

  protected Basis(Unit unit, Detum detum) {
    this.unit = unit;
    this.detum = detum;
  }

  public Unit getUnit() {
    return unit;
  }

  public Detum getDetum() {
    return detum;
  }

  public static Basis of(Unit unit, Detum detum) {
    Basis b = map.get(detum).get(unit);
    if (b != null) {
      return b;
    }
    b = new Basis(unit, detum);
    map.get(detum).put(unit, b);
    return b;
  }

  @Override
  public int hashCode() {
    return Objects.hash(detum, unit);
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (!(obj instanceof Basis))
      return false;
    Basis other = (Basis) obj;
    return detum == other.detum && unit == other.unit;
  }

  @Override
  public String toString() {
    return "Basis [unit=" + unit + ", detum=" + detum + "]";
  }

}


text:
typedef void(^QRUrlBlock)(NSString *url);
@interface QRViewController : UIViewController

@property (nonatomic, copy) QRUrlBlock qrUrlBlock;

@end


text:
@extends('layout.email')
@section('content')

Hi, {{$userObj->first_name.' '.$userObj->last_name}}

Thank you for the donation!!. We have received $@if($mailFrom == "PAYPAL"){{ number_format($fundObj->amount,2) }}@else{{ number_format($zcashTransaction->amount,2) }}@endif and the transaction details are below.

            Transaction Details

        @if($mailFrom == "PAYPAL")

                Transaction Id
                {{$paypalTransaction->donate_paypal_id}}

                Amount
                ${{ number_format($fundObj->amount,2) }}

        @else

                Address
                {{$zcashTransaction->zcash_address}}

                Amount
                ${{ number_format($zcashTransaction->amount,2) }}

                Transaction Id
                {{$zcashTransaction->transaction_id}}

        @endif

Regards,

info@javul.org

@endsection


text:
// Copyright 2011-2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.security.zynamics.binnavi.Gui.GraphWindows.NodeTaggingTree;

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

import com.google.security.zynamics.binnavi.Tagging.ITagManager;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.ZyGraph;

/**
 * Panel that shows the node tagging tree.
 */
public final class CTaggingPanel extends JPanel {
  /**
   * Used for serialization.
   */
  private static final long serialVersionUID = 1584298280294554416L;

  /**
   * The node tagging tree.
   */
  private final CTagsTree m_tagsTree;

  /**
   * Creates a new panel object.
   *
   * @param parent Parent window used for dialogs.
   * @param graph Graph whose nodes are tagged.
   * @param manager Provides tag information.
   */
  public CTaggingPanel(final JFrame parent, final ZyGraph graph, final ITagManager manager) {
    super(new BorderLayout());

    m_tagsTree = new CTagsTree(parent, graph, manager);

    final JScrollPane pane = new JScrollPane(m_tagsTree);
    pane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    add(pane);

    setBorder(new TitledBorder(new LineBorder(Color.LIGHT_GRAY, 1, true), "Tagging"));

    setDoubleBuffered(true);
  }

  /**
   * Returns the tag tree.
   *
   * @return The tag tree.
   */
  public CTagsTree getTree() {
    return m_tagsTree;
  }
}


text:
package bgames.thing;

import java.util.function.Function;
import java.util.ArrayList;

import bgames.trie.Trie;
import bgames.trie.FindOrCreate;
import bgames.trie.Assign;
import bgames.field.Field;
import bgames.field.ValueField;
import bgames.other.ParseState;
import bgames.stack.controls.Block;

public class Thing {
  private final String id;
  private final Trie<Field> fields;

  public Thing(String id, Trie<Field> fields) {
    this.id = id;
    this.fields = fields;
  }

  public String getId() {
    return id;
  }
  public Thing setId(String id) {
    return new Thing(id, this.fields);
  }

  public Trie<Field> getFields() {
    return fields;
  }
  public Thing setFields(Trie<Field> fields) {
    if (fields == this.fields) {
      return this;
    }
    return new Thing(this.id, fields);
  }

  public static class GetFields implements Function<Thing, Thing> {
    private final Function<Trie<Field>, Trie<Field>> nextFunction;

    public GetFields(Function<Trie<Field>, Trie<Field>> nextFunction) {
      this.nextFunction = nextFunction;
    }

    @Override
    public Thing apply(Thing thing) {
      return thing.setFields(nextFunction.apply(thing.fields));
    }
  }

  public static Thing parse(ParseState text) {
    int backup = text.getPosition();
    String id = text.readName();
    if (id == null) {
      return null;
    }
    if (!text.read("{")) {
      text.setPosition(backup);
      return null;
    }
    Trie<Field> result = new Trie<>();
    while (true) {
      if (text.read("}")) {
        break;
      }
      Field field = Field.parse(text);
      if (field == null) {
        text.setPosition(backup);
        return null;
      }
      FindOrCreate<Field> procedure = new FindOrCreate<Field>(field.getId(),
                                      new Assign<Field>(field));
      result = procedure.apply(result);
    }
    return new Thing(id, result);
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("&");
    builder.append(id);
    builder.append(":\n");
    ArrayList<String> list = fields.collect();
    for (int i = 0; i < list.size(); i++) {
      Field field = fields.get(list.get(i));
      if (field instanceof ValueField) {
        builder.append(Block.indent(field.toString()));
      }
    }
    return builder.toString();
  }
}


text:
#import <Foundation/Foundation.h>
#import "ASPObject.h"

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

@protocol ASPWBSCodeMask
@end

@interface ASPWBSCodeMask : ASPObject

@property(nonatomic) NSNumber* level;

@property(nonatomic) NSString* length;

@property(nonatomic) NSString* sequence;

@property(nonatomic) NSString* separator;

@end


text:
using System;
using FarseerPhysics.Common;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Dynamics;
using GlitchGame.Devices;
using GlitchGame.Weapons;
using Microsoft.Xna.Framework;
using SFML.Graphics;
using SFML.Window;

namespace GlitchGame.Entities
{
    public abstract class Ship : Entity
    {
        private const int DamageSprites = 5;
        private const string SpriteFormat = "{0}{1}.png";

        private Sprite _forward;
        private Sprite _backward;
        private Sprite _left;
        private Sprite _right;

        public override RadarValue RadarType { get { return RadarValue.Count; } }

        public Sprite Sprite { get; protected set; }
        public float Size { get; protected set; }
        public Weapon Weapon { get; protected set; }

        public int Team { get; private set; }

        public float MaxHealth { get; protected set; }
        public float Health;
        public float MaxEnergy { get; protected set; }
        public float Energy;

        public float HealthRegenRate;
        public float EnergyRegenRate;
        public float DamageTakenMultiplier; // armor
        public float DamageMultiplier;
        public float SpeedMultiplier;
        public float NerfMultiplier;

        protected float Thruster;
        protected float AngularThruster;
        protected bool Shooting;

        protected Ship(State state, Vector2 position, float size, int team)
            : base(state)
        {
            Sprite = new Sprite(Assets.LoadTexture(string.Format(SpriteFormat, "ship", 0))).Center();

            if (team != 0)
                Sprite.Color = new Color(255, 200, 220);

            Scale = new Vector2f(size, size);

            #region Body Initialize
            InitializeBody(state.World, size);

            Body.UserData = this;
            Body.Position = position;
            Body.Rotation = (float)Program.Random.NextDouble() * Util.Pi2;
            #endregion

            Size = size;
            Team = team;

            DamageTakenMultiplier = 1;
            DamageMultiplier = 1;
            SpeedMultiplier = 1;
            NerfMultiplier = 1;

            _forward = new Sprite(Assets.LoadTexture("ship_forward.png"));
            _forward.Origin = new Vector2f(_forward.Texture.Size.X / 2f, 0) - new Vector2f(0, 65);

            _backward = new Sprite(Assets.LoadTexture("ship_backward.png"));
            _backward.Origin = new Vector2f(_backward.Texture.Size.X / 2f, _backward.Texture.Size.Y) - new Vector2f(0, -54);

            _left = new Sprite(Assets.LoadTexture("ship_left.png"));
            _left.Origin = new Vector2f(0, _left.Texture.Size.Y / 2f) - new Vector2f(15, -37);

            _right = new Sprite(Assets.LoadTexture("ship_right.png"));
            _right.Origin = new Vector2f(_right.Texture.Size.X, _right.Texture.Size.Y / 2f) - new Vector2f(-15, -37);
        }

        public virtual void InitializeBody(World world, float size)
        {
            Body = new Body(State.World);
            Body.BodyType = BodyType.Dynamic;
            Body.LinearDamping = 0.5f;
            Body.AngularDamping = 1.0f;

            // tip
            var rect1 = new PolygonShape(PolygonTools.CreateRectangle(0.23f * size, 0.55f * size, new Vector2(0, -0.45f) * size, 0), 1);

            // tail
            var rect2 = new PolygonShape(PolygonTools.CreateRectangle(0.725f * size, 0.45f * size, new Vector2(0, 0.55f) * size, 0), 3);

            Body.CreateFixture(rect1);
            Body.CreateFixture(rect2);
        }

        public override void Update(float dt)
        {
            /*if (Health <= 0)
            {
                Dead = true;
                return;
            }*/

            var a = Math.Abs(1 - NerfMultiplier);
            var s = Math.Sign(1 - NerfMultiplier);
            NerfMultiplier += Util.Clamp(a, -0.05f, 0.05f) * s * dt;
            NerfMultiplier = Util.Clamp(NerfMultiplier, 0.5f, 1.5f);

            Health = Util.Clamp(Health + HealthRegenRate * NerfMultiplier * dt, 0, MaxHealth);
            Energy = Util.Clamp(Energy + EnergyRegenRate * NerfMultiplier * dt, 0, MaxEnergy);

            if (Weapon != null && Shooting)
                Weapon.TryShoot();

            // TODO: see if we can make large ships turn slower
            var linearSpeed = 7.5f * Body.Mass * SpeedMultiplier * NerfMultiplier;
            var angularSpeed = 2.5f * Body.Inertia * SpeedMultiplier * NerfMultiplier;
            Body.ApplyForce(Body.GetWorldVector(new Vector2(0.0f, Util.Clamp(Thruster, -1.0f, 0.5f) * linearSpeed)));
            Body.ApplyTorque(AngularThruster * angularSpeed);
        }

        public override void Draw(RenderTarget target)
        {
            var damage = Health / MaxHealth;
            var damageIdx = (DamageSprites - 1) - (int)Util.Clamp(damage * DamageSprites, 0, DamageSprites - 1);
            Sprite.Texture = Assets.LoadTexture(string.Format(SpriteFormat, "ship", damageIdx));

            Position = Body.Position.ToSfml() * Program.PixelsPerMeter;
            Rotation = Body.Rotation * Program.DegreesPerRadian;

            var states = new RenderStates(Transform);
            target.Draw(Sprite, states);

            if (Thruster < 0)
            {
                target.Draw(_forward, states);
            }
            else if (Thruster > 0)
            {
                target.Draw(_backward, states);
            }

            if (AngularThruster < 0)
            {
                target.Draw(_left, states);
            }
            else if (AngularThruster > 0)
            {
                target.Draw(_right, states);
            }
        }
    }
}


text:
package org.apache.flink.runtime.concurrent.akka;

import org.apache.flink.runtime.concurrent.ScheduledExecutor;
import org.apache.flink.util.Preconditions;

import akka.actor.ActorSystem;
import akka.actor.Cancellable;

import javax.annotation.Nonnull;

import java.util.concurrent.Callable;
import java.util.concurrent.Delayed;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import scala.concurrent.duration.FiniteDuration;

/** Adapter to use a {@link ActorSystem} as a {@link ScheduledExecutor}. */
public final class ActorSystemScheduledExecutorAdapter implements ScheduledExecutor {

    private final ActorSystem actorSystem;

    public ActorSystemScheduledExecutorAdapter(ActorSystem actorSystem) {
        this.actorSystem = Preconditions.checkNotNull(actorSystem, "rpcService");
    }

    @Override
    @Nonnull
    public ScheduledFuture<?> schedule(
            @Nonnull Runnable command, long delay, @Nonnull TimeUnit unit) {
        ScheduledFutureTask<Void> scheduledFutureTask =
                new ScheduledFutureTask<>(command, unit.toNanos(delay), 0L);

        Cancellable cancellable = internalSchedule(scheduledFutureTask, delay, unit);

        scheduledFutureTask.setCancellable(cancellable);

        return scheduledFutureTask;
    }

    @Override
    @Nonnull
    public <V> ScheduledFuture<V> schedule(
            @Nonnull Callable<V> callable, long delay, @Nonnull TimeUnit unit) {
        ScheduledFutureTask<V> scheduledFutureTask =
                new ScheduledFutureTask<>(callable, unit.toNanos(delay), 0L);

        Cancellable cancellable = internalSchedule(scheduledFutureTask, delay, unit);

        scheduledFutureTask.setCancellable(cancellable);

        return scheduledFutureTask;
    }

    @Override
    @Nonnull
    public ScheduledFuture<?> scheduleAtFixedRate(
            @Nonnull Runnable command, long initialDelay, long period, @Nonnull TimeUnit unit) {
        ScheduledFutureTask<Void> scheduledFutureTask =
                new ScheduledFutureTask<>(
                        command, triggerTime(unit.toNanos(initialDelay)), unit.toNanos(period));

        Cancellable cancellable =
                actorSystem
                        .scheduler()
                        .schedule(
                                new FiniteDuration(initialDelay, unit),
                                new FiniteDuration(period, unit),
                                scheduledFutureTask,
                                actorSystem.dispatcher());

        scheduledFutureTask.setCancellable(cancellable);

        return scheduledFutureTask;
    }

    @Override
    @Nonnull
    public ScheduledFuture<?> scheduleWithFixedDelay(
            @Nonnull Runnable command, long initialDelay, long delay, @Nonnull TimeUnit unit) {
        ScheduledFutureTask<Void> scheduledFutureTask =
                new ScheduledFutureTask<>(
                        command, triggerTime(unit.toNanos(initialDelay)), unit.toNanos(-delay));

        Cancellable cancellable = internalSchedule(scheduledFutureTask, initialDelay, unit);

        scheduledFutureTask.setCancellable(cancellable);

        return scheduledFutureTask;
    }

    @Override
    public void execute(@Nonnull Runnable command) {
        actorSystem.dispatcher().execute(command);
    }

    private Cancellable internalSchedule(Runnable runnable, long delay, TimeUnit unit) {
        return actorSystem
                .scheduler()
                .scheduleOnce(new FiniteDuration(delay, unit), runnable, actorSystem.dispatcher());
    }

    private long now() {
        return System.nanoTime();
    }

    private long triggerTime(long delay) {
        return now() + delay;
    }

    private final class ScheduledFutureTask<V> extends FutureTask<V>
            implements RunnableScheduledFuture<V> {

        private long time;

        private final long period;

        private volatile Cancellable cancellable;

        ScheduledFutureTask(Callable<V> callable, long time, long period) {
            super(callable);
            this.time = time;
            this.period = period;
        }

        ScheduledFutureTask(Runnable runnable, long time, long period) {
            super(runnable, null);
            this.time = time;
            this.period = period;
        }

        public void setCancellable(Cancellable newCancellable) {
            this.cancellable = newCancellable;
        }

        @Override
        public void run() {
            if (!isPeriodic()) {
                super.run();
            } else if (runAndReset()) {
                if (period > 0L) {
                    time += period;
                } else {
                    cancellable = internalSchedule(this, -period, TimeUnit.NANOSECONDS);

                    // check whether we have been cancelled concurrently
                    if (isCancelled()) {
                        cancellable.cancel();
                    } else {
                        time = triggerTime(-period);
                    }
                }
            }
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            boolean result = super.cancel(mayInterruptIfRunning);

            return result && cancellable.cancel();
        }

        @Override
        public long getDelay(@Nonnull TimeUnit unit) {
            return unit.convert(time - now(), TimeUnit.NANOSECONDS);
        }

        @Override
        public int compareTo(@Nonnull Delayed o) {
            if (o == this) {
                return 0;
            }

            long diff = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
            return (diff < 0L) ? -1 : (diff > 0L) ? 1 : 0;
        }

        @Override
        public boolean isPeriodic() {
            return period != 0L;
        }
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE680_Integer_Overflow_to_Buffer_Overflow__new_listen_socket_65b.cpp
Label Definition File: CWE680_Integer_Overflow_to_Buffer_Overflow__new.label.xml
Template File: sources-sink-65b.tmpl.cpp
*/
/*
 * @description
 * CWE: 680 Integer Overflow to Buffer Overflow
 * BadSource: listen_socket Read data using a listen socket (server side)
 * GoodSource: Small number greater than zero that will not cause an integer overflow in the sink
 * Sinks:
 *    BadSink : Attempt to allocate array using length value from source
 * Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer
 *
 * */

#include "std_testcase.h"

#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif

#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)

namespace CWE680_Integer_Overflow_to_Buffer_Overflow__new_listen_socket_65
{

#ifndef OMITBAD

void badSink(int data)
{
    {
        size_t dataBytes,i;
        int *intPointer;
        /* POTENTIAL FLAW: dataBytes may overflow to a small value */
        dataBytes = data * sizeof(int); /* sizeof array in bytes */
        intPointer = (int*)new char[dataBytes];
        for (i = 0; i < (size_t)data; i++)
        {
            intPointer[i] = 0; /* may write beyond limit of intPointer if integer overflow occured above */
        }
        printIntLine(intPointer[0]);
        delete [] intPointer;
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(int data)
{
    {
        size_t dataBytes,i;
        int *intPointer;
        /* POTENTIAL FLAW: dataBytes may overflow to a small value */
        dataBytes = data * sizeof(int); /* sizeof array in bytes */
        intPointer = (int*)new char[dataBytes];
        for (i = 0; i < (size_t)data; i++)
        {
            intPointer[i] = 0; /* may write beyond limit of intPointer if integer overflow occured above */
        }
        printIntLine(intPointer[0]);
        delete [] intPointer;
    }
}

#endif /* OMITGOOD */

} /* close namespace */


text:
redirect_to: https://anvio.org/help/main/programs/anvi-inspect
---