text:
Q: Two problems with jquery script: z-index and setTimeout have a side menu on the left side of the website. I want the submenu to slide open to the right with a neat animation. I have made the script:
jQuery(document).ready(function($){
    $(".main-navigation ul li").mouseenter(function() {
        if ($(this).children().length > 0) {
            $(this).children("ul").css ({
            "display" : "block",
            }).animate({
                left: '250px',
                opacity: 1,
                }, 500)
            }})
            .mouseleave(function() {
                setTimeout(function() {
                    $(this).children("ul").css({
                    "display" : "none",
                    "left" : "0px",
                    "opacity": 0,
                    })
                }, 1000);
            });
});

Sliding works just fine. The menu shows up nicely.
There's two problems though. One is, that the menu z-index doesn't work. The submenu's ul has a negative index set in css but when it slides it goes OVER the main ul. I want it to go UNDER the menu so it doesn't show.
Second one is, the SetTimeout function doesn't seem to work. Once the mouse leaves the area the ul just stays there forever. Without the Settimeout function it disappears just nicely (instantly though, I want it to stay there awhile).
I have made a jsfiddle example
http://jsfiddle.net/r8vx07ae/4/

A: It is because $(this) is losing its scope on setTimeout function. To overcome this issue, you can assign your $(this) scope into a variable like $this and then use it in your setTimeout function. Here is the code changes:
.mouseleave(function() {
        var $this=$(this);
        setTimeout(function() {
            $this.children("ul").css({
                "display" : "none",
                "left" : "0px",
                "opacity": 0,
            })
        }, 1000);
});

And here is your updated fiddle:
http://jsfiddle.net/r8vx07ae/5/

A: Problem with z-index:
An element can not appear behind its parent. Since the submenu exists as a child element of the menu, it will not be able to appear behind the menu, z-index is really only applicable to two elements which share the same parent.
Problem with setTimeout:
The issue is most likely being caused because the this variable is out of scope by the time that the timeout occurs. This has an easy fix: create a global variable (say subMenu) and set subMenu = this before the timeout occurs and replace this with subMenu in your timeout function. You may use additional variables or a dictionary/array if you have multiple submenus to prevent the variable from being overwritten if two submenus get opened one right after the other

A: The problem with the setTimeout is the scope of this
When it runs, it is the window, not the menu.
jQuery(document).ready(function($){
    $(".main-navigation ul li").mouseenter(function() {
        /* see if the timer has run yet, if it has not, cancel it */
        var hideTimer = $(this).data("timer");
        if (hideTimer) window.clearTimeout(hideTimer);

        if ($(this).children().length > 0) {
            $(this).children("ul").css ({
            "display" : "block",
            }).stop().animate({
                left: '250px',
                opacity: 1,
                }, 500)
            }})
            .mouseleave(function() {
                /* store the children here to get rid of the "this" scope issue */
                var ul = $(this).children("ul");
                /* Store a reference to the timer so we can cancel it if they mouseover again */
                $(this).data("timer", setTimeout(function() {
                    ul.css({
                    "display" : "none",
                    "left" : "0px",
                    "opacity": 0,
                    })
                }, 1000));
            });
});

This will not fix the z-index issue.

A: I guess this is from the usage of "this" inside the callback of setTimeout sadly i do not have any computer to test out...
 See section "the this problem": https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout#The_%27this%27_problem
To solve it, save a reference of this before the call of setTimeout, and use the saved reference inside your callback


text:
Q: Gradle - Default build type always debug I have an Android App with build types "release" and "debug"
When I build it with

./gradlew build

It always uses the debug build type.
Why that and how can I choose to build release?

A: If you are using Android Studio you can change the default executed build type int the left bottom tab called Build Variants. There you can see your app and build types. When you change it for your app and press the execution button, it executes the new default task provided. However, I don't really know how to change the default one using the command line, but you can execute the one you want with the next template:
gradle taskFlavorBuildType

for example, to build a debug build type it is:
gradle assembleDebug

You can find more info here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regex Pattern Match Digit preceding a alphabet only I am trying to setup a regex but having an issue with the same.
The Text:
1)
1.2.3.4 - USER [01/Mar/2015:10:05:16 +0200] SSLv1.0 ABCDE-FGH-IJK128-LMN111 POST /abc/def/ghi/jklmn/opqrs/t1 HTTP/1.1 200 99 12345 http://somehost.somedomain.com:1234 balancer://abc_def_ghi_http_port_1234
2)
1.2.3.4 - USER [01/Mar/2015:10:05:16 +0200] SSLv1.0 ABCDE-FGH-IJK128-LMN111 POST /abc/def/ghi/jklmn/opqrs/12531631913/wqeqeqer HTTP/1.1 200 99 12345 http://somehost.somedomain.com:1234 balancer://abc_def_ghi_http_port_1234

The Regex:
(?:\/[^]\s\/(){},~:;=@#%&_\-]*)+

URL: https://regex101.com/r/qc9BOX/1/
Currently, the match for the above cases are:
1)
/Mar/2015
/abc/def/ghi/jklmn/opqrs/t1
/1.1
//somehost.somedomain.com
//abc

2)
/Mar/2015
/abc/def/ghi/jklmn/opqrs/12531631913/wqeqeqer
/1.1
//somehost.somedomain.com
//abc

The data is am getting is almost accurate, but in the 1st and 2nd matches of the regex i.e. /Mar/2015 and /abc/def/ghi/jklmn/opqrs/12531631913/wqeqeqer
I dont not want the digits to be matched.
Which means, my regex should find /Mar/ only and not 2015. It should match /abc/def/ghi/jklmn/opqrs/wqeqeqer but not 12531631913.

A: try this
(\/)([a-zA-Z\/]+)(\1)


text:
Q: Clean API after Content Type modification During development, I made quite a few changes to my model. Since Strapi doesn't migrate your db this results in an API with lots of confusing and useless fields (that are not in the admin UI), like in this screenshot.
The migration/database problem is a well known issue. However, is it possible to clean the API without fixing the database (which I don't really care if the API is clean) ? Ideally the API should mirror the admin UI.

A: If you are referring to the created_by and updated_by we have an open issue to hide these by default, it's being looked into by our engineering team: https://github.com/strapi/strapi/issues/7177
Can you clarify what fields in your screenshot you are referring to?


text:
Q: Get a node list from an apply-templates It's me again.
I'm working on an NLP project  and my task is oriented about syntactic dependencies between words in sentences. But here is my xml :
<trame>
<codage>utf-8</codage>
<delimiteur><![CDATA[. ,:;!?/_-"'()[]{}§0*><=+#]]></delimiteur>
<items>
<item type="forme" pos="1"><f>euh</f><c>I</c><l>euh</l>B-----ROOTROOT----OBOOBOOOOOOOUO00-92.9019676125922791.26525310558021UU_mmmm79.99999999999996259.01900000000006$L1-BB_hlhlUU_Hmfilled-pause_Hmfilled-pauseHmUU_HmU_filled-pause_Hmfilled-pauseHmUU_filled-pauseU_filled-pause_Hmfilled-pauseHm0.4602990.540299(IU:B)_(PER:B)_(PAQ:U)_(GR:U)(ASNUC:U)_(PER:B)(PRN:O)_(PER:B)(PON:O)_(PAQ:U)_(PER:B)_(GR:U)</item>
<item type="delim" pos="2"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="3"><f>bon</f><c>I</c><l>bon</l>B-----ROOTROOT----OIOOIOOOOOOOUO00-93.6114279213457191.82168183237229UU_mmm2mmm2280.0139.99999999999997$L1-I-hlBB_mhlone_mhlonemhBB_mhB_strong_mhstrongmhBB_weakB_weak_mhweakmh0.5402990.820299(IU:I)_(PER:I)_(PAQ:B)_(GR:B)(ASNUC:U)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:B)_(PER:I)_(GR:B)</item>
<item type="delim" pos="4"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="5"><f>pour</f><c>Pre</c><l>pour</l>B-----AD(33)AD(33)----OIOOIOOOOOOOOO00-93.5580384132087393.98225339281224UU_hhhh238.0380000000001172.99049999999997$L1-I-hlI--lonemhI--strongmhL--weakmh0.8202991.099946(IU:I)_(PER:I)_(PAQ:I)_(GR:I)(ASNUC:O)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:I)_(PER:I)_(GR:I)</item>
<item type="delim" pos="6"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="7"><f>aller</f><c>V</c><l>aller</l>Binfinitive----DEP(5)DEP(5)----OIOOIOOOOOOOOOSW-93.8159871000441595.55844144923779UU_hhhh229.99999999999997185.00000000000003$L1-I-hlL--lonemhL--strongmhUU_strongU_strong_hhstronghh1.0999461.390299(IU:I)_(PER:I)_(PAQ:L)_(GR:L)(ASNUC:O)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:L)_(PER:I)_(GR:L)</item>
<item type="delim" pos="8"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="9"><f>du</f><c>Pre+D</c><l>de+le</l>B---sgmascOBJ(7)OBJ(7)----OIOOIOOOOOOOOO00-93.9147289372461893.43828093467815UU_hmhm310.00000000000006132.99049999999997$L1-I-hlBB_hmmotherless_hmmotherlesshmBB_hmB_weak_hmweakhmUU_weakU_weak_hmweakhm1.3902991.700299(IU:I)_(PER:I)_(PAQ:B)_(GR:B)(ASNUC:O)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:B)_(PER:I)_(GR:B)</item>
<item type="delim" pos="10"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="11"><f>CRDT</f><c>N</c><l>CRDT</l>B---sgmascDEP(9)DEP(9)----OIOOIOOOOOOOOOW0-89.8839666857609192.21161134439662UU_hmhm482.86399999999975230.9190000000001$L1-I-hlL--motherlesshmL--weakhmUU_weakU_weak_mmweakmm1.7002992.513163(IU:I)_(PER:I)_(PAQ:L)_(GR:L)(ASNUC:O)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:L)_(PER:I)_(GR:L)</item>
<item type="delim" pos="12"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="13"><f>à</f><c>Pre</c><l>à</l>B-----OBL(7)OBL(7)----OIOOIOOOOOOOOO00H90.2636630988775488.57247375870008UU_mlml340.0000000000003343.1742499999999$L1-I-hlBB_mHl2tail_mHl2tailmHl2BB_mHl2B_tail_mHl2tailmHl2BB_strongB_strong_mHl2strongmHl22.5831632.923163(IU:I)_(PER:I)_(PAQ:B)_(GR:B)(ASNUC:O)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:B)_(PER:I)_(GR:B)</item>
<item type="delim" pos="14"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="15"><f>la</f><c>D</c><l>le</l>B---sgfemDEP(17)DEP(17)----OIOOIOOOOOOOOO00H92.0766611323949286.20573686283727UU_llll273.67600000000004396.37325$L1-I-hlI--tailmHl2I--tailmHl2L--strongmHl22.9231633.196839(IU:I)_(PER:I)_(PAQ:I)_(GR:I)(ASNUC:O)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:I)_(PER:I)_(GR:I)</item>
<item type="delim" pos="16"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="17"><f>gare</f><c>N</c><l>gare</l>B---sgfemDEP(13)DEP(13)----OIOOIOOOOOOOOO0S-88.1712225783339897.38585113265228UU_HHHH346.4720000000003344.91649999999987$L10.237114I-hlL--tailmHl2L--tailmHl2UU_tailU_tail_HHtailHH3.1968393.959468(IU:I)_(PER:I)_(PAQ:L)_(GR:L)(ASNUC:O)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:L)_(PER:I)_(GR:L)</item>
<item type="delim" pos="18"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="19"><f>euh</f><c>I</c><l>euh</l>B-----ROOTROOT----OIOOIOOOOOOOUO0_H86.4444417173464887.63023960575637UU_mlml309.9999999999996171.13449999999997$L1-I-hlUU_mlfilled-pause_mlfilled-pausemlUU_mlU_filled-pause_mlfilled-pausemlUU_filled-pauseU_filled-pause_mlfilled-pauseml4.1965824.506582(IU:I)_(PER:I)_(PAQ:U)_(GR:U)(ASNUC:U)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:U)_(PER:I)_(GR:U)</item>
<item type="delim" pos="20"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="21"><f>de</f><c>Pre</c><l>de</l>B-----DEP(17)DEP(17)----OIOOIOOOOOOOOO00-88.8041464740217986.72856086599734UU_llll150.00000000000034257.940333333333$L1-I-hlBB_lhH2lone-dis-strong_lhH2lone-dis-stronglhH2BB_lhH2B_dis-strong_lhH2dis-stronglhH2UU_strongU_strong_lHstronglH4.5065824.656582(IU:I)_(PER:I)_(PAQ:B)_(GR:B)(ASNUC:O)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:B)_(PER:I)_(GR:B)</item>
<item type="delim" pos="22"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="23"><f>Grenoble</f><c>N</c><l>Grenoble</l>B---sgmasc-femDEP(21)DEP(21)----OIOOLOOOOOOOOO00-90.5393729958911197.37944865527233UU_HhHh307.07300000000083515.0497499999998$L1-I-hlI--lone-dis-stronglhH2I--dis-stronglhH2BB_dis-strongB_dis-strong_Hhdis-strongHh4.6565825.427476(IU:I)_(PER:I)_(PAQ:I)_(GR:I)(ASNUC:O)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:I)_(PER:I)_(GR:I)</item>
<item type="delim" pos="24"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="25"><f>je</f><c>Cl</c><l>je</l>B--1sg-PARA_DISFL(31)--PARA_DISFL(31)SUB_INHERITED(33)-UIBOOOOOOOOOOOSSH92.9925711877650593.45817303640241UU_hhhh524.4369999999998474.6527500000002$L1-I-hlL--lone-dis-stronglhH2L--dis-stronglhH2L--dis-strongHh5.4274765.951913(IU:I)_(PER:I)_(PAQ:L)_(GR:L)(ASNUC:O)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:L)_(PER:I)_(GR:L)</item>
<item type="delim" pos="26"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="27"><f>euh</f><c>I</c><l>euh</l>B-----ROOTROOT----BIIOOOOOOOOOUO00H94.494916099350889.91711913085308UU_hlhl1071.9409999999998312.52675000000016$L1-I-hlBB_hml2lone_hml2lonehml2BB_hml2B_strong_hml2stronghml2BB_strongB_strong_hml2stronghml25.9519137.023854(IU:I)_(PER:I)_(PAQ:B)_(GR:B)(ASNUC:U)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:B)_(PER:I)_(GR:B)</item>
<item type="delim" pos="28"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="29"><f>ben</f><c>I</c><l>ben</l>B-----ROOTROOT----IIIOOOOOOOOOUO00-93.792016526919792.05183971732146UU_mmmm248.0450000000003484.5832499999998$L1-I-hlI--lonehml2I--stronghml2I--stronghml27.0238547.271899(IU:I)_(PER:I)_(PAQ:I)_(GR:I)(ASNUC:U)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:I)_(PER:I)_(GR:I)</item>
<item type="delim" pos="30"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="31"><f>je</f><c>Cl</c><l>je</l>B--1sg-SUB(33)SUB(33)----LIIOOOOOOOOOOO00-92.8929328943933395.09020298840696UU_mhH2mhH2170.55199999999982402.84725$L1-I-hlI--lonehml2I--stronghml2I--stronghml27.2718997.442451(IU:I)_(PER:I)_(PAQ:I)_(GR:I)(ASNUC:O)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:I)_(PER:I)_(GR:I)</item>
<item type="delim" pos="32"><f> </f><c>BLANK</c><l>BLANK</l>--------------------------------------------------------------</item>
<item type="forme" pos="33"><f>sors</f><c>V</c><l>sortir</l>Bindicativepresent1sg-ROOTROOT----OIIOOOOOOOOOOOSS-92.8210634894043596.70257095201634UU_HmHm171.40299999999974172.14925000000014$L1-I-hlL--lonehml2L--stronghml2L--stronghml27.4424517.613854(IU:I)_(PER:I)_(PAQ:L)_(GR:L)(ASNUC:O)_(PER:I)(PRN:O)_(PER:I)(PON:O)_(PAQ:L)_(PER:I)_(GR:L)</item>

I need to extract two elements. They are both nodes item. As you can see on the xml, there is in a[8] for each item his parts of speech and a number which match with the governor of this word (attribute @pos from item). So i need to get all items with a[8] = SUB and extract the number to find the governors of each one SUB. Thus, i'll have the dependent word and his governor.
Example: in the sample, 'je' (item/@pos=31) have a a[8] = SUB(33) so himself, the dependent has as governor the item/@=33 so 'sors'. So i need the grab these two item nodes and for all the file.
But the problem is not here. My template that matches with items node needs to return values of these two item nodes and furthermore it's gonna be a list. Here is my code. It's pretty simple :
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"
    xmlns:saxon="http://saxon.sf.net/" extension-element-prefixes="saxon"
    xmlns:str="http://exslt.org/strings" exclude-result-prefixes="saxon str">
    <xsl:output method="text" encoding="utf-8"/>
    <xsl:variable name="count" saxon:assignable="yes" select="0"/>

    <xsl:template match="/">

        <xsl:variable name="items" as="document-node()">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
        </xsl:variable>
        <xsl:value-of select="$items"/>

    </xsl:template>

    <xsl:template match="items">

        <xsl:for-each select="//item[@type='forme'][contains(a[7], 'SUB')]">
        <xsl:variable name="gouv_pos" select='replace(a[8], "SUB\((\d+)\)", "$1")'/>
        <xsl:variable name="gouv" select="//item[@pos=number($gouv_pos)]"/>
            <xsl:variable name="dep" select="current()"/>
            <xsl:choose>
                <xsl:when test="number($gouv_pos) > $dep/@pos">
                    <xsl:value-of select="$dep"/>
                    <xsl:value-of select="$gouv"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="$gouv"/>
                    <xsl:value-of select="$dep"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each>

    </xsl:template>

    <xsl:template match="item">

    </xsl:template>

</xsl:stylesheet>

I want to have in my variable items in template matching root, the list of nodes item grouped by two (the governor and the dependent). And this variable must be iterable. I don't know if it's possible but when i try to get the values with xsl:copy, it doesn't work.My war $items stays empty.
<xsl:variable name="items" as="document-node()">
<xsl:copy>
    <xsl:apply-templates/>
</xsl:copy>
</xsl:variable>
<xsl:value-of select="$items"/>

My <xsl:value-of select="$items"/> is empty whereas i want a list of nodes item. How to do that ? And how to connect these two item nodes (dependent and governor) ?
With this problem managed, it's gonna be easier for me to do the task.
Thx for your help.


text:
Q: strange output during git merge I am in a clone named /private/gmills, and I ran git merge main_int.
I am seeing a reference to another clone for some other user on a different machine. What does this mean?
I have only 1 remote configured and it isn't pointing to this other clone or machine.
Warning message :
warning: Failed to merge submodule projects/kernel (multiple merges found)
 1b64e534e162316a124f98edef6584d7ead1c563: > Merge branch 'main_int' into main_int_infra_xlp
 fe1ffcf1f49d8741e03710837fc6e1179b1cf222: > merge from main_int workspace:/private/sriniv/projects/kernel on build02

Information on remote repositories :
git remote -v
origin  git@server:flt/root.git (fetch)
origin  git@server:flt/root.git (push)

A: It looks like the git branches you're merging have submodule issues. Look at the .gitmodules and .git/config files within your repositories to find out which submodule is being referenced.


text:
Q: Same form , Same barcode(128), Zxing reads only one Barcode( from 2 documents) I am writing a simple program that extracts barcode from images.
I tried zxing. It worked well. Until I found a something strange.
The organization that i work at, publish forms . Same form (that I got from 2 places in the
org) with the same barcode,  I scanned them in the same machine (same resulotion also) to
pdf format.
zxing is doing the job realy well with first image, And returning the barcode. No luck with
the second image.. I got com.google.zxing.NotFoundException when trying to extract barcode
from second image. The problem occurred with more forms of the organization).
This is the image that Zxing not recognize.
http://s000.tinyupload.com/?file_id=12080994969485224486
This is the one that he does recognize.
http://s000.tinyupload.com/?file_id=30365671784453283753
This is my code :
private String handlePdf(File pdfFile) throws Exception {

    StringBuilder sb = new StringBuilder();

    PDDocument pdDoc = PDDocument.load(pdfFile);

    int size = pdDoc.getDocumentCatalog().getAllPages().size();

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

        PDPage page = (PDPage) pdDoc.getDocumentCatalog().getAllPages().get(i);

        PDResources resources = page.getResources();

        Map images = resources.getImages();

           if (images != null) {

            Iterator<String> imageIter = images.keySet().iterator();

                   while (imageIter.hasNext()) {

                  String key = (String) imageIter.next();

                  PDXObjectImage image = (PDXObjectImage) images.get(key);

                  String barcode = null ;

                  barcode = extraceBarcodeFromImage(image.getRGBImage());

                if(barcode!= null){

                   sb.append(barcode);

                   sb.append(",");

                }

               }

         }

    }

     return sb.capacity() > 0 ? sb.toString().substring(0, sb.length()-1) :
                                  "no barcode was found";

}

private String extraceBarcodeFromImage(BufferedImage image)

            throws NotFoundException {

    String finalResult;

    if (image == null)

        throw new IllegalArgumentException("Could not decode image.");

    Map<DecodeHintType, Object> HINTS;

    HINTS = new EnumMap(DecodeHintType.class);

    HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);

    HINTS.put(DecodeHintType.POSSIBLE_FORMATS,

            EnumSet.allOf(BarcodeFormat.class));

    Map<DecodeHintType, Object> HINTS_PURE;

    HINTS_PURE = new EnumMap<DecodeHintType, Object>(HINTS);

    HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);

    LuminanceSource source = new BufferedImageLuminanceSource(image);

    BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(

            source));

    MultiFormatReader barcodeReader = new MultiFormatReader();

    Result result;

    result = barcodeReader.decode(bitmap, HINTS_PURE);

    finalResult = String.valueOf(result.getText());

    return finalResult;

}

Thank you for any help you can provide in this situation.

A: The issue simply is the fairly low image quality.
Look at the working bar code at some magnification:

The quality is not good but it is good enough.
Now compare it to the not working bar code:

It is somewhat rotated and (maybe due to the rotation) the bars are very fringed. Too fringed for zxing to recognize the bar code.
I went through that with a debugger, and even making it look at every single row of the image (without manipulation it looks only at 256 evenly spaced rows), it didn't find any row it could read successfully as a bar code.
Thus, you either have to improve the quality of the scans (higher resolution, making sure the document is not rotated, ...) or have to look for a bar code reader library which does not merely look at image columns or rows individually but instead tries to recognize larger structures. I'm not deep enough into these things to be able to recommend any.


text:
Q: convert spark-submit command (dotnet for spark app) to spark-submit command for python app If the following (working) spark-submit command (for a dotnet for Spark app) was executing a python script, would it still use the same --conf settings?  Given a python script name of myapp.py that has no defined function (other than main), what would the --class reference be for a python script?
/opt/spark/bin/spark-submit --class org.apache.spark.deploy.dotnet.DotnetRunner \
   --conf "spark.eventLog.enabled=true" \
   --conf "spark.eventLog.dir=file:/usr/bin/spark/hadoop/logs" \
   --master spark://spark:7077 \
   /opt/spark/jars/microsoft-spark-3-1_2.12-2.0.0.jar \
   dotnet myapp.dll "somefilename.txt"

A: For Python applications, simply pass a .py file, no need to mention the class name
/opt/spark/bin/spark-submit \
--conf "spark.eventLog.enabled=true" \
--conf "spark.eventLog.dir=file:/usr/bin/spark/hadoop/logs" \
--master spark://spark:7077 \
/your python file path/myapp.py

For further info, you can refer https://spark.apache.org/docs/latest/submitting-applications.html


text:
Q: Custom IAuthenticationFilter in ASP.NET Core 6 Web API based on Active Directory I need to implement custom authorization based on some information in on-premise Active Directory. After doing some research, I figured that best approach would be to write a custom Authentication Filter and add that information from AD to the list of claims.
So after users are authenticated by IIS using Windows Authentication, I plan to read some information and put that among the list of claims:
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
  var claims = new List<Claim>();
  claims.Add(new Claim(ClaimTypes.Name, userPrincipal.Name));
  claims.Add(new Claim(ClaimTypes.Role, "client"));
  claims.Add(new Claim("Accounts", "[List of accounts from AD]"));

  var identity = new ClaimsIdentity(claims);

  var principal = new ClaimsPrincipal(new[] { identity });
  context.Principal = principal;

  Thread.CurrentPrincipal = context.Principal;
}

I believe that this approach will allow me to access the list of accounts from any controller. However, I am unable to add my IAuthenticationFilter implementation to the list of global filters using the following approach.
builder.Services.AddControllers(config =>
{
    config.Filters.Add(new ApiAuthenticationFilter())
});

This method required IFilterMetaData interface, while I have implemented IAuthenticationFilter. In previous Web API versions, we were able to access HttpConfiguration in Application_Start() method, but in ASP.NET Core 6 Web API, I am unable to find a way to add my filter to HttpConfiguration.
Could you please tell me if that's the right approach, or I should try implementing the IActionFilter interface? Or a different approach altogether.
Thanks!

A: I figured IAuthenticationFilter is not the right approach anymore to add Claims to  the ClaimsPrincipal. There's another interface IClaimsTransformation that does exactly what I wanted.
The example posted on ASP.NET website was creating a new ClaimsIdentity instance to the ClaimsPrincipal while I was able to achieve that by just adding to existing list of claims:
public class MyClaimsTransformation : IClaimsTransformation
{
    private readonly IActiveDirectoryService _activeDirectoryService;

    public MyClaimsTransformation(IActiveDirectoryService activeDirectoryService)
    {
        _activeDirectoryService = activeDirectoryService;
    }

    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        var identity = principal.Identities.FirstOrDefault(c => c.IsAuthenticated);

        if (identity == null)
        {
            return principal;
        }

        var user = _activeDirectoryService.GetUser(principal.Identity as WindowsIdentity);

        // Add or replace identity.Claims

        if (!principal.HasClaim(c => c.Type == MyClaimTypes.ACCOUNTS))
        {
            identity.AddClaim(new Claim(MyClaimTypes.ACCOUNTS, user.Accounts));

        }

        return principal;
    }
}

Another advantage of using IClaimsTransformation is to be able to inject dependencies through .Net core DI container.
In my Program.cs, I was unable to make it work using the recommended Authentication method:
builder.Services.AddAuthentication(IISDefaults.AuthenticationScheme);
However, using Negotiate worked for me:
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
Finally, add our custom IClaimsTranformation implementation to services:
// Claim transformation
builder.Services.AddScoped<IClaimsTransformation, MyClaimsTransformation>();

In the past, it had to be done inside ConfigureServices() method
More details about IClaimsTransformation are available here:
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/claims?view=aspnetcore-6.0


text:
Q: Url click counter, only registering one unique click counter from one browser I want to make my post url to update the total click by registering it one unique click per browser everytime it is(the url) clicked, in simpler words, i want my total clicks to be unique.
I have found the method for url clicking here
http://jsfiddle.net/donejs/qYdwR/
//html

//javascript

var Component = can.Component.extend({
    tag: 'click-counter',
    template: '' +
            'Click Me' +
            '
Clicked {{count}} times
',
    scope: {
        count: 0,
        updateCount: function() {
            this.attr('count', this.attr('count') + 1);
        }
    }
});

$('#content').html(can.view('main-template', {}));

The example of what i wish to do can be seen here pingje.org (article post).
Help me gurus, point me where to start, ive been trying to achieve this for days now, any time you took to answer my question is highly appreciated.


text:
Q: cannot get data in php sdk facebook 5.6 I try get data for php graphe sdk facebook 5.6 but I don't get for exaple user_likes
this is code php:
$fb = new Facebook([
  'app_id' => 'app id',
  'app_secret' => 'secret id',
  'default_graph_version' => 'v2.11'
]);

if ($request->isMethod('POST')) {
    $token = $request->request->get('token');
    $response= $fb->get('me?fields=id,name,email,last_name,first_name,gender,locale,users_likes,birthday',$token);
    $userNode = $response->getGraphNode();
}

but response is name,gender,email,lastname,firstname,locale btu birthday and user_likes I d'ont anything

A: $response= $fb->get('me?fields=id,...,likes,birthday',$token);

You used users_likes - that is not even a valid permission (because that would be user_likes).


text:
Q: display buffer in C I'm trying to display a buffer but it's being displayed with special characters.  Here's my code:
size_t write(int fd, const void *buf, size_t count)
{

    static size_t (*write_func)(int, const void *, size_t) = NULL;
    if (!write_func)
        write_func = (size_t(*)(int, const void *, size_t)) dlsym(RTLD_NEXT, "write");

    char tmp[count];

    memcpy(tmp,buf,count);
    printf("  %c \n",tmp[1]);

Do you have any ideas on how to fix this?  Thank you so much!

A: You allocate a copy of the read-only data on stack. That is dangerous, since stack space may be limited. (In Linux, only the original stack will grow dynamically; thread stacks are of fixed size, and often very small.)
Then you use the stdio.h printf() function to output the second byte of the specified data (even though count may be 1) to standard output, so you're likely to access outside of the temporary array anyway.
Most printf() implementations call write() internally to flush the buffer. Depending on the linkage, this may end up being recursive (your function calling printf which calls your function which calls printf and so on), using up all RAM available to the process, then crashing.
None of the above makes sense.
First, if you need to duplicate the input data, do it dynamically using malloc() and memcpy(), then free() it afterwards. That way you don't suddenly start causing crashes in multithreaded programs (where stack space is limited and fixed for all but the original process in Linux).
Second, you need to use the original write_func you obtained using the linker.
Third, you need to retain errno to avoid unforeseen problems in client programs. Just use a temporary local int to store it. Remember that not only write(), but also malloc() and free() may modify errno, and you must hide those changes from the caller.
Fourth, the return type of write() is ssize_t, not size_t. The former is signed, the latter may be unsigned.
Fifth, short writes are always allowed. You cannot ever rely on getting a "full" chunk; applications do internal processing, and especially when working with sockets, flush it at odd sizes (multiples of MTU for TCP/IP and UDP/IP in particular). Your "modifications" to the input/output would have to be stateless. Worse, if your modifications change the buffer length, and the descriptor is nonblocking, and the write_func() call returns a short write just in the middle of the modified part that does not map sensibly to any original byte, how are you going to handle it? You cannot retry, really, since the descriptor is nonblocking; the original application might hang -- for example if used in a coprocess manner, simultaneously sending and receiving data from a peer process with strict ordering requirements -- because your additions would reissue a write when one is not allowed at the application logic level.
Simply put, your scheme is not going to work. You might get it to work with some specific simple applications, but it can break others horribly. Whatever you're trying to achieve, there is a better way.
I hope I am not being too blunt, but I seriously suggest you first learn the ins and outs of low-level POSIX I/O, before you create wrappers around them. The Linux man-pages project is a good reference I can recommend, but I think you might need to start with some tutorials first.


text:
Q: Recording a track, not a polygon in QField I researched the QField documentation, google, etc. but could not help myself.
My goal is to record a GPS track using QField.  However, the tracking function only seems to work in polygon layers. The recorded "track" resulting from this is a weird polygon shape of the track, not just the track itself.
In the bee farming demo it is also only possible to get the track as a polygon (tracking only possible in layer "fields").
I am assuming that this is just a user-error from my side, but I cannot figure out the problem.


text:
Q: R terra overlap vectors and return land areas I am following the example for terra::intersect
library(terra)
f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
e <- ext(5.6, 6, 49.55, 49.7)
x <- intersect(v, e)
p <- vect(c("POLYGON ((5.8 49.8, 6 49.9, 6.15 49.8, 6 49.6, 5.8 49.8))",
            "POLYGON ((6.3 49.9, 6.2 49.7, 6.3 49.6, 6.5 49.8, 6.3 49.9))"), crs=crs(v))
values(p) <- data.frame(pid=1:2, area=expanse(p))
y <- intersect(v, p)

and what I ultimately want it so summarise the land area of all the polygons created by joining p and v. What I mean is, for each polygon in p, how many ha of polygon is in Diekirch, Grevenmacher, and Luxembourg.
I try this:
lapply(y, FUN=expanse, unit="ha")
expanse(v)

yy <- union(v,p)
lapply(yy, FUN=expanse, unit="ha")

but in both cases, expanse returns the same values as
expanse(v)

A: Here's an approach with sf and tidyverse:
library(terra)
library(tidyverse)
library(sf)

f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
e <- ext(5.6, 6, 49.55, 49.7)
x <- intersect(v, e)
p <- vect(c("POLYGON ((5.8 49.8, 6 49.9, 6.15 49.8, 6 49.6, 5.8 49.8))",
            "POLYGON ((6.3 49.9, 6.2 49.7, 6.3 49.6, 6.5 49.8, 6.3 49.9))"), crs=crs(v))
values(p) <- data.frame(pid=1:2, area=expanse(p))
y <- terra::intersect(v, p)

# sanity check: view data, cropping polygons, and cropped layer
plot(v)
plot(p, add = TRUE, col = "red")
plot(y, add = TRUE, col = "blue")

# convert to sf (data frame), mutate an area, and sum area per name group
st_as_sf(y) %>%
  mutate(area = st_area(geometry)) %>%
  group_by(NAME_1) %>%
  summarise(area_sum = sum(area)) %>%
  ungroup()

This returns the summed area per name group:
Simple feature collection with 3 features and 2 fields
Geometry type: GEOMETRY
Dimension:     XY
Bounding box:  xmin: 5.8 ymin: 49.6 xmax: 6.5 ymax: 49.9
Geodetic CRS:  WGS 84
# A tibble: 3 × 3
  NAME_1         area_sum                             geometry
  <chr>             [m^2]                       <GEOMETRY [°]>
1 Diekirch     233635561. MULTIPOLYGON (((6.285424 49.87085, …
2 Grevenmacher 285068244. POLYGON ((6.42977 49.72977, 6.5 49.…
3 Luxembourg   225869770. MULTIPOLYGON (((6.217318 49.68268, …

A: You can do
e <- expanse(y, unit="km")
aggregate(cbind(area=e), y[,c("pid", "NAME_1"), drop=TRUE], sum)

#  pid       NAME_1       area
#1   1     Diekirch 226.271445
#2   2     Diekirch   8.147181
#3   2 Grevenmacher 286.019968
#4   1   Luxembourg 194.340843
#5   2   Luxembourg  32.281530

Or like this (I would prefer the approach above because it avoids the need to aggregate polygons)
z <- aggregate(y, c("pid", "NAME_1"))
cbind(z[, c("pid", "NAME_1"), drop=TRUE],
                 area=expanse(z, unit="km"))

#  pid       NAME_1       area
#1   1     Diekirch 226.271445
#2   1   Luxembourg 194.340843
#3   2     Diekirch   8.147181
#4   2 Grevenmacher 286.019968
#5   2   Luxembourg  32.281530


text:
Q: django check user groups in forms I have a form defined from a model class.
Depending from the user group of the logged in user, some fields should be read-only.
I tried with the 'request.user.groups.values_list'. But this is not working, error message: 'global name 'request' is not defined'
class gwagen1Form(forms.ModelForm):
class Meta:
    model = gwagen1
    fields = ('gwnummer', 'wk_auftrag', 'model', 'vorbesitzer', 'typ', 'verwendung',
              'kennzeichen', 'hsn_tsn', 'km_stand', 'repartur_kosten')

    localized_fields = '__all__'

# Default value for salesman
def __init__(self, *args, **kwargs):
    super(gwagen1Form, self).__init__(*args, **kwargs)
    self.fields["verk_num"].initial = benutzer.objects.get(flag_default=True)

    gr = request.user.groups.values_list('name', flat=True)
    if gr:
        self.fields['km_stand'].widget.attrs['readonly'] = True

A: Are you using class based views?
If so, in the corresponding view add:
def get_form_kwargs(self):
    kwargs = super(GwagenView, self).get_form_kwargs()  # change to view name

    return dict(kwargs, groups=self.request.user.groups.values_list('name', flat=True))

then change the init of the form to:
def __init__(self, groups, *args, **kwargs):
    super(gwagen1Form, self).__init__(*args, **kwargs)
    self.fields["verk_num"].initial = benutzer.objects.get(flag_default=True)

    if groups:
        self.fields['km_stand'].widget.attrs['readonly'] = True

A: If you're using Class Based Views (CBVs) then passing an extra argument in the form constructor (e.g. in get_forms_class) or in form_class will not work, as <form> object is not callable will be shown.
The solution for CBVs is to use get_form_kwargs to pass the user object to MyForm:
views.py:
form_class = MyForm

# Sending user object to the form, to verify which fields to display/remove (depending on group)
def get_form_kwargs(self):
    kwargs = super(MyView, self).get_form_kwargs()
    kwargs.update({'user': self.request.user})
    return kwargs

forms.py:
class MyForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')  # To get request.user. Do not use kwargs.pop('user', None) due to potential security hole

        super(MyForm, self).__init__(*args, **kwargs)

        # If the user does not belong to a certain group, remove the field
        if not self.user.groups.filter(name__iexact='mygroup').exists():
            del self.fields['confidential']

A: No I did not use class based Views:
I found the solution, also valid for function based views.
The user group could be retrieved in the view.py and assigned to the form:
gr = request.user.groups.values_list('name', flat=False)
...
form = gwagen1Form(gr, request.POST)

if form.is_valid():
    (do something)
else:
    form = gwagen1Form(gr)

In the form.py the init method will retrieve the user groups:
def __init__(self, *args, **kwargs):
    super(gwagen1Form, self).__init__(*args, **kwargs)
    self.fields["verk_num"].initial = benutzer.objects.get(flag_default=True)

    # Rolle einlesen
    gr = Group()
    if gr:
        self.fields['km_stand'].widget.attrs['readonly'] = True


text:
Q: problem with moderncv and \bf inside bibliography I've this problem using moderncv. I'm using multibib and the first bibliography entry is:
@article{Aad:2011tw,
  author         = "Aad, Georges and others",
  title          = "{Measurement of the inclusive isolated prompt photon cross-section in pp collisions at sqrt(s)= 7 TeV using 35 pb-1 of ATLAS data}",
  collaboration  = "ATLAS Collaboration",
  journal        = "Phys.Lett.",
  volume         = "B706",
  pages          = "150-167",
  doi            = "10.1016/j.physletb.2011.11.010",
  year           = "2011",
  eprint         = "1108.0253",
  archivePrefix  = "arXiv",
  primaryClass   = "hep-ex",
  reportNumber   = "CERN-PH-EP-2011-115",
  SLACcitation   = "%%CITATION = ARXIV:1108.0253;%%",
}

and it is translated by bibtex to:
\bibitem{Aad:2011tw}
{ATLAS Collaboration} Collaboration, G.~Aad et al., {\em {Measurement of the
  inclusive isolated prompt photon cross-section in pp collisions at sqrt(s)= 7
  TeV using 35 pb-1 of ATLAS data}\/},
  \href{http://dx.doi.org/10.1016/j.physletb.2011.11.010}{Phys.Lett. {\bf B706}
  (2011)  150--167},
\href{http://arxiv.org/abs/1108.0253}{{\tt arXiv:1108.0253 [hep-ex]}}.
%%CITATION = ARXIV:1108.0253;%%.

When I run pdflatex I get:
[4]) (./pub.bbl
! Undefined control sequence.
<argument> \Hy@safe@activesfalse Phys.Lett. {\bf
                                                 B706} (2011) 150--167
l.8   (2011)  150--167}
                       ,

what's the problem? I used the same .bib file without moderncv and I haven't such problems.
My preample looks like this:
\documentclass[11pt,a4paper,sans]{moderncv}

\moderncvstyle{classic}
\moderncvcolor{blue}

\renewcommand*\bibliographyitemlabel{\arabic{enumiv}.}

\usepackage[left=2cm,right=2cm,top=1.8cm,bottom=2.2cm]{geometry}
\setlength{\hintscolumnwidth}{2.5cm}

\usepackage[utf8x]{inputenc}
\usepackage{color}
\usepackage{multibib}
\usepackage{url}
\usepackage{amsmath}

\newcites{conf}{Conferences and talks}
\newcites{pub}{Publications}
\newcites{confnote}{Selected conference and public notes}
\newcites{intnote}{Selected internal notes}
\newcites{poster}{Posters}
\newcites{proceedings}{Proceedings}

A: \bf is apparently not defined in some modern implementations of LaTeX. I reproduced this issue with XeLaTeX and the following MWE:
\documentclass{minimal}
\begin{document}
Test \bf test
\end{document}

I was using XeLaTeX 0.9998 and MiKTeX 2.9. moderncv was last updated in 2007, so this is likely just the march of time leaving behind an unmaintained package.

A: Support for the old commands \bf, \rm, etc. is generally provided by the document class. For example, lines 579-587 of report.cls contain the following
\DeclareOldFontCommand{\rm}{\normalfont\rmfamily}{\mathrm}
\DeclareOldFontCommand{\sf}{\normalfont\sffamily}{\mathsf}
\DeclareOldFontCommand{\tt}{\normalfont\ttfamily}{\mathtt}
\DeclareOldFontCommand{\bf}{\normalfont\bfseries}{\mathbf}
\DeclareOldFontCommand{\it}{\normalfont\itshape}{\mathit}
\DeclareOldFontCommand{\sl}{\normalfont\slshape}{\@nomath\sl}
\DeclareOldFontCommand{\sc}{\normalfont\scshape}{\@nomath\sc}
\DeclareRobustCommand*\cal{\@fontswitch\relax\mathcal}
\DeclareRobustCommand*\mit{\@fontswitch\relax\mathnormal}

This is missing from moderncv.cls. Try adding the above to the preamble of your document. In this particular case you could just add the lines concerning \bf, \em and \tt, but it's probably worth adding them all, just to be sure the problem won't occur again.


text:
Q: jquery anchor popup I am trying to take a list of anchors and show the text the anchor references to in a popup.  like a pop-up glossary of sorts. I have tried a couple of different techniques but i couldnt get any to work as i am very new to this.  this technique worked in firefox, but not in internet explorer.  any help on this would be appreciated, or if i should be using a different method to this please let me know.
i have my anchor ids as say, id="first" and then the text it references as id="2first"
$("a").click(function(){
    var toGet = $(this).attr('id');
    var holder =$("#2" + toGet);
    var toShow = $(holder).html();
    loadPopup(toShow);
    return false;
});

A: I'd guess that IE doesn't like id attributes that begin with a number. From the HTML4 specification:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

HTML5 has this to say about the id attribute:

The id attribute specifies its element's unique identifier (ID). The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

So HTML5 allows you to use pretty much anything but HTML4 certainly doesn't allow an id of "2first" and that may explain IE's behavior. You may find this question of interest as well.
Try moving the "2" to the end:
$("a").click(function(){
    var toGet  = this.id;
    var holder = $("#" + toGet + '2');
    var toShow = holder.html();
    loadPopup(toShow);
    return false;
});

Demo: http://jsfiddle.net/ambiguous/ZcT9f/3/

A: I know that this is old, and hopefully you've found an answer by now, but maybe this will help someone else. If you want to avoid an anchor link being followed when you click on it in jQuery and you want to perform some other action instead you can do the following:
$("a").click(function(e){
    e.preventDefault();
    var toGet  = this.id;
    var holder = $("#" + toGet + '2');
    var toShow = holder.html();
    loadPopup(toShow);
    return false;
});

By adding the event, e, to the function you can now access the event and call e.preventDefault() which will prevent the link from being followed, instead it will execute the code that follows it.


text:
Q: Can't SSH from 22.04 LTS I'm running 22.04 LTS off an external ssd drive connected to my pc via USB.
I am completely unable to SSH from there to anything, and I have no idea why or what is (not) happening.
I can easily connect from Windows, as well as from my Ubuntu Server 22.04 LTS that runs on a regular Lenovo machine.
I followed the instructions at https://www.linuxcapable.com/install-enable-connect-to-ssh-on-ubuntu-22-04-lts/ and to sum them up, they are:
$ sudo apt install openssh-server -y (Install and enable OpenSSH Server)
$ sudo systemctl enable --now ssh

$ sudo systemctl status ssh:

> ● ssh.service - OpenBSD Secure Shell server
>      Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: e>
>      Active: active (running) since Tue 2022-06-28 23:36:54 CEST; 11h ago
>        Docs: man:sshd(8)
>              man:sshd_config(5)    Main PID: 1004 (sshd)
>       Tasks: 1 (limit: 18726)
>      Memory: 3.1M
>         CPU: 29ms
>      CGroup: /system.slice/ssh.service
>              └─1004 "sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups"
>
> jun 28 23:36:54 Hakuna systemd[1]: Starting OpenBSD Secure Shell
> server... jun 28 23:36:54 Hakuna sshd[1004]: Server listening on
> 0.0.0.0 port 22. jun 28 23:36:54 Hakuna sshd[1004]: Server listening on :: port 22. jun 28 23:36:54 Hakuna systemd[1]: Started OpenBSD
> Secure Shell server.

$ sudo ufw allow 22/tcp (allow port 22)

> sudo ufw status Status: active
>
> Til                        Handling    Fra
> ---                        --------    ---
> 22/tcp                     ALLOW       Anywhere
> 22/tcp (v6)                ALLOW       Anywhere (v6)

From here on, I should be able to ssh to my Pihole:
> ssh pi@10.0.0.5 ssh: connect to host 10.0.0.5 port 22: Connection timed out

Any help is appreciated,
Thanks!
EDIT:
From Ubuntu Desktop to target
 $ ip addr show
    1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
        link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
        inet 127.0.0.1/8 scope host lo
           valid_lft forever preferred_lft forever
    2: enp0s31f6: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc fq_codel state DOWN group default qlen 1000
        link/ether f8:75:a4:12:a0:88 brd ff:ff:ff:ff:ff:ff
    3: wlp5s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
        link/ether 28:7f:cf:2b:9e:2c brd ff:ff:ff:ff:ff:ff
        inet 10.0.0.215/24 brd 10.0.0.255 scope global dynamic noprefixroute wlp5s0
           valid_lft 46015sec preferred_lft 46015sec
    5: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default qlen 1000
        link/ether 52:54:00:c5:ce:7d brd ff:ff:ff:ff:ff:ff
        inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
           valid_lft forever preferred_lft forever
    6: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UNKNOWN group default qlen 500
        link/none
        inet 10.8.1.4/24 scope global tun0
           valid_lft forever preferred_lft forever
    11: wlx00c0cab15fb4: <NO-CARRIER,BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state DORMANT group default qlen 1000
        link/ether 00:c0:ca:b1:5f:b4 brd ff:ff:ff:ff:ff:ff

    $ netstat -r -n
    Kernel IP routing table
    Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
    0.0.0.0         10.0.0.1        0.0.0.0         UG        0 0          0 wlp5s0
    10.0.0.0        0.0.0.0         255.255.255.0   U         0 0          0 wlp5s0
    10.8.1.0        0.0.0.0         255.255.255.0   U         0 0          0 tun0
    169.254.0.0     0.0.0.0         255.255.0.0     U         0 0          0 virbr0
    192.168.122.0   0.0.0.0         255.255.255.0   U         0 0          0 virbr0

$ ping 10.0.0.5
PING 10.0.0.5 (10.0.0.5) 56(84) bytes of data.
^C
--- 10.0.0.5 ping statistics ---
188 packets transmitted, 0 received, 100% packet loss, time 191470ms

From Ubuntu Server 22.04 to target:
$ ping 10.0.0.5
PING 10.0.0.5 (10.0.0.5) 56(84) bytes of data.
64 bytes from 10.0.0.5: icmp_seq=1 ttl=64 time=33.9 ms
64 bytes from 10.0.0.5: icmp_seq=2 ttl=64 time=1.66 ms
64 bytes from 10.0.0.5: icmp_seq=3 ttl=64 time=1.94 ms
64 bytes from 10.0.0.5: icmp_seq=4 ttl=64 time=1.74 ms
64 bytes from 10.0.0.5: icmp_seq=5 ttl=64 time=13.8 ms
64 bytes from 10.0.0.5: icmp_seq=6 ttl=64 time=1.45 ms
64 bytes from 10.0.0.5: icmp_seq=7 ttl=64 time=1.68 ms
64 bytes from 10.0.0.5: icmp_seq=8 ttl=64 time=4.43 ms
64 bytes from 10.0.0.5: icmp_seq=9 ttl=64 time=1.53 ms
64 bytes from 10.0.0.5: icmp_seq=10 ttl=64 time=4.20 ms
64 bytes from 10.0.0.5: icmp_seq=11 ttl=64 time=5.94 ms
64 bytes from 10.0.0.5: icmp_seq=12 ttl=64 time=2.71 ms
^C
--- 10.0.0.5 ping statistics ---
12 packets transmitted, 12 received, 0% packet loss,

From Pihole, which connects to the routher via ethernet:
ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether dc:a6:32:33:8c:bd brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.5/24 brd 10.0.0.255 scope global noprefixroute eth0
       valid_lft forever preferred_lft forever

$ netstat -r -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         10.0.0.1        0.0.0.0         UG        0 0          0 eth0
10.0.0.0        0.0.0.0         255.255.255.0   U         0 0          0 eth0

$ ping 10.0.0.10 (Pinging my 22.04 server)
PING 10.0.0.10 (10.0.0.10) 56(84) bytes of data.
64 bytes from 10.0.0.10: icmp_seq=1 ttl=64 time=1.63 ms
64 bytes from 10.0.0.10: icmp_seq=2 ttl=64 time=1.77 ms
64 bytes from 10.0.0.10: icmp_seq=3 ttl=64 time=1.72 ms
64 bytes from 10.0.0.10: icmp_seq=4 ttl=64 time=5.97 ms
64 bytes from 10.0.0.10: icmp_seq=5 ttl=64 time=0.870 ms
64 bytes from 10.0.0.10: icmp_seq=6 ttl=64 time=6.84 ms
^C
--- 10.0.0.10 ping statistics ---
6 packets transmitted, 6 received, 0% packet loss, time 13ms
rtt min/avg/max/mdev = 0.870/3.134/6.844/2.346 ms

I have connected from my server to my pihole. It went as planned.

A: Disabling the NordVPN did the trick. Can't believe it was that simple!
To make Ubuntu work alongside NordVPN, I made these changes to my settings:
> $ nordvpn whitelist add subnet 10.0.0.0/24

I also added my pihole DNS server, while I was at it:
> $ nordvpn set dns 10.0.0.5

Source:
https://support.nordvpn.com/da/Forbindelse/Linux/1807056062/Installation-af-NordVPN-pao-Debian-Ubuntu-Raspberry-Pi-Elementary-OS-og-Linux-Mint.htm
Now, allow me a moment while I scream into a pillow, before I figure out how to credit @user68186 with providing the correct answers.
And again, thank you all for helping me out. It means a lot.


text:
Q: SQL Help regarding time greater than 7 days I was wondering if someone can help with my query. I finally got it to display all the information I need but is there any way to make it output only data for OPN 9661 that is greater than 7 days.
And OPN 9601 and 9640 to display data greater than 2 days.
Thank you in advance!
SELECT lma.lot, lma.device, dd.device_desc, lma.lpt,lma.opn,
CASE WHEN l.hold = 'Y' THEN 'Y'
     WHEN l.hold = 'F' THEN 'F' ELSE 'N' END AS hold,lma.arrival_dttm,
Round((SYSDATE - lma.arrival_dttm)*24,2) AS duration, lma.in_qty,
ls.lot_code3 AS location, la.operator
FROM lot_move_age  lma, lot_str ls, lot l, lot_cur_opn lco, device_def dd, lot_act la
WHERE lma.facility = 'DP1DM5' and ls.facility = 'DP1DM5'
and l.facility = 'DP1DM5' AND dd.facility = 'DP1DM5'
and lco.facility = 'DP1DM5' and la.facility = 'DP1DM5'
AND lma.grp_type = '704'
AND lma.latest = 'O'
AND ls.latest = 'Y'
AND lma.lot = ls.lot
AND lma.lot = l.lot
AND lma.lot = lco.lot
AND lma.lot = la.lot
AND lma.opn = lco.opn
AND lma.lpt = lco.lpt
AND la.tran_dttm IS NULL
AND lma.departure_dttm IS NULL
AND lma.lpt = l.lpt
AND lma.opn != '0000'
AND (lma.opn LIKE '9601' or lma.opn LIKE '9640' or lma.opn LIKE '9661')
AND lma.device = ls.device
AND lma.device = dd.device

ORDER BY arrival_dttm

Here is a screenshot of the table:

A: you have duration column in your query Round((SYSDATE - lma.arrival_dttm)*24,2) AS duration
so... just add one more line into where section:
and Round((SYSDATE - lma.arrival_dttm)*24,2) >= 7

or if you need specific logic for OPN 9661 and 9640
that can be:
and (
(lma.opn = 9661 and Round((SYSDATE - lma.arrival_dttm)*24,2) >= 7)
or
(lma.opn = 9640 and Round((SYSDATE - lma.arrival_dttm)*24,2) >= 2)
)

A: You can use additional condition using case statement in WHERE clause to find the conditional date difference as following:
And sysdate - lma.arrival_dttm >=
    Case when lma.opn = 9661
         Then 7
    Else 2
    End

Please note that the difference between dates gives number of days between those two dates.
Cheers!!


text:
Q: Addition of 16-bit Floating point Numbers and How to convert it back to decimal I want to Convert the following two numbers into IEEE Floating Point Standard (FPS) modified (16 bits) by changing the 23 bit fractional part to a 7 bit fractional part, and add them up. But I don't know whether I have done it correctly and how to convert the result back to decimal to get approximately 28.625
Numbers in parenthesis are hidden bits (Cause we convert number e.g 3.5 into 11.1*2^0 then  1.11 *2^1 so we omit that leftmost '1' and we call it hidden bit)

A: Numbers are not added by adding their significands while their exponents are different. That is like trying to add 25.25 to 3.375 by adding 2525 to 3375. It does not work. You must align the corresponding bits by shifting them and adjusting the exponents accordingly. If you had these two numbers:

*

*1.10010102•24

*1.10110002•21
Then you would adjust change the smaller number, giving this pair:

*

*1.10010102•24 (same as original)

*0.00110112•24 (shifted three bits right and added three to exponent)

Then you add them:

*

*1.11001012•24
Then you can round that number if necessary and convert it to another format.


text:
Q: Is there any way to lint a Python file to check for Numpy documentation style adherence? I'm working on a project that requires Numpy documentation. In my Java days, I remember having linters that checked for Javadoc adherence in Eclipse/IDEA; is there an equivalent that checks for Numpy documentation style adherence?
I know about PEP257, but it doesn't seem to have any specific checks for Numpy documentation.

A: Pylint seems to support that. Take a look at pylint.extensions.docparams.
To sum it up. You activate this checker of pylint by adding
load-plugins=pylint.extensions.docparams

in the Master section of your .pylintrc.

This checker verifies that all function, method, and constructor
  docstrings include documentation of the

*

*parameters and their types

*return value and its type

*exceptions raised

Actually pydocstyle (formerly pep257) recently added support for the numpy docstring convention. Although, it's not perfect I think it's the closest to what you want to achieve and it will probably improve in the near future.
pydocstyle --convention=numpy example.py


text:
Q: How to add context sensitive help text for custom functions in eclipse I am programming for using eclipse as an IDE to program in a different language. I have implemented custom content-assist feature using eclipse using the org.eclipse.jface.text.contentassist.IContentAssistProcessor package. You can see my output below with the "__XXXXX" functions being displayed as someone types anything based on the context.
How can I display function details of a custom function. I mean, the type of help that can been seen in normal functions. I want to give an useful information about these functions.

A: See ICompletionProposal.getAdditionalProposalInfo() and ICompletionProposalExtension5.getAdditionalProposalInfo(...). Eclipse contains several examples on how to implement these.


text:
Q: How can gnome based applications such as rhythmbox use a proxy I happen to be using xubuntu but I dont think the desktop-environment is applicable in this context.
I noticed that some gnome-based applications such as rhythmbox cannot fetch any information from the internet if the corporate network is using a proxy.
In this particular scenario - the cover-art search facility of rhythmbox cannot find coverart sought from the various providers on the internet.
I've tried the usual tricks such as setting http_proxy and running rhythmbox from the terminal, but this does not seem to work.

*

*How can a proxy be set for the whole xubuntu system?
Any ideas?

A: Some of the newer GTK3 based gnome-applications ignore/don't use environment variables when dealing with proxies.
Instead, they use values stored in gsettings / dconf
If you use dconf-editor installed as part of the dconf-tools package you can define the proxy in a GUI manner.
First - set the proxy mode to manual as shown

Second - set the proxy host & port.  If you dont have an anonymous proxy you need to set the authentication-password and authentication-user values

If your corporate network uses https then set the equivalent system - proxy - https tree values instead of system - proxy - http that is shown above.
Via the terminal you can use the following:
gsettings set org.gnome.system.proxy mode 'manual'
gsettings set org.gnome.system.proxy.http host 'proxy.askubuntu.com'
gsettings set org.gnome.system.proxy.http port 8080
gsettings set org.gnome.system.proxy.http authentication-user '[host]\[username]'
gsettings set org.gnome.system.proxy.http authentication-password 'mypassword'

Where [host]\[username] corresponds to your corporate network credentials e.g. mywindowsdomain\fossfreedom
If your corporate network uses https then substitute http with https in the above terminal commands.


text:
Q: Contact angle of liquid drop on surface How do you explain point 44 of the attached pdf document on surface tension? Here's the link.
How is the direction of surface tension found out?
(I know it tangential but in which direction along the tangent?)
Also why is surface tension for solid-air surface considered when balancing the forces on liquid? Any help will be appreciated.

A: The problem is azimuthally-symmetric, so the tangential direction is the one with no azimuthal component, i.e. the one "straight up the side" if you were a small mountain climber climbing from the surface to the top of the drop.
All three surface tensions are required because all three exert forces. For example, if the solid-air surface tension were extremely high, the system would try to minimize the area of contact between the surface and the air, which corresponds to spreading the drop out flat. If the solid-air surface tension were very low, the opposite would occur and the drop would be a sphere touching the surface in a very small area.


text:
Q: "Exception handling" in shell scripts I know that you can use the shortcutting boolean operators in shell scripts to do some sort of exception handling like so:
my_first_command && my_second_command && my_third_command

But this quickly becomes unreadable and unmaintainable as the number of commands you want to chain grows. If I'm writing a script (or a shell function), is there a good way to have execution of the script or function halt on the first nonzero return code, without writing on one big line?
(I use zsh, so if there are answers that only work in zsh that's fine by me.)

A: The -e option does this:
   ERR_EXIT (-e, ksh: -e)
          If a command has a non-zero exit status, execute the ZERR  trap,
          if set, and exit.  This is disabled while running initialization
          scripts.

You should be able to put this on the shebang line, like:
#!/usr/bin/zsh -e

Most shells have this option, and it's usually called -e.


text:
Q: Powershell extracting logs based upon interval? I have script logic as follows:-

*

*check if the folder is empty

*If yes Use the same command with exception time period of last 30 days. i.e StartDate etc

*If folder not empty get / extract the logs for 1 day using same command
just tweaking timesettings.

*the script will be scheduled to run every 5 minutes. For every run extract using the same command for 1 day saves the result in temp.csv and compare it most updated copy of final-admin.csv.

*If changes found; write difference / over-write in
final-admin.csv

code
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
$outcsv='c:\Mail-audit-results\Final-mail-admin.csv'
if(Get-ChildItem C:\Mail-audit-results){

    $enddate=[datetime]::Today
    $Startdate=$enddate.AddDays(-1)
    $splat=@{
         Identity='mail.test-nw.com'
         LogonTypes=@('Admin','Delegate')
         ShowDetails=$true
         StartDate=$Startdate
         EndDate=$enddate
    }

        Search-MailboxAuditLog @splat | Export-Csv c:\Mail-audit-results\temp_results.csv -NoTypeInformation -Append
        $Old = Import-CSV $outcsv
        $New = Import-CSV c:\Mail-audit-results\temp_results.csv
        $New | ?{$Old -notmatch $_} | Export-CSV $outcsv -notype
    }

    #process items when files found
}else{
    # process when no files found.
    $enddate=[datetime]::Today
    $Startdate=$enddate.AddDays(-30)
    $splat=@{
         Identity='mail.test-nw.com'
         LogonTypes=@('Admin','Delegate')
         ShowDetails=$true
         StartDate=$Startdate
         EndDate=$enddate
    }
    Search-MailboxAuditLog @splat | Export-Csv $outcsv -NoTypeInformation -Append

}

    Get-ChildItem 'c:\Mail-audit-results\Final-mail-admin.csv' | ForEach {

    Else
    {
    return 0;

    }

}

Problem-points
How can I change the format of date in mm/dd/yyy format in section
$enddate=[datetime]::Today
$Startdate=$enddate.AddDays(-1)

How to overwrite with difference data?
$New | ?{$Old -notmatch $_} | Export-CSV $outcsv -notype

I don't want to write to third file the difference I want original file $outcsv to get written; would the above command overwrite/ or just append?
Thanks.

A: You can change your dates using -Uformat switch
$enddate= Get-Date ([datetime]::Today) -UFormat "%m%d%Y"
$Startdate= Get-Date ($enddate.AddDays(-1))  -UFormat "%m%d%Y"

The line
$New | ?{$Old -notmatch $_} | Export-CSV $outcsv -notype
will overwrite data, Export-CSV -Append  will append.


text:
Q: ssh launch of jenkins slave stalls jenkins start I'm not sure how to go about debugging this issue. Jenkins on restarts takes forever and from the logs I can see that its sitting trying to launch the slave
06/25/15 14:03:34] SSH Launch of Slave1 on dom-jenkins-sl1.cloud.dev.phx3.gdg failed in 179,907 ms

Jun 25, 2015 2:05:06 PM hudson.slaves.SlaveComputer tryReconnect
INFO: Attempting to reconnect Slave1
Jun 25, 2015 2:05:07 PM org.jenkinsci.main.modules.sshd.SSHD start
INFO: Started SSHD at port 33090
Jun 25, 2015 2:05:07 PM jenkins.InitReactorRunner$1 onAttained
INFO: Completed initialization
Jun 25, 2015 2:05:07 PM org.jenkinsci.plugins.skipcert.ItemListenerImpl onLoaded
INFO: Bypassing certificate check
Jun 25, 2015 2:05:08 PM hudson.WebAppMain$3 run
INFO: Jenkins is fully up and running
[06/25/15 14:05:08] SSH Launch of Slave1 on dom-jenkins-sl1.cloud.dev.phx3.gdg completed in 1,923 ms

And yet on the second try 2 minutes later it works just fine.  Any ideas?


text:
Q: Thread safe File System Watcher for Unity Editor I need a thread safe class for File System Watcher to use in Unity Editor, I already know that Threading is not possible out of coroutines, but I didn't know that threading wasn't allowed also in Editor.
So, there is my error:

get_isEditor can only be called from the main thread. Constructors and
  field initializers will be executed from the loading thread when
  loading a scene. Don't use this function in the constructor or field
  initializers, instead move initialization code to the Awake or Start
  function. 0x0000000140E431ED (Unity) StackWalker::GetCurrentCallstack
  0x0000000140E44EE1 (Unity) StackWalker::ShowCallstack
  0x00000001405FC603 (Unity) GetStacktrace 0x00000001405F97FE (Unity)
  DebugStringToFile 0x00000001405F9C5C (Unity) DebugStringToFile
  0x000000014035F7B3 (Unity) ThreadAndSerializationSafeCheckReportError
  0x0000000140E7B988 (Unity) Application_Get_Custom_PropIsEditor
  0x0000000015AC46AA (Mono JIT Code) (wrapper managed-to-native)
  UnityEngine.Application:get_isEditor () 0x0000000015AC42FE (Mono JIT
  Code) [Helpers.cs:585] Lerp2API.DebugHandler.Debug:Log (object)
  0x0000000015AC41C2 (Mono JIT Code) [Helpers.cs:578]
  Lerp2API.DebugHandler.Debug:Log (string)  0x0000000015AC40F7 (Mono JIT
  Code) [LerpedEditorCore.cs:101]
  Lerp2APIEditor.LerpedEditorCore:Recompile
  (object,System.IO.FileSystemEventArgs)  0x0000000015AC3F2D (Mono JIT
  Code) (wrapper runtime-invoke)
  :runtime_invoke_void__this___object_object
  (object,intptr,intptr,intptr) 0x00007FFB400A519B (mono) [mini.c:4937]
  mono_jit_runtime_invoke  0x00007FFB3FFF84FD (mono) [object.c:2623]
  mono_runtime_invoke  0x00007FFB3FFFE8F7 (mono) [object.c:3827]
  mono_runtime_invoke_array  0x00007FFB3FFFEBCC (mono) [object.c:5457]
  mono_message_invoke  0x00007FFB4001EB8B (mono) [threadpool.c:1019]
  mono_async_invoke  0x00007FFB4001F5E2 (mono) [threadpool.c:1455]
  async_invoke_thread  0x00007FFB4002329F (mono) [threads.c:685]
  start_wrapper  0x00007FFB400D78C9 (mono) [win32_threads.c:599]
  thread_start  0x00007FFB77FC8364 (KERNEL32) BaseThreadInitThunk

I copied full stack trace to make aware any helper where can be the problem. Because, I searched for a solution, like any threaded safe FWS, and yes, there is one, but only for .NET 4, and I need one for .NET 2
This is my code:
using System.IO; //class, namespace, redundant info...

private static FileSystemWatcher m_Watcher;

[InitializeOnLoadMethod]
static void HookWatcher()
{
    m_Watcher = new FileSystemWatcher("path", "*.cs");
    m_Watcher.NotifyFilter = NotifyFilters.LastWrite;
    m_Watcher.IncludeSubdirectories = true;
    //m_Watcher.Created += new FileSystemEventHandler(); //Add to the solution before compile
    //m_Watcher.Renamed += new FileSystemEventHandler(); //Rename to the solution before compile
    //m_Watcher.Deleted += new FileSystemEventHandler(); //Remove to the solution before compile
    m_Watcher.Changed += Recompile;
    m_Watcher.EnableRaisingEvents = true;
}

private static void Recompile(object sender, FileSystemEventArgs e)
{
    Debug.Log("Origin files has been changed!");
}

There nothing special as you can see...
The FSW I saw was this: https://gist.githubusercontent.com/bradsjm/2c839912294d0e2c008a/raw/c4a5c3d920ab46fdaa53b0e111e0d1204b1fe903/FileSystemWatcher.cs
My purpose with this is simple, I have a separated DLL from my current Unity project, the idea is simple, I want to recompile everything automatically from Unity when any change from the project of the DLL is changed, but I can't achieve that because of threads, so what can I do? Is there any alternative that listen files that is compatible with Unity?
Thanks.

A: From my experience you can use threads but you have to take care that access to Unity classes is performed from the main thread only. My suggestion is to hand over control to the main thread whenever your watchdog alerts.
static bool _triggerRecompile = false;

[InitializeOnLoadMethod]
static void HookWatcher()
{
    m_Watcher = new FileSystemWatcher("path", "*.cs");
    // ....
    m_Watcher.Changed += Recompile;
    EditorApplication.update += OnEditorApplicationUpdate;
}

private static void Recompile(object sender, FileSystemEventArgs e)
{
    bool _triggerRecompile = true;
    // Never call any Unity classes as we are not in the main thread
}

static void OnEditorApplicationUpdate ()
{
    // note that this is called very often (100/sec)
    if (_triggerRecompile)
    {
        _triggerRecompile = false;
        Debug.Log("Origin files has been changed!");
        DoRecompile();
    }
}

Polling is of course kind of nasty and ugly. In general I prefer event based approaches. But in this special case I see no chance to cheat the main thread rule.

A: I solved it with the help of @Kay, thanks @Kay!
I wanted to make a more generic answer, so I decided to make my own class to achieve what I wanted. And this is the result:
using System;
using System.IO;
using System.Collections.Generic;

namespace Lerp2APIEditor.Utility
{
    public class LerpedThread<T>
    {
        public T value = default(T);
        public bool isCalled = false;
        public string methodCalled = "";
        public Dictionary<string, Action> matchedMethods = new Dictionary<string, Action>();

        public FileSystemWatcher FSW
        {
            get
            {
                return (FileSystemWatcher)(object)value;
            }
        }
        public LerpedThread(string name, FSWParams pars)
        {
            if(typeof(T) == typeof(FileSystemWatcher))
            {
                FileSystemWatcher watcher = new FileSystemWatcher(pars.path, pars.filter);

                watcher.NotifyFilter = pars.notifiers;
                watcher.IncludeSubdirectories = pars.includeSubfolders;

                watcher.Changed += new FileSystemEventHandler(OnChanged);
                watcher.Created += new FileSystemEventHandler(OnCreated);
                watcher.Deleted += new FileSystemEventHandler(OnDeleted);
                watcher.Renamed += new RenamedEventHandler(OnRenamed);

                ApplyChanges(watcher);
            }
        }
        private void OnChanged(object source, FileSystemEventArgs e)
        {
            methodCalled = "OnChanged";
            isCalled = true;
        }
        private void OnCreated(object source, FileSystemEventArgs e)
        {
            methodCalled = "OnCreated";
            isCalled = true;
        }
        private void OnDeleted(object source, FileSystemEventArgs e)
        {
            methodCalled = "OnDeleted";
            isCalled = true;
        }
        private void OnRenamed(object source, RenamedEventArgs e)
        {
            methodCalled = "OnRenamed";
            isCalled = true;
        }
        public void StartFSW()
        {
            FSW.EnableRaisingEvents = true;
        }
        public void CancelFSW()
        {
            FSW.EnableRaisingEvents = false;
        }
        public void ApplyChanges<T1>(T1 obj)
        {
            value = (T)(object)obj;
        }
    }
    public class FSWParams
    {
        public string path,
                      filter;
        public NotifyFilters notifiers;
        public bool includeSubfolders;
        public FSWParams(string p, string f, NotifyFilters nf, bool isf)
        {
            path = p;
            filter = f;
            notifiers = nf;
            includeSubfolders = isf;
        }
    }
}

Main class code:
namespace Lerp2APIEditor
{
    public class LerpedEditorCore
    {

        private static LerpedThread<FileSystemWatcher> m_Watcher;

        [InitializeOnLoadMethod]
        static void HookWatchers()
        {
            EditorApplication.update += OnEditorApplicationUpdate;

            m_Watcher.matchedMethods.Add("OnChanged", () => {
                Debug.Log("Origin files has been changed!");
            });

            m_Watcher.StartFSW();
        }

        static void OnEditorApplicationUpdate()
        {
            if(EditorApplication.timeSinceStartup > nextSeek)
            {
                if (m_Watcher.isCalled)
                {
                    foreach (KeyValuePair<string, Action> kv in m_Watcher.matchedMethods)
                        if (m_Watcher.methodCalled == kv.Key)
                            kv.Value();
                    m_Watcher.isCalled = false;
                }
                nextSeek = EditorApplication.timeSinceStartup + threadSeek;
            }
        }
    }
}

The thing I have done is very simple. I only created a generic class that create a FSW instance or whatever you want to listen. One time created, I attach the events that only activates the bool @Kay suggested me to use, and also the method called to know exactly what method have been called.
Later in the main class, a foreach loops every method listed every second if a change has been detected, and the method linked to the string get called.


text:
Q: remove files on remote machine this is simple CLI to remove couple file on remote machine
 ssh 182.2.34.1 "rm -f /etc/yum.repos.d/repo.1 master.er top.fg  REPO.l"

but only repo.1 file was deleted
what is wrong with my syntax

A: master.er, top.fg, and REPO.1 are being removed from current directory (which is probably your home directory). You should provide full path to the directories.

A: The command rm -f /etc/yum.repos.d/repo.1 master.er top.fg REPO.l will delete exactly those files. The files other than the first are being deleted in the current directory, which is likely to be your home directory on the remote machine.
If all four files are to be deleted from /etc/yum.repos.d, you may use
ssh 182.2.34.1 "cd /etc/yum.repos.d && rm -f repo.1 master.er top.fg REPO.l"

This will first changed the current directory, and if that is successful, it will delete the files.

Also note that you ideally should not work as root but as an unprivileged user.  This may mean that your ssh command may end up looking as
ssh 182.2.34.1 "cd /etc/yum.repos.d && sudo rm -f repo.1 master.er top.fg REPO.l"

and that you execute this as a non-root user with sudo access on the remote machine (there is seldom a reason to allow SSH access by root).
The benefit of this is that you explicitly state your intention to issue an operation as root, and that the commands executed as root are logged.  The logging is important if you need to recover what operations may have hosed a system.


text:
Q: javascript Date() sum day but not month I want sum 30 days in Date() object, I've used javascript Date() and set new date with .setDate(.getDate()+30) and it seems to have updated the month when you print it with console.log() but when I try to get the values,
var myDate = new Date();

myDate.setDate( myDate.getDate() + 30 );

console.log( myDate ); // will show 1 month ahead
console.log( "Next Month (wrong): " + myDate.getMonth() ); // will thow this month! why???

var dateData = {
  'day':(myDate.getDate() < 10) ? "0" + myDate.getDate() : myDate.getDate(),
  'month':(myDate.getMonth() < 10) ? "0" + myDate.getMonth() : myDate.getMonth(),
  'year':myDate.getFullYear()
} ;

console.log( dateData.year + "-" + dateData.month + "-" + dateData.day ) ;
// it sum date but not month

ps.: today is august 28. + 30 days it should be 07
it will output in console:
Date 2017-09-27T18:07:56.101Z  Scratchpad/3:14:1
Next Month (wrong): 8  Scratchpad/3:15:1
2017-08-27 // this should print 2017-09-27 but the month still 08

what's wrong? is this a javascript fault or a programmer mess?

A: It's correct. JavaScript counts month on a 0 based index. 0 = January, 1 = February, etc. September is month 8, not 9, so your code is correct.
Try this:
console.log(new Date().getMonth()); // During August, will be 7

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth

A: The getMonth() function returns values from 0 to 11.


text:
Q: Trying to hide a HTML 'label' using CSS 'hide' Should be simple enough but it doesn't seem to work.
I am trying to hide a checkbox on a login form that says "Remember Me" on my membership site.
Here is the relevant bit of HTML:
<input name="rememberme" type="checkbox" id="rememberme" value="forever" /> Remember Me

Here is my CSS:
.rememberme {
  display: none
}

No joy.
Any idea how I hide that 'label' string of HTML?
Thanks
++++ EDIT ++++
I added the entire code to help with this question. Thanks again for all  help!
<form name="mepr_loginform" id="mepr_loginform" class="mepr-form" action="https://my-site.com/login/" method="post">

            Username

        <input type="text" name="log" id="user_login" value="" />

            Password

        <input type="password" name="pwd" id="user_pass" value="" />

            *

        <input type="text" name="meprmath_quiz" id="meprmath_quiz" value="" class="mepr-form-input" />
        <input type="hidden" name="meprmath_data" value="sdasDDDDI4YWYxYmIzYWIxODU=" />

        <input name="rememberme" type="checkbox" id="rememberme" value="forever" />Remember Me

        <input type="submit" name="wp-submit" id="wp-submit" class="button-primary mepr-share-button " value="Log In" />
        <input type="hidden" name="redirect_to" value="https://my-site.com/account/" />
        <input type="hidden" name="mepr_process_login_form" value="true" />
        <input type="hidden" name="mepr_is_login_page" value="true" />

</form>

A: The problem here is you are selecting .rememberme when the input has a name and id attribute of 'rememberme' instead of a class. Try adding the class 'rememberme' to the input tag.
<input class="rememberme" type="checkbox" value="forever" /> remember me

A: I assume that you can't edit the markup in this case.
You have to be specific on CSS selector so the style will apply only on that one. Because all direct child elements (but the one you want to hide) of this form have some classes, we can exclude them on the selector:
#mepr_loginform > div:not(.mp-form-row):not(.submit):not(.mp-spacer) {
  display: none;
}

Codepen


text:
Q: pso algorithm on test function. But I'm stuck with python code So I have to classes Swarm and Particles, and a class for Sphere function.
But when I'm trying to run the optimization, I get error on iteretation and I don't understand why:
TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'
Eventually, if you can give me some tipf for shifted sphere function.
from abc import ABCMeta, abstractmethod
import numpy
import numpy.random
from particle import Particle
class Swarm (object):
__metaclass__ = ABCMeta

def __init__ (self,
        swarmsize,
        minvalues,
        maxvalues,
        currentVelocityRatio,
        localVelocityRatio,
        globalVelocityRatio):

    self.__swarmsize = swarmsize

    assert len (minvalues) == len (maxvalues)
    assert (localVelocityRatio + globalVelocityRatio) > 4

    self.__minvalues = numpy.array (minvalues[:])
    self.__maxvalues = numpy.array (maxvalues[:])

    self.__currentVelocityRatio = currentVelocityRatio
    self.__localVelocityRatio = localVelocityRatio
    self.__globalVelocityRatio = globalVelocityRatio

    self.__globalBestFinalFunc = None
    self.__globalBestPosition = None

    self.__swarm = self.__createSwarm ()

def __getitem__ (self, index):
    """
    Возвращает частицу с заданным номером
    """
    return self.__swarm[index]

def __createSwarm (self):

    return [Particle (self) for _ in range (self.__swarmsize) ]

def nextIteration (self):

    for particle in self.__swarm:
        return particle.nextIteration (self)

@property
def minvalues (self):
    return self.__minvalues

@property
def maxvalues (self):
    return self.__maxvalues

@property
def currentVelocityRatio (self):
    return self.__currentVelocityRatio

@property
def localVelocityRatio (self):
    return self.__localVelocityRatio

@property
def globalVelocityRatio (self):
    return self.__globalVelocityRatio

@property
def globalBestPosition (self):
    return self.__globalBestPosition

@property
def globalBestFinalFunc (self):
    return self.__globalBestFinalFunc

def getFinalFunc (self, position):
    assert len (position) == len (self.minvalues)

    finalFunc = self._finalFunc (position)

    if (self.__globalBestFinalFunc == None or
            finalFunc < self.__globalBestFinalFunc):
        self.__globalBestFinalFunc = finalFunc
        self.__globalBestPosition = position[:]

@abstractmethod
def _finalFunc (self, position):
    pass

@property
def dimension (self):

    return len (self.minvalues)

def _getPenalty (self, position, ratio):

    penalty1 = sum ([ratio * abs (coord - minval)
        for coord, minval in zip (position, self.minvalues)
        if coord < minval ] )

    penalty2 = sum ([ratio * abs (coord - maxval)
        for coord, maxval in zip (position, self.maxvalues)
        if coord > maxval ] )

    return penalty1 + penalty2

class Particle (object):
def __init__ (self, swarm):

    self.__currentPosition = self.__getInitPosition (swarm)

    self.__localBestPosition = self.__currentPosition[:]

    self.__localBestFinalFunc = swarm.getFinalFunc (self.__currentPosition)

    self.__velocity = self.__getInitVelocity (swarm)

@property
def position (self):
    return self.__currentPosition

@property
def velocity (self):
    return self.__velocity

def __getInitPosition (self, swarm):
    return numpy.random.rand (swarm.dimension) * (swarm.maxvalues - swarm.minvalues) + swarm.minvalues

def __getInitVelocity (self, swarm):

    assert len (swarm.minvalues) == len (self.__currentPosition)
    assert len (swarm.maxvalues) == len (self.__currentPosition)

    minval = -(swarm.maxvalues - swarm.minvalues)
    maxval = (swarm.maxvalues - swarm.minvalues)

    return numpy.random.rand (swarm.dimension) * (maxval - minval) + minval

def nextIteration (self, swarm):

    rnd_currentBestPosition = numpy.random.rand (swarm.dimension)

    rnd_globalBestPosition = numpy.random.rand (swarm.dimension)

    veloRatio = swarm.localVelocityRatio + swarm.globalVelocityRatio
    commonRatio = (2.0 * swarm.currentVelocityRatio /
            (numpy.abs (2.0 - veloRatio - numpy.sqrt (veloRatio ** 2 - 4.0 * veloRatio) ) ) )

    newVelocity_part1 = commonRatio * self.__velocity

    newVelocity_part2 = (commonRatio *
            swarm.localVelocityRatio *
            rnd_currentBestPosition *
            (self.__localBestPosition - self.__currentPosition) )

    newVelocity_part3 = (commonRatio *
            swarm.globalVelocityRatio *
            rnd_globalBestPosition *
            (swarm.globalBestPosition - self.__currentPosition) )

    self.__velocity = newVelocity_part1 + newVelocity_part2 + newVelocity_part3

    self.__currentPosition += self.__velocity

    finalFunc = swarm.getFinalFunc (self.__currentPosition)
    if finalFunc < self.__localBestFinalFunc:
        self.__localBestPosition = self.__currentPosition[:]
        self.__localBestFinalFunc = finalFunc

class Swarm_X2 (Swarm):
def init (self,
swarmsize,
minvalues,
maxvalues,
currentVelocityRatio,
localVelocityRatio,
globalVelocityRatio):
Swarm.init (self,
swarmsize,
minvalues,
maxvalues,
currentVelocityRatio,
localVelocityRatio,
globalVelocityRatio)
def _finalFunc (self, position):
    penalty = self._getPenalty (position, 10000.0)
    finalfunc = sum (position * position)

    return finalfunc + penalty

from swarm_x2 import Swarm_X2
from utils import printResult
if name == "main":
iterCount = 300
dimension = 5
swarmsize = 200

minvalues = numpy.array ([-100] * dimension)
maxvalues = numpy.array ([100] * dimension)

currentVelocityRatio = 0.1
localVelocityRatio = 1.0
globalVelocityRatio = 5.0

swarm = Swarm_X2 (swarmsize,
        minvalues,
        maxvalues,
        currentVelocityRatio,
        localVelocityRatio,
        globalVelocityRatio
        )

for n in range (iterCount):
    print "Position", swarm[0].position
    print "Velocity", swarm[0].velocity

    print printResult (swarm, n)

    swarm.nextIteration()


text:
Q: Sum values of similar keys inside two nested dictionary in python I have nested dictionary like this:
data = {
    "2010":{
            'A':2,
            'B':3,
            'C':5,
            'D':-18,
        },
    "2011":{
            'A':1,
            'B':2,
            'C':3,
            'D':1,
        },
    "2012":{
            'A':1,
            'B':2,
            'C':4,
            'D':2
        }
    }

In my case, i need to sum all values based on its similar keys in every year, from 2010 till 2012..
So the result i expected should be like this:
data = {'A':4,'B':7, 'C':12, 'D':-15}

A: You can use collections.Counter() (works only for positive values!):
In [17]: from collections import Counter
In [18]: sum((Counter(d) for d in data.values()), Counter())
Out[18]: Counter({'C': 12, 'B': 7, 'A': 4, 'D': 3})

Note that based on python documentation Counter is designed only for use cases with positive values:

The multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison.
  The elements() method requires integer counts. It ignores zero and negative counts.

So if you want to get a comprehensive result you can do the summation manually. The collections.defaultdict() is a good way for getting around this problem:
In [28]: from collections import defaultdict

In [29]: d = defaultdict(int)

In [30]: for sub in data.values():
   ....:     for i, j in sub.items():
   ....:         d[i] += j
   ....:

In [31]: d
Out[31]: defaultdict(<class 'int'>, {'D': -15, 'A': 4, 'C': 12, 'B': 7})

A: Try this,
reduce(lambda x, y: dict((k, v + y[k]) for k, v in x.iteritems()), data.values())

Result
{'A': 4, 'B': 7, 'C': 12, 'D': -15}


text:
Q: Generate a C# delegate method stub Anyone know how to automatically create a delegate stub method?
In WPF it seems im constantly having to pass delegates around. i would like to be able to type a method name that doesnt exist and have a method stub automatically generated...currently i'am having to constantly reference the docs to get the delegate signature and then manually create method with matching signature.

A: Use an IDE plugin like Refactor Pro! It also allows you to convert your delegates to instance methods, or if its a one-liner, into a lambda. I tend to start typing using a lambda and then hovering my cursor over the parms gives you the types available.
Or. Wait till Visual Studio 10 which would have this all built in. But until then use either of the aforementioned :)


text:
Q: "Forward" as transitive verb When casually writing email I find myself using forward like this:

I forwarded him the email with your info.

Is the above version grammatically correct?

I forwarded the email with your info to him

somehow sounds more proper. Given that

I sent you a letter

is structured exactly the same way, it seems like it should work the same with forward.
Is this usage accepted? Why might it still sound odd to me, assuming it is in fact correct?

A: Sod what's proper. The sentence is written in normal, grammatical English.

A: I agree with Barrie England. Both versions sound proper to me. This is probably a new usage of the word forward that came about with email use, but since native speakers accept it in both ways, it's fine.


text:
Q: Simply Handling Session Free Node.js with Authentication and Client Side Templating I have a question - I found a few answers floating around here.
Basically, I want to have a node.js server application serving up json documents for requests.
All templating will happen client side
Some of the requests will require authentication but most will not.
I'd like to eliminate the need for framework (express) session management wherever possible (as recommended by linked-in) to improve performance so I thought of a couple solutions for authentication.
1) Write custom authentication that persists the session as a document and checks it wherever a request is made to the node.js server that needs authentication. Keep all user info in html5 storage or cookies for the dom to use for templating.
+ Works
- Have to write custom security to avoid session management in express/node.
2) Have 2 node.js instances. One serves everything in the public domain. One is for secure requests only. Still keep all user info in the session.
+ Simple as we can push session management onto the framework for requests that require authentication
- Has 2 node instances. May have some bad DRY.
Is the second option reasonable? Or is there another option I'm missing. Option 1 is my fallback as I'd rather not do all of the custom coding when it's already built into express.
EDIT:
To leave one possibility on here, I think I can use multiple callbacks on a resource request to allow an interceptor type pattern for validating user in session. This answers the first question.
From the express documentation:
Several callbacks may also be passed, useful for re-using middleware that load resources, perform validations, etc.
app.get('/user/:id', user.load, function(){
  // ...
})


text:
Q: Java custom serialization best practices I am attempting to improve our current serialization performance by switching from the Serializable interface to Externalizable, but have not found a lot of documentation on best practice for creating custom and performant serialzations.  My current solution is about twice as fast as the stock Java serialization, which while good, doesn't seem like the vast improvement I was expecting (Benchmark of serialization techniques/libraries)
For anything but primitives I've taken the approach of writing a 0 or 1 to show the field exists, then reading the field if the value is 1:
if (in.read() == 1) {
    name = in.readUTF();
}

Does that sound about right?  Are there better encodings to use?  What about Maps, Lists, and other complex data structures.  Is the default serialization for Enums fine?
Thanks.

A: Any reason not to use an existing serialization framework - but a rather better one than Java has built-in? My own preference is Protocol Buffers, but there are alternatives as well, such as Thrift. I'd try to avoid doing your own low-level serialization unless you really can't avoid it. The page you've linked to shows lots of alternatives.
You should consider both performance and maintainability. While Externalizable can give you great performance, it depends on how you implement it, in the end - and you could do a good job, or a bad job... but it'll all be manual.

A: From a maintainability point of view, I try to use generated Data Transfer Objects. This way you generate the toString, hashCode, equals, readObject, writeObject and possibly their Builder classes as well from a single definition.
In terms of speed, it depends on what your raw data types are. There are three main costs in deserialization/deserialization

*

*use of reflection, this is the main benefit of custom serialization because you can hard code the fields and types

*creating new objects. You can use recycled objects, but this can be tricky.

*number of bytes you read/write. Using more compact forms can help.


text:
Q: Marketing Cloud RMM not honoring direct forwards we have been using SFMC for more than a year, utilizing Dynamic Sender Profiles. The RMM feature on the dynamic profile is set to use direct forwards, as we want recipients to engage in direct conversation with our consultants afterwards. However, we stumbled upon some cases, where, the email was correctly send from the respective sender (the consultants personal email address), but the reply of the customer went to the Routing Address for Remaining Replies.
Any ideas why this might me happening?
Just to note that it happened on some emails sends, not all (e.g. same journey, same template, but some customer replies were sent directly, as expected, some were routed)
Thanks,
Emil


text:
Q: Standard Deviation coming up NA when using summarise() function I am trying to calculate descriptive statistics for the birthweight data set (birthwt) found in RStudio. However, I'm only interested in a few variables: age, ftv, ptl and lwt.
This is the code I have so far:
library(MASS)
library(dplyr)
data("birthwt")

grouped <- group_by(birthwt, age, ftv, ptl, lwt)

summarise(grouped,
          mean = mean(bwt),
          median = median(bwt),
          SD = sd(bwt))

It gives me a pretty-printed table but only a limited number of the SD is filled and the rest say NA. I just can't work out why or how to fix it!

A: I stumbled here for another reason and also for me, the answer comes from the docs:
# BEWARE: reusing variables may lead to unexpected results
mtcars %>%
    group_by(cyl) %>%
    summarise(disp = mean(disp), sd = sd(disp))
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 3 x 3
#>     cyl  disp    sd
#>   <dbl> <dbl> <dbl>
#> 1     4  105.    NA
#> 2     6  183.    NA
#> 3     8  353.    NA

So, in case someone has the same reason as me, instead of reusing a variable, create new ones:
mtcars %>%
group_by(cyl) %>%
summarise(
    disp_mean = mean(disp),
    disp_sd = sd(disp)
)

`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 3 x 3
    cyl disp_mean disp_sd
  <dbl>     <dbl>   <dbl>
1     4      105.    26.9
2     6      183.    41.6
3     8      353.    67.8

A: The number of rows for some of the groups are 1.
grouped %>%
     summarise(n = n())
# A tibble: 179 x 5
# Groups: age, ftv, ptl [?]
#     age   ftv   ptl   lwt     n
#   <int> <int> <int> <int> <int>
# 1    14     0     0   135     1
# 2    14     0     1   101     1
# 3    14     2     0   100     1
# 4    15     0     0    98     1
# 5    15     0     0   110     1
# 6    15     0     0   115     1
# 7    16     0     0   110     1
# 8    16     0     0   112     1
# 9    16     0     0   135     2
#10    16     1     0    95     1

According to ?sd,

The standard deviation of a length-one vector is NA.

This results in NA values for the sd where there is only one element


text:
Q: Cannot find the match from the Route variable path (properties of undefined (reading 'params')) I am pretty new to JavaScript and React, Just following some youtube tutorials.
I am not able to get the "roomCode" from the url "/room/:roomCode".
Homepage.js
<Route path={"/room/:roomCode"} element={<Room />} />

Room.js
import React, {Component} from "react";

export default class Room extends Component {
    constructor(props) {
        super(props);
        this.roomCode = this.props.match.params.roomCode;
    }
    render() {
        return (

{this.roomCode}

        );
    }
}

I am not able to print roomCode, need step by step instruction where I need to change my code.

A: React router v6 has dropped support for class based components. See this github thread https://github.com/remix-run/react-router/issues/8146
Convert Room component function component and then use the useParams react hook.
I've converted your class based component to a function component.
import { useParams } from "react-router-dom";

const Room = () => {
  const { id } = useParams();

  return (

{id}

  );

}

export default Room

Edit:
I noticed you have curly braces around your route path, remove those so it should look like so,
<Route path="/room/:roomCode" element={<Room />} />


text:
Q: Python PyQt5 open window and close after 10 seconds? This is my code, how can I make the opened window to close automatically after 10s? I tried with the time.sleep(10) and then win.close() but it doesn't do anything.
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys

def window():
    app = QApplication(sys.argv)
    win = QMainWindow()
    win.setGeometry(200,200,300,300)
    win.setWindowTitle("test")

    label = QtWidgets.QLabel(win)
    label.setText("test")
    label.move(50,50)
    win.show()
    sys.exit(app.exec_())

window()