问:
Swift Get Text Selection Events for UIWebView in Cordova Ionic Application
Currently, I have a Cordova ionic-angularjs application where I want to freeze the scrolling while the user is selecting text (I enable the context menu by following this little hack)

Right now, I have the Swift native code capturing UIMenuController.didShowMenuNotification and UIMenuController.didHideMenuNotification events, which, in turn, dispatches respective javascript document events to be handled by the web application and freezes the $ionicScrollDelegate, as shown below. This works great and the scroll is frozen upon display of the context menu, however, if the user wants to expand/contract the selection, the context menu disappears temporarily during the expansion/contraction, which unfreezes the scroll view until the context menu reappears after the user lifts their finger. Would it be possible to get the range of selected text instead of basing the freeze of the scroll view on the context menu display state, so that the scroll view is frozen until no text is selected?

CDVContextMenu.swift

@objc(CDVContextMenu)
class CDVContextMenu: CDVPlugin {

    typealias This = CDVContextMenu
    static var sharedCommandDelegate: CDVCommandDelegate?
    var contextMenuVisible = false

    override func pluginInitialize() {
        super.pluginInitialize()
        This.sharedCommandDelegate = commandDelegate
        NotificationCenter.default
            .addObserver(self,
                         selector: #selector(menuDidShow),
                         name: UIMenuController.didShowMenuNotification,
                         object: nil)
        NotificationCenter.default
            .addObserver(self,
                         selector: #selector(menuDidHide),
                         name: UIMenuController.didHideMenuNotification,
                         object: nil)
    }

    // MARK: - Event Handlers

    @objc
    func menuDidShow(_ notification: Notification) {
        This.sharedCommandDelegate?.evalJs("document.dispatchEvent(new Event('contextMenuDidShow'));")
        contextMenuVisible = true
    }

    @objc
    func menuDidHide(_ notification: Notification) {
        This.sharedCommandDelegate?.evalJs("document.dispatchEvent(new Event('contextMenuDidHide'));")
        contextMenuVisible = false
    }

}
```

<p><strong>index.js</strong></p>

<pre class="lang-js prettyprint-override"><code>document.addEventListener('contextMenuDidShow', function() {
  $ionicScrollDelegate.freezeScroll(true);
})

document.addEventListener('contextMenuDidHide', function() {
  $ionicScrollDelegate.freezeScroll(false);
})
</code>```

答:
I found a work around by doing this in the javascript without the need for a plugin:

document.addEventListener('selectionchange', function() {
    $ionicScrollDelegate.freezeScroll(true);
});
document.addEventListener('touchend', function() {
    $ionicScrollDelegate.freezeScroll(false);
})
```

Body:
Currently, I have a Cordova ionic-angularjs application where I want to freeze the scrolling while the user is selecting text (I enable the context menu by following this little hack)

Right now, I have the Swift native code capturing UIMenuController.didShowMenuNotification and UIMenuController.didHideMenuNotification events, which, in turn, dispatches respective javascript document events to be handled by the web application and freezes the $ionicScrollDelegate, as shown below. This works great and the scroll is frozen upon display of the context menu, however, if the user wants to expand/contract the selection, the context menu disappears temporarily during the expansion/contraction, which unfreezes the scroll view until the context menu reappears after the user lifts their finger. Would it be possible to get the range of selected text instead of basing the freeze of the scroll view on the context menu display state, so that the scroll view is frozen until no text is selected?

CDVContextMenu.swift

@objc(CDVContextMenu)
class CDVContextMenu: CDVPlugin {

    typealias This = CDVContextMenu
    static var sharedCommandDelegate: CDVCommandDelegate?
    var contextMenuVisible = false

    override func pluginInitialize() {
        super.pluginInitialize()
        This.sharedCommandDelegate = commandDelegate
        NotificationCenter.default
            .addObserver(self,
                         selector: #selector(menuDidShow),
                         name: UIMenuController.didShowMenuNotification,
                         object: nil)
        NotificationCenter.default
            .addObserver(self,
                         selector: #selector(menuDidHide),
                         name: UIMenuController.didHideMenuNotification,
                         object: nil)
    }

    // MARK: - Event Handlers

    @objc
    func menuDidShow(_ notification: Notification) {
        This.sharedCommandDelegate?.evalJs("document.dispatchEvent(new Event('contextMenuDidShow'));")
        contextMenuVisible = true
    }

    @objc
    func menuDidHide(_ notification: Notification) {
        This.sharedCommandDelegate?.evalJs("document.dispatchEvent(new Event('contextMenuDidHide'));")
        contextMenuVisible = false
    }

}

index.js

document.addEventListener('contextMenuDidShow', function() {
  $ionicScrollDelegate.freezeScroll(true);
})

document.addEventListener('contextMenuDidHide', function() {
  $ionicScrollDelegate.freezeScroll(false);
})


来源: stackexchange

问:
How to Replace text characters only in a column with date values but of VARCHAR data type in MySQL?
I have a table with a column of dates which has had various values that have been cleansed from Excel dates etc to mysql dates and the last step that I want to run is to remove any non-date values in the column before I run an alter command to change the data type to DATE but unfortunately the query that I have written is giving me a few issues. The following is a sample of my dates:

```<code>CREATE TABLE `date_checks`
        (
        `Start_Date` varchar(255) DEFAULT NULL
        );
</code>```

My Insert Statements:

```<code>INSERT INTO `date_checks` (`Start_Date`) VALUES
('04/04/2018'),
('01/05/2018'),
('3 years'),
('28/05/2018');
</code>```

My Output

```<code>Start_Date
    04/04/2018
    01/05/2018
    3 years
    28/05/2018
</code>```

The query that I am running is the following:

```<code>UPDATE 'date_checks' SET Start_Date = '' WHERE Start_Date NOT REGEXP '^[0-9]';
</code>```

Now I am guessing because I have the value 3 at the start of my 3rd row, this won't get deleted, so I just wanted to get some help to make sure I do this the right way as all I would like in this column is date values. The REGEXP I have written is looking for everything that does not begin with a number but I am guessing I need to expand this to the way the dates are in the column for it to be more specific and accurate.

If the above code runs OK, then I will run the following to change the data type:

```<code>ALTER TABLE date_checks MODIFY Start_Date DATE;
</code>```

Would appreciate it, if somebody could advise that I am going about this the right way.

答:
MySQL doesn't understand dates in DD/MM/YYYY format. If you do the ALTER TABLE statement you show, it will fail to convert those dates into their DATE type value.

You need to convert the strings to YYYY-MM-DD format.

I'd suggest starting with a new column:

```<code>ALTER TABLE date_checks ADD COLUMN Start_Date2 DATE;
</code>```

Then copy the values to the new column.

```<code>UPDATE date_checks SET Start_Date2 = STR_TO_DATE(Start_Date, '%d/%m/%Y');
</code>```

If a string like '3 years' isn't in a format that matches the format string in that function, then STR_TO_DATE() returns NULL.

So after this UPDATE you will have most of your dates copied into the proper format, but those that couldn't be parsed will be NULL.

Then you can check for oddball cases that failed to be parsed. These might be few enough that you want to update them in the new column manually.

```<code>SELECT Start_Date FROM date_checks WHERE Start_Date2 IS NULL;
</code>```

After you've manually assigned any you want to keep, the remaining Start_Date strings are not worth keeping. Then you can feel free to drop the old column, and rename the new column.

```<code>ALTER TABLE date_checks DROP COLUMN Start_Date,
    CHANGE COLUMN Start_Date2 Start_Date DATE;
</code>```

Re your comment:

How would I change the Update Code to accept both?

I don't know that it's necessary to do this in one pass. You could do it in several passes:

```<code>UPDATE date_checks SET Start_Date2 = STR_TO_DATE(Start_Date, '%d/%m/%Y');
UPDATE date_checks SET Start_Date2 = STR_TO_DATE(Start_Date, '%d-%m-%Y') WHERE Start_Date2 IS NULL;
UPDATE date_checks SET Start_Date2 = STR_TO_DATE(Start_Date, '%d.%m.%Y') WHERE Start_Date2 IS NULL;
...other formats...
</code>```

So after each pass, fewer rows would still have NULL for the Start_Date2. You keep trying other formats as needed, until either there aren't any more NULLs, or you want to give up because the last few stragglers aren't parseable.

Like what do you do if there's one left, but the string in Start_Date reads, "as old as my tongue and a little bit older than my teeth"?

If you really need it to be done in one pass, you can use COALESCE() with several tries:

```<code>UPDATE date_checks SET Start_Date2 = COALESCE(
  STR_TO_DATE(Start_Date, '%d/%m/%Y'),
  STR_TO_DATE(Start_Date, '%d-%m-%Y'),
  STR_TO_DATE(Start_Date, '%d.%m.%Y')
  ...other formats...
);
</code>```

COALESCE() returns its first non-NULL argument. So it will try each of these STR_TO_DATE() calls in order, left-to-right, and the result will be first one that succeeds. Or else NULL if none succeed.

ContentLicense: CC BY-SA 4.0

Body:
I have a table with a column of dates which has had various values that have been cleansed from Excel dates etc to mysql dates and the last step that I want to run is to remove any non-date values in the column before I run an alter command to change the data type to DATE but unfortunately the query that I have written is giving me a few issues. The following is a sample of my dates:

CREATE TABLE `date_checks`
        (
        `Start_Date` varchar(255) DEFAULT NULL
        );

My Insert Statements:

INSERT INTO `date_checks` (`Start_Date`) VALUES
('04/04/2018'),
('01/05/2018'),
('3 years'),
('28/05/2018');

My Output

Start_Date
    04/04/2018
    01/05/2018
    3 years
    28/05/2018

The query that I am running is the following:

UPDATE 'date_checks' SET Start_Date = '' WHERE Start_Date NOT REGEXP '^[0-9]';

Now I am guessing because I have the value 3 at the start of my 3rd row, this won't get deleted, so I just wanted to get some help to make sure I do this the right way as all I would like in this column is date values. The REGEXP I have written is looking for everything that does not begin with a number but I am guessing I need to expand this to the way the dates are in the column for it to be more specific and accurate.

If the above code runs OK, then I will run the following to change the data type:

ALTER TABLE date_checks MODIFY Start_Date DATE;

Would appreciate it, if somebody could advise that I am going about this the right way.

Body:
MySQL doesn't understand dates in DD/MM/YYYY format. If you do the ALTER TABLE statement you show, it will fail to convert those dates into their DATE type value.

You need to convert the strings to YYYY-MM-DD format.

I'd suggest starting with a new column:

ALTER TABLE date_checks ADD COLUMN Start_Date2 DATE;

Then copy the values to the new column.

UPDATE date_checks SET Start_Date2 = STR_TO_DATE(Start_Date, '%d/%m/%Y');

If a string like '3 years' isn't in a format that matches the format string in that function, then STR_TO_DATE() returns NULL.

So after this UPDATE you will have most of your dates copied into the proper format, but those that couldn't be parsed will be NULL.

Then you can check for oddball cases that failed to be parsed. These might be few enough that you want to update them in the new column manually.

SELECT Start_Date FROM date_checks WHERE Start_Date2 IS NULL;

After you've manually assigned any you want to keep, the remaining Start_Date strings are not worth keeping. Then you can feel free to drop the old column, and rename the new column.

ALTER TABLE date_checks DROP COLUMN Start_Date,
    CHANGE COLUMN Start_Date2 Start_Date DATE;

Re your comment:

How would I change the Update Code to accept both?

I don't know that it's necessary to do this in one pass. You could do it in several passes:

UPDATE date_checks SET Start_Date2 = STR_TO_DATE(Start_Date, '%d/%m/%Y');
UPDATE date_checks SET Start_Date2 = STR_TO_DATE(Start_Date, '%d-%m-%Y') WHERE Start_Date2 IS NULL;
UPDATE date_checks SET Start_Date2 = STR_TO_DATE(Start_Date, '%d.%m.%Y') WHERE Start_Date2 IS NULL;
...other formats...

So after each pass, fewer rows would still have NULL for the Start_Date2. You keep trying other formats as needed, until either there aren't any more NULLs, or you want to give up because the last few stragglers aren't parseable.

Like what do you do if there's one left, but the string in Start_Date reads, "as old as my tongue and a little bit older than my teeth"?

If you really need it to be done in one pass, you can use COALESCE() with several tries:

UPDATE date_checks SET Start_Date2 = COALESCE(
  STR_TO_DATE(Start_Date, '%d/%m/%Y'),
  STR_TO_DATE(Start_Date, '%d-%m-%Y'),
  STR_TO_DATE(Start_Date, '%d.%m.%Y')
  ...other formats...
);

COALESCE() returns its first non-NULL argument. So it will try each of these STR_TO_DATE() calls in order, left-to-right, and the result will be first one that succeeds. Or else NULL if none succeed.


问:
Convert from HTML to string XQuery
I have text below

Some Text.

Another Text.

Bla bla bla.

I need to convert it in:

"Some Text.

Another Text.

Bla bla bla."

How can i do it in XQuery?

答:
In MarkLogic, you can use the xdmp:unquote() function with the repair-full option:

```<code>let $html := "<p>Some Text. </p><p><br></p><p>Another Text.</p><p><br></p><p>Bla bla bla.</p>"
let $xhtml := xdmp:unquote($html, "", "repair-full")
return $xhtml//text()
</code>```

Which will return a sequence of text() nodes. If you want a single string, you could change the return to fn:string-join($xhtml//text(), "
")

In BaseX, you could use the html:parse() method

In Saxon, you could use the saxon:parse-html() method

Title: Convert from HTML to string XQuery

Body:
In MarkLogic, you can use the xdmp:unquote() function with the repair-full option:

let $html := "<p>Some Text. </p><p><br></p><p>Another Text.</p><p><br></p><p>Bla bla bla.</p>"
let $xhtml := xdmp:unquote($html, "", "repair-full")
return $xhtml//text()

Which will return a sequence of text() nodes. If you want a single string, you could change the return to fn:string-join($xhtml//text(), "&#10;")

In BaseX, you could use the html:parse() method

In Saxon, you could use the saxon:parse-html() method


问:
iterate array of object and save values
I have this objects in Javascript:

```<code>products = {
    {
      family : 'mugs', name :'black mug' , article_id : 1728
    },
    {
      family : 'tees', name :'red t-shirt' , article_id : 1332
    },
    {
      family : 'mugs', name :'tea white mug' , article_id : 2748
    },
    {
      family : 'tees', name :'green woman t-shirt' , article_id : 1332
    },
}
</code>```

I want to group the articles_ids in the same family.
I want get this result:

```<code>grouped_products = {
    {
      family : 'mugs', articles_ids : '1728,2748' //only mugs articles ids
    },
    {
      family : 'tees', articles_ids : '1332,1332' //only tees articles ids
    },
}
</code>```

I try with forEach and filter methods, but I dont know how to make this with perform mode.

答:
As @terry said products should be array like :

```<code>products = [
    {
        family : 'mugs', name :'black mug' , article_id : 1728
    },
    {
        family : 'tees', name :'red t-shirt' , article_id : 1332
    },
    {
        family : 'mugs', name :'tea white mug' , article_id : 2748
    },
    {
        family : 'tees', name :'green woman t-shirt' , article_id : 1332
    }
];
</code>```

Now, to get desired output you can do this :

```<code>let group= products.reduce((prev, curr) => {
   let i = prev.findIndex(item => item.family === curr.family);

   if(i > -1){
       prev[i].article_ids.push(curr.article_id);
   }else{
       prev.push({
           family: curr.family,
           article_ids: [curr.article_id]
       });
    }
    return prev;
},[]);
</code>```

Title: iterate array of object and save values

Body:
I have this objects in Javascript:

products = {
    {
      family : 'mugs', name :'black mug' , article_id : 1728
    },
    {
      family : 'tees', name :'red t-shirt' , article_id : 1332
    },
    {
      family : 'mugs', name :'tea white mug' , article_id : 2748
    },
    {
      family : 'tees', name :'green woman t-shirt' , article_id : 1332
    },
}

I want to group the articles_ids in the same family.
I want get this result:

grouped_products = {
    {
      family : 'mugs', articles_ids : '1728,2748' //only mugs articles ids
    },
    {
      family : 'tees', articles_ids : '1332,1332' //only tees articles ids
    },
}

I try with forEach and filter methods, but I dont know how to make this with perform mode.

Body:
As @terry said products should be array like :

products = [
    {
        family : 'mugs', name :'black mug' , article_id : 1728
    },
    {
        family : 'tees', name :'red t-shirt' , article_id : 1332
    },
    {
        family : 'mugs', name :'tea white mug' , article_id : 2748
    },
    {
        family : 'tees', name :'green woman t-shirt' , article_id : 1332
    }
];

Now, to get desired output you can do this :

let group= products.reduce((prev, curr) => {
   let i = prev.findIndex(item => item.family === curr.family);

   if(i > -1){
       prev[i].article_ids.push(curr.article_id);
   }else{
       prev.push({
           family: curr.family,
           article_ids: [curr.article_id]
       });
    }
    return prev;
},[]);


问:
Unable to insert stylesheet/script into window.open
I have been fighting this issue for quite some time now, and have been (still) unable to print my div with its styling.

Currently, my script is:

```<code>$('#printMeButton').click(function () {
    //alert("a");
    var data = document.getElementById('thisPrintableTable').outerHTML;

    var mywindow = window.open('', data);
    mywindow.document.write('<html><head><title>Print Me!!!</title>');
    // mywindow.document.write('<link rel="stylesheet" type="text/css" href="Site.css" media="screen">');
    mywindow.document.write('</head><body>');
    mywindow.document.write(data);
    mywindow.document.write('</body></html>');

    mywindow.document.close();
    mywindow.focus();
    mywindow.print();
    mywindow.close();
    return true;

});
</code>```

which is nested within a $(document).ready function.

When I include the desired stylesheet (currently commented out), Nothing appears in the print preview.

I also have some script that has an effect on the appearance of the table, and, as such, I believe this may hold the key of having these included into the popup window.

How can i include this into the new popup?

Could someone please suggest a way of printing this as it stands?

Edit History

removed space at end of

Changed var data to have outerHTML instead of innerHTML

Altered Question/details from better understanding of issue

答:
We can use this inline style.</p>

```<code>var divToPrint = document.getElementById('DivIdToPrint');

var newWin=window.open('','Print-Window');

newWin.document.open();

newWin.document.write('<html>' +
    '<style>' +
    ".btn-petty-cash-split{display: none}"+
    ".btn-petty-cash-split{display: none}"+
    '</style>' +
    '<body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');

newWin.document.close();

setTimeout(function(){
    newWin.close();
    window.location.reload();
},10);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been fighting this issue for quite some time now, and have been (still) unable to print my div with its styling.

Currently, my script is:

$('#printMeButton').click(function () {
    //alert("a");
    var data = document.getElementById('thisPrintableTable').outerHTML;

    var mywindow = window.open('', data);
    mywindow.document.write('<title>Print Me!!!</title>');
    // mywindow.document.write('<link rel="stylesheet" type="text/css" href="Site.css" media="screen">');
    mywindow.document.write('');
    mywindow.document.write(data);
    mywindow.document.write('');

    mywindow.document.close();
    mywindow.focus();
    mywindow.print();
    mywindow.close();
    return true;

});

which is nested within a $(document).ready function.

When I include the desired stylesheet (currently commented out), Nothing appears in the print preview.

I also have some script that has an effect on the appearance of the table, and, as such, I believe this may hold the key of having these included into the popup window.

How can i include this into the new popup?

Could someone please suggest a way of printing this as it stands?

Edit History

removed space at end of

Changed var data to have outerHTML instead of innerHTML

Altered Question/details from better understanding of issue

Body:
We can use this inline style.

var divToPrint = document.getElementById('DivIdToPrint');

var newWin=window.open('','Print-Window');

newWin.document.open();

newWin.document.write('<html>' +
    '<style>' +
    ".btn-petty-cash-split{display: none}"+
    ".btn-petty-cash-split{display: none}"+
    '</style>' +
    '<body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');

newWin.document.close();

setTimeout(function(){
    newWin.close();
    window.location.reload();
},10);


问:
Using bash functions in snakemake
I am trying to download some files with snakemake. The files (http://snpeff.sourceforge.net/SnpSift.html#dbNSFP) I would like to download are on a google site/drive and my usual wget approach does not work. I found a bash function that does the job (https://www.zachpfeffer.com/single-post/wget-a-Google-Drive-file):

```<code>function gdrive_download () {  CONFIRM=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate "https://docs.google.com/uc?export=download&id=$1" -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')  wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$CONFIRM&id=$1" -O $2  rm -rf /tmp/cookies.txt }

gdrive_download 120aPYqveqPx6jtssMEnLoqY0kCgVdR2fgMpb8FhFNHo test.txt
</code>```

I have tested this function with my ids in a plain bash script and was able to download all the files. To add a bit to the complexity, I must use a workplace template, and incorporate the function into it.

```<code>rule dl:
    params:
        url = 'ftp://ftp.ncbi.nlm.nih.gov/pub/clinvar/vcf_{genome}/{afile}'
    output:
        'data/{genome}/{afile}'
    params:
        id1 = '0B7Ms5xMSFMYlOTV5RllpRjNHU2s',
        f1 = 'dbNSFP.txt.gz'
    shell:
        """CONFIRM=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate "https://docs.google.com/uc?export=download&id={{params.id1}}" -O- | sed -rn "s/.*confirm=([0-9A-Za-z_]+).*/\1\n/p") && wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$CONFIRM&id={{params.id1}}" -O {{params.f1}} && rm -rf /tmp/cookies.txt"""
        #'wget -c {params.url} -O {output}'

rule checksum:
    input:
        i = 'data/{genome}/{afile}'
    output:
        o = temp('tmp/{genome}/{afile}.md5')
    shell:
        'md5sum {input} > {output}'

rule file_size:
    input:
        i = 'data/{genome}/{afile}'
    output:
        o = temp('tmp/{genome}/{afile}.size')
    shell:
        'du -csh --apparent-size {input} > {output}'

rule file_info:
    """md5 checksum and file size"""
    input:
        md5 = 'tmp/{genome}/{afile}.md5',
        s = 'tmp/{genome}/{afile}.size'
    output:
        o = temp('tmp/{genome}/info/{afile}.csv')
    run:
        with open(input.md5) as f:
            md5, fp = f.readline().strip().split()
        with open(input.s) as f:
            size = f.readline().split()[0]
        with open(output.o, 'w') as fout:
            print('filepath,size,md5', file=fout)
            print(f"{fp},{size},{md5}", file=fout)

rule manifest:
    input:
        expand('tmp/{genome}/info/{suffix}.csv', genome=('GRCh37','GRCh38'), suffix=('dbNSFP.txt.gz', 'dbNSFP.txt.gz.tbi'))
        #expand('tmp/{genome}/info/SnpSift{suffix}.csv', genome=('GRCh37','GRCh38'), suffix=('dbNSFP.txt.gz', 'dbNSFP.txt.gz.tbi'))
    output:
        o = 'MANIFEST.csv'
    run:
        pd.concat([pd.read_csv(afile) for afile in input]).to_csv(output.o, index=False)
</code>```

There are four downloadable files for which I have ids (I only show one in params), however I don't know how to call the bash functions as written by ZPfeffer for all the ids I have with snakemake. Additionally, when I run this script, there are several errors, the most pressing being

```<code>sed: -e expression #1, char 31: unterminated `s' command
</code>```

I am far from a snakemake expert, any assistance on how to modify my script to a) call the functions with 4 different ids, b) remove the sed error, and c) verify whether this is the correct url format (currently url = 'https://docs.google.com/uc?export/{afile}) will be greatly appreciated.

答:
Here is how I "solved" it:

```<code>import pandas as pd

rule dl:
    output:
        'data/{genome}/{afile}'
    shell:
        "sh download_snpsift.sh"

rule checksum:
    input:
        i = 'data/{genome}/{afile}'
    output:
        o = temp('tmp/{genome}/{afile}.md5')
    shell:
        'md5sum {input} > {output}'

rule file_size:
    input:
        i = 'data/{genome}/{afile}'
    output:
        o = temp('tmp/{genome}/{afile}.size')
    shell:
        'du -csh --apparent-size {input} > {output}'

rule file_info:
    """md5 checksum and file size"""
    input:
        md5 = 'tmp/{genome}/{afile}.md5',
        s = 'tmp/{genome}/{afile}.size'
    output:
        o = temp('tmp/{genome}/info/{afile}.csv')
    run:
        with open(input.md5) as f:
            md5, fp = f.readline().strip().split()
        with open(input.s) as f:
            size = f.readline().split()[0]
        with open(output.o, 'w') as fout:
            print('filepath,size,md5', file=fout)
            print(f"{fp},{size},{md5}", file=fout)

rule manifest:
    input:
        expand('tmp/{genome}/info/{suffix}.csv', genome=('GRCh37','GRCh38'), suffix=('dbNSFP.txt.gz', 'dbNSFP.txt.gz.tbi'))
    output:
        o = 'MANIFEST.csv'
    run:
        pd.concat([pd.read_csv(afile) for afile in input]).to_csv(output.o, index=False)
</code>```

And here is the bash script.

```<code>function gdrive_download () {
 CONFIRM=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate "https://docs.google.com/uc?export=download&id=$1" -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')
 wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$CONFIRM&id=$1" -O $2
 rm -rf /tmp/cookies.txt
}

gdrive_download 0B7Ms5xMSFMYlSTY5dDJjcHVRZ3M data/GRCh37/dbNSFP.txt.gz
gdrive_download 0B7Ms5xMSFMYlOTV5RllpRjNHU2s data/GRCh37/dbNSFP.txt.gz.tbi

gdrive_download 0B7Ms5xMSFMYlbTZodjlGUDZnTGc data/GRCh38/dbNSFP.txt.gz
gdrive_download 0B7Ms5xMSFMYlNVBJdFA5cFZRYkE data/GRCh38/dbNSFP.txt.gz.tbi
</code>```

Title: Using bash functions in snakemake

Body:
I am trying to download some files with snakemake. The files (http://snpeff.sourceforge.net/SnpSift.html#dbNSFP) I would like to download are on a google site/drive and my usual wget approach does not work. I found a bash function that does the job (https://www.zachpfeffer.com/single-post/wget-a-Google-Drive-file):

function gdrive_download () {  CONFIRM=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate "https://docs.google.com/uc?export=download&id=$1" -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')  wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$CONFIRM&id=$1" -O $2  rm -rf /tmp/cookies.txt }

gdrive_download 120aPYqveqPx6jtssMEnLoqY0kCgVdR2fgMpb8FhFNHo test.txt

I have tested this function with my ids in a plain bash script and was able to download all the files. To add a bit to the complexity, I must use a workplace template, and incorporate the function into it.

rule dl:
    params:
        url = 'ftp://ftp.ncbi.nlm.nih.gov/pub/clinvar/vcf_{genome}/{afile}'
    output:
        'data/{genome}/{afile}'
    params:
        id1 = '0B7Ms5xMSFMYlOTV5RllpRjNHU2s',
        f1 = 'dbNSFP.txt.gz'
    shell:
        """CONFIRM=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate "https://docs.google.com/uc?export=download&id={{params.id1}}" -O- | sed -rn "s/.*confirm=([0-9A-Za-z_]+).*/\1\n/p") && wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$CONFIRM&id={{params.id1}}" -O {{params.f1}} && rm -rf /tmp/cookies.txt"""
        #'wget -c {params.url} -O {output}'

rule checksum:
    input:
        i = 'data/{genome}/{afile}'
    output:
        o = temp('tmp/{genome}/{afile}.md5')
    shell:
        'md5sum {input} > {output}'

rule file_size:
    input:
        i = 'data/{genome}/{afile}'
    output:
        o = temp('tmp/{genome}/{afile}.size')
    shell:
        'du -csh --apparent-size {input} > {output}'

rule file_info:
    """md5 checksum and file size"""
    input:
        md5 = 'tmp/{genome}/{afile}.md5',
        s = 'tmp/{genome}/{afile}.size'
    output:
        o = temp('tmp/{genome}/info/{afile}.csv')
    run:
        with open(input.md5) as f:
            md5, fp = f.readline().strip().split()
        with open(input.s) as f:
            size = f.readline().split()[0]
        with open(output.o, 'w') as fout:
            print('filepath,size,md5', file=fout)
            print(f"{fp},{size},{md5}", file=fout)

rule manifest:
    input:
        expand('tmp/{genome}/info/{suffix}.csv', genome=('GRCh37','GRCh38'), suffix=('dbNSFP.txt.gz', 'dbNSFP.txt.gz.tbi'))
        #expand('tmp/{genome}/info/SnpSift{suffix}.csv', genome=('GRCh37','GRCh38'), suffix=('dbNSFP.txt.gz', 'dbNSFP.txt.gz.tbi'))
    output:
        o = 'MANIFEST.csv'
    run:
        pd.concat([pd.read_csv(afile) for afile in input]).to_csv(output.o, index=False)

There are four downloadable files for which I have ids (I only show one in params), however I don't know how to call the bash functions as written by ZPfeffer for all the ids I have with snakemake. Additionally, when I run this script, there are several errors, the most pressing being

sed: -e expression #1, char 31: unterminated `s' command

I am far from a snakemake expert, any assistance on how to modify my script to a) call the functions with 4 different ids, b) remove the sed error, and c) verify whether this is the correct url format (currently url = 'https://docs.google.com/uc?export/{afile}) will be greatly appreciated.

Body:
Here is how I "solved" it:

import pandas as pd

rule dl:
    output:
        'data/{genome}/{afile}'
    shell:
        "sh download_snpsift.sh"

rule checksum:
    input:
        i = 'data/{genome}/{afile}'
    output:
        o = temp('tmp/{genome}/{afile}.md5')
    shell:
        'md5sum {input} > {output}'

rule file_size:
    input:
        i = 'data/{genome}/{afile}'
    output:
        o = temp('tmp/{genome}/{afile}.size')
    shell:
        'du -csh --apparent-size {input} > {output}'

rule file_info:
    """md5 checksum and file size"""
    input:
        md5 = 'tmp/{genome}/{afile}.md5',
        s = 'tmp/{genome}/{afile}.size'
    output:
        o = temp('tmp/{genome}/info/{afile}.csv')
    run:
        with open(input.md5) as f:
            md5, fp = f.readline().strip().split()
        with open(input.s) as f:
            size = f.readline().split()[0]
        with open(output.o, 'w') as fout:
            print('filepath,size,md5', file=fout)
            print(f"{fp},{size},{md5}", file=fout)

rule manifest:
    input:
        expand('tmp/{genome}/info/{suffix}.csv', genome=('GRCh37','GRCh38'), suffix=('dbNSFP.txt.gz', 'dbNSFP.txt.gz.tbi'))
    output:
        o = 'MANIFEST.csv'
    run:
        pd.concat([pd.read_csv(afile) for afile in input]).to_csv(output.o, index=False)

And here is the bash script.

function gdrive_download () {
 CONFIRM=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate "https://docs.google.com/uc?export=download&id=$1" -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')
 wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$CONFIRM&id=$1" -O $2
 rm -rf /tmp/cookies.txt
}

gdrive_download 0B7Ms5xMSFMYlSTY5dDJjcHVRZ3M data/GRCh37/dbNSFP.txt.gz
gdrive_download 0B7Ms5xMSFMYlOTV5RllpRjNHU2s data/GRCh37/dbNSFP.txt.gz.tbi

gdrive_download 0B7Ms5xMSFMYlbTZodjlGUDZnTGc data/GRCh38/dbNSFP.txt.gz
gdrive_download 0B7Ms5xMSFMYlNVBJdFA5cFZRYkE data/GRCh38/dbNSFP.txt.gz.tbi


问:
Use a CodeBehind Boolean to update visibility of control
I have the following code;

```<code>public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        bool _myValue;
        public bool myValue
        {
            get { return _myValue; }
            set {
                _myValue = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("myValue"));
            }
        }

        public MainWindow() {
            myValue = false;
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += timer_Tick;
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e) {
            myValue = !myValue;
            lblTime.Content = myValue.ToString();
        }
    }
</code>```

and the corresponding xaml:

```<code>    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVis" />
    </Window.Resources>
    <DockPanel Margin="10">
        <Button x:Name="HideMe"
             Height="50" Width="50"
            Cursor="Hand"
            Visibility="{Binding Path=myValue, Converter={StaticResource BoolToVis}}"/>
        <Label x:Name="lblTime" />
    </DockPanel>

</code>```

What i am trying to do; is update the visibility of the button with every timer_tick;
The label is updated, yet the binding refuses to work

I am very sure there is an oversight, but after following numerous tutorials, there is none on how I can make this work.. most work with a checkbox on the WPF; but I need the boolean in the codebehind to send to control the visibility of the button, once it's updated..

答:
mm8 gave you the perfect answer to your question (setting the data context) - I just want to point out one small thing that should make your life muchhhh easier when building your properties.

We can create a function to trigger the property changed event, requiring you to only write "OnPropertyChanged()" to trigger the UI update. To do this, we're going to add the 'void' below, telling it to use a property called "Caller Member Name" by default, unless you manually provide a property name (I.E. OnPropertyChanged("SomeOtherValue");).

To do this, we first need to add a using statement to the top of your UserViewModel class:

```<code>using System.Runtime.CompilerServices;
</code>```

Then, we will add the OnPropertyChanged code and include the 'caller member name' It should look like this:

```<code>    private void OnPropertyChanged([CallerMemberName] String name = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
</code>```

Now - we will update your property to use the simplified method:

```<code>   public bool myValue
   {
     get { return _myValue; }
     set
     {
            _myValue = value;
            OnPropertyChanged();
     }
}
</code>```

Lastly - I've personally prefer a streamlined way for get/set's - What you're doing is completely OK and there is no need to change it if you don't want to, but i'd suggest trying it this way to see how you like it :)

```<code>    public bool MyValue
    {
        get => _myValue;
        set
        {
            // If the value hasn't changed, the code will return (Exit) - avoiding a false property changed trigger :)
            if (_myValue == value) return;
            _myValue = value;
            OnPropertyChanged();
        }
    }
</code>```

Reasons: Checking to see if the value has actually changed in your SET will prevent false triggers, you use less brackets, and intellisense makes writing this super easy!

Let me know if you have any questions!

Body:
I have the following code;

public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        bool _myValue;
        public bool myValue
        {
            get { return _myValue; }
            set {
                _myValue = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("myValue"));
            }
        }

        public MainWindow() {
            myValue = false;
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += timer_Tick;
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e) {
            myValue = !myValue;
            lblTime.Content = myValue.ToString();
        }
    }

and the corresponding xaml:

    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVis" />
    </Window.Resources>
    <DockPanel Margin="10">
        <Button x:Name="HideMe"
             Height="50" Width="50"
            Cursor="Hand"
            Visibility="{Binding Path=myValue, Converter={StaticResource BoolToVis}}"/>

    </DockPanel>

What i am trying to do; is update the visibility of the button with every timer_tick;
The label is updated, yet the binding refuses to work

I am very sure there is an oversight, but after following numerous tutorials, there is none on how I can make this work.. most work with a checkbox on the WPF; but I need the boolean in the codebehind to send to control the visibility of the button, once it's updated..

Body:
mm8 gave you the perfect answer to your question (setting the data context) - I just want to point out one small thing that should make your life muchhhh easier when building your properties.

We can create a function to trigger the property changed event, requiring you to only write "OnPropertyChanged()" to trigger the UI update. To do this, we're going to add the 'void' below, telling it to use a property called "Caller Member Name" by default, unless you manually provide a property name (I.E. OnPropertyChanged("SomeOtherValue");).

To do this, we first need to add a using statement to the top of your UserViewModel class:

using System.Runtime.CompilerServices;

Then, we will add the OnPropertyChanged code and include the 'caller member name' It should look like this:

    private void OnPropertyChanged([CallerMemberName] String name = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }

Now - we will update your property to use the simplified method:

   public bool myValue
   {
     get { return _myValue; }
     set
     {
            _myValue = value;
            OnPropertyChanged();
     }
}

Lastly - I've personally prefer a streamlined way for get/set's - What you're doing is completely OK and there is no need to change it if you don't want to, but i'd suggest trying it this way to see how you like it :)

    public bool MyValue
    {
        get => _myValue;
        set
        {
            // If the value hasn't changed, the code will return (Exit) - avoiding a false property changed trigger :)
            if (_myValue == value) return;
            _myValue = value;
            OnPropertyChanged();
        }
    }

Reasons: Checking to see if the value has actually changed in your SET will prevent false triggers, you use less brackets, and intellisense makes writing this super easy!

Let me know if you have any questions!


问:
JSF: Absolutely need to put expensive Business Logic inside accessor method. How to avoid calling this expensive BL multiples time
Here is my dilemma, I know in JSF the accessor method will get call mutilple times, therefore I know not to put expensive business logic (like DB access) in accessor method. What if I absolutely have to put business logic into my accessor. What should I do in this case? Below are a high level layout of my dilemma. (Mojarra 2.1, GF 3.1)

```<code><h:dataTable value="#{myBean.comments}" var="item1">
    <h:column>
          #{item1.name} says: #{item1.comment}
          <h:dataTable value="#{myBean.handleReplies(item1)}" var="item2">
               <h:column>
                   #{item2.name} replies: #{item2.comment}
               </h:column>
          </h:dataTable>
    </h:column>
</h:dataTable>

@ManagedBean
@ViewScoped
public void myBean(){
    private List<Comment> comments;

    @EJB
    private MyEJB myEJB;

    @PostConstruct
    public void init(){
        comments = myEJB.getAllComments();
    }

    //getters and setters for List<Comment> comments

    public List<Comment> handleReplies(Comment comment){
         //Return a List of replies of the comment
         return myEJB.getRepliesFromComment(comment);
    }
}
</code>```

As you can see, the inner dataTable take in the item of the outer dataTable to generate its List. Is there a way for somehow stop handleReplies() to be called multiple times, since this accessor method access DB.

答:
You can also just let JPA do the lazy loading and caching job (with a proper second level cache).

Assuming that your Comment entity look like this

```<code>@Entity
@NamedQuery(name="Comment.list", query="SELECT c FROM Comment c WHERE c.parent IS NULL")
public class Comment implements Serializable {

    @ManyToOne(optional=false)
    private Comment parent;

    @OneToMany(mappedBy="parent", fetch=LAZY, cascade=ALL);
    private List<Comment> children;

    // ...
}
</code>```

You could just use #{comment.children} to (lazily) get the children in a <h:dataTable>.

Body:
Here is my dilemma, I know in JSF the accessor method will get call mutilple times, therefore I know not to put expensive business logic (like DB access) in accessor method. What if I absolutely have to put business logic into my accessor. What should I do in this case? Below are a high level layout of my dilemma. (Mojarra 2.1, GF 3.1)

<h:dataTable value="#{myBean.comments}" var="item1">
    <h:column>
          #{item1.name} says: #{item1.comment}
          <h:dataTable value="#{myBean.handleReplies(item1)}" var="item2">
               <h:column>
                   #{item2.name} replies: #{item2.comment}
               </h:column>
          </h:dataTable>
    </h:column>
</h:dataTable>

@ManagedBean
@ViewScoped
public void myBean(){
    private List<Comment> comments;

    @EJB
    private MyEJB myEJB;

    @PostConstruct
    public void init(){
        comments = myEJB.getAllComments();
    }

    //getters and setters for List<Comment> comments

    public List<Comment> handleReplies(Comment comment){
         //Return a List of replies of the comment
         return myEJB.getRepliesFromComment(comment);
    }
}

As you can see, the inner dataTable take in the item of the outer dataTable to generate its List. Is there a way for somehow stop handleReplies() to be called multiple times, since this accessor method access DB.

Body:
You can also just let JPA do the lazy loading and caching job (with a proper second level cache).

Assuming that your Comment entity look like this

@Entity
@NamedQuery(name="Comment.list", query="SELECT c FROM Comment c WHERE c.parent IS NULL")
public class Comment implements Serializable {

    @ManyToOne(optional=false)
    private Comment parent;

    @OneToMany(mappedBy="parent", fetch=LAZY, cascade=ALL);
    private List<Comment> children;

    // ...
}

You could just use #{comment.children} to (lazily) get the children in a <h:dataTable>.


问:
Lotusscript - Type mismatch when useing ArrayGetIndex
I have a function where I check if a string is found in a variant:

```<code>Function checkIfValueIsInVariant (tempVariant As Variant, tempValue As String) As Boolean
    Dim valueFound As Boolean

    'zet standaard waarde op niet gevonden
    valueFound = False
    Print "Value : " + tempValue
    If Not IsNull( ArrayGetIndex(tempVariant, tempValue) ) Then
            'waarde is gevonden in variant dus zet op true
            valueFound = true
    End If
        checkIfValueIsInVariant = valueFound
End Function
</code>```

When I go through the code with the debugger then I can see these values:

```<code>tempVariant = "value" type = Variant
tempValue = "value" type = String
</code>```

But when it is executing this line:

```<code>`If Not IsNull( ArrayGetIndex(tempVariant, tempValue) )` Then
</code>```

I get Type mismatch, What am I doing wrong?

答:
Variant is a very bad data type in LotusScript: it can contain anything. ArrayGetIndex expects the first parameter to be An array or Variant containing an array.. In your example tempvariant is a Variant of type string and NOT an array --> Type mismatch.

If I don't know, if I get a scalar or an array in before then usually I write something like that in my code:

```<code>Dim varArray as Variant
Dim arrOneElement(0) as Variant

If not IsArray( tempVariant ) then
    arrOneElement(0) = tempVariant
    varArray = arrOneElement
Else
    varArray = tempVariant
End If
If Not IsNull( ArrayGetIndex(varArray, tempValue) ) Then
</code>```

That way I can put in there (almost) whatever I want and it will return the correct result.

Body:
I have a function where I check if a string is found in a variant:

Function checkIfValueIsInVariant (tempVariant As Variant, tempValue As String) As Boolean
    Dim valueFound As Boolean

    'zet standaard waarde op niet gevonden
    valueFound = False
    Print "Value : " + tempValue
    If Not IsNull( ArrayGetIndex(tempVariant, tempValue) ) Then
            'waarde is gevonden in variant dus zet op true
            valueFound = true
    End If
        checkIfValueIsInVariant = valueFound
End Function

When I go through the code with the debugger then I can see these values:

tempVariant = "value" type = Variant
tempValue = "value" type = String

But when it is executing this line:

`If Not IsNull( ArrayGetIndex(tempVariant, tempValue) )` Then

I get Type mismatch, What am I doing wrong?

Body:
Variant is a very bad data type in LotusScript: it can contain anything. ArrayGetIndex expects the first parameter to be An array or Variant containing an array.. In your example tempvariant is a Variant of type string and NOT an array --> Type mismatch.

If I don't know, if I get a scalar or an array in before then usually I write something like that in my code:

Dim varArray as Variant
Dim arrOneElement(0) as Variant

If not IsArray( tempVariant ) then
    arrOneElement(0) = tempVariant
    varArray = arrOneElement
Else
    varArray = tempVariant
End If
If Not IsNull( ArrayGetIndex(varArray, tempValue) ) Then

That way I can put in there (almost) whatever I want and it will return the correct result.


问:
How we load other languages Data Instead of English Data?
**i need a help i want to display two different languages data in android first one is arabic second is hindi.
instead of english data all data in arabic or hindi.

can we put the arbic or hindi data in deafult strings.xml file.

or

create two different resource files in arabic and hindi than programmatically changes the language through Localization.

i need a solution please help me which is best solution or any other solution.

答:
In android you can easily put language translations in resource qualifier directories.
res/values/strings.xml is the default string which will be shown when the string is not translated.

To translate to arabic, you can create a new strings file
res/values-ar/strings.xml which will contain the translated strings but with the same resource names.

You can find more information from the google docs
How to create alternative resources


问:
How do I access the user selected text within an element ui input?
I want to access the text within an ElInput component via Javascript in Electron. According to mozilla it is impossible to access information within an html input or textfield via window.getSelection.

I unsuccessfully tried to access the selection with the proposed selectionStart

```<code>const input = document.getElementById("input")
alert(input.selectionStart.toString)
</code>```

Given that this doesn't work, what do I have to do, to get the text in my selection within my el-input?

答: <input value="try to select some of the text" onclick="console.log(this.value.substring(this.selectionStart, this.selectionEnd))"/>```

Body:
I want to access the text within an ElInput component via Javascript in Electron. According to mozilla it is impossible to access information within an html input or textfield via window.getSelection.

I unsuccessfully tried to access the selection with the proposed selectionStart

const input = document.getElementById("input")
alert(input.selectionStart.toString)

Given that this doesn't work, what do I have to do, to get the text in my selection within my el-input?


问:
System.TypeInitializationException: 'The type initializer for 'Bid' threw an exception.'
I have a service layer with the target framework set to .NET Standard 2.0. Some of the services uses DbContext from EntityFrameWorkCore.

There are two web projects which uses this service layer:

ASP.NET Core 3.0 (Blazor)

ASP.NET MVC 4.6.2

The Core project uses dependency injection like this (shortened):

```<code>public void ConfigureServices(IServiceCollection services)
{
    var json = File.ReadAllText("appsettings.json");
    var settings = JsonConvert.DeserializeObject<Settings>(json);
    services.AddScoped(provider => new CompetitorContext(settings.ConnectionStrings.Web));
    services.AddScoped<ICompetitorService, CompetitorService>();
}
</code>```

The MVC project uses dependency injection through Unity like this (shortened):

```<code>public static void RegisterComponents()
{
    _container = new UnityContainer();

    var settings =
        JsonConvert.DeserializeObject<Settings>(
            File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
            @"appsettings.json")));

    _container.RegisterInstance(typeof(CompetitorContext), new CompetitorContext(settings.ConnectionStrings.Web));
    _container.RegisterType<ICompetitorService, CompetitorService>();

    DependencyResolver.SetResolver(new UnityDependencyResolver(_container));
}
</code>```

When calling one of the services' method that makes a call to the CompetitorContext (which inherits from DbContext) it works fine in the Core project but in the MVC project I get this error:

```<code>System.TypeInitializationException
  HResult=0x80131534
  Message=The type initializer for 'Bid' threw an exception.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

  This exception was originally thrown at this call stack:
    Bid.internalInitialize()
    Bid.Bid()

Inner Exception 1:
EntryPointNotFoundException: Unable to find an entry point named 'DllBidEntryPoint' in DLL 'System.Data.dll'.
</code>```

Other services that do not use EntityFrameWorkCore works fine, so I think the issue is with using EntityFrameWorkCore together with an .NET MVC 4.6.2 project but I'm not sure.

What might the issue to this exception be or how can I found out more information?

Edited:
The CompetitorService:

```<code>public class CompetitorService : ICompetitorService
    {
        private readonly CompetitorContext _ctx;

        public CompetitorService(CompetitorContext ctx)
        {
            _ctx = ctx;
        }

        public IList<CompetitorModel> GetAll()
        {
           return _ctx.Competitors.OrderBy(c => c.ID).ToList();
        }

        public CompetitorModel GetById(int id)
        {
            return this.GetAll().Where(c => c.ID == id).First();
        }

        public CompetitorModel GetByCompetitorKey(string competitorKey)
        {
            return this.GetAll().Where(c => c.CompetitorKey == competitorKey).FirstOrDefault();
        }
    }
</code>```

The CompetitorContext:

```<code>public class CompetitorContext : DbContext
    {
        public DbSet<CompetitorModel> Competitors { get; set; }

        public CompetitorContext(string connectionString) :
            base(SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options)
        {
        }
    }
</code>```

The CompetitorModel:

```<code>[Table("vw_competitors")]
    public class CompetitorModel
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ID { get; set; }
        public string CompetitorKey { get; set; }
        public string Name { get; set; }
        public string ShortName { get; set; }
        public string Experience { get; set; }
        public string BBB_Rating { get; set; }
        public string BBB_URL { get; set; }
        public string BBB_Complaints { get; set; }
        public string BBB_Accredited { get; set; }
        public string TrustPilot_URL { get; set; }
        public string TrustPilot_Rating { get; set; }
        public string TrustPilot_Reviews { get; set; }
        public string RipoffReport_Complaints { get; set; }
        public string MoneyBackGuarantee { get; set; }
        public DateTime LastUpdated { get; set; }
    }
</code>```

Note: The referenced Bid class is not a data model of mine nor do I have any knowledge of it

答: I've had a simular issue using a .NET Standard 2.0 reference in a WPF application. Removing all references to System.Data(.xxx) in the WPF app did help.</p>

Body:
I have a service layer with the target framework set to .NET Standard 2.0. Some of the services uses DbContext from EntityFrameWorkCore.

There are two web projects which uses this service layer:

ASP.NET Core 3.0 (Blazor)

ASP.NET MVC 4.6.2

The Core project uses dependency injection like this (shortened):

public void ConfigureServices(IServiceCollection services)
{
    var json = File.ReadAllText("appsettings.json");
    var settings = JsonConvert.DeserializeObject<Settings>(json);
    services.AddScoped(provider => new CompetitorContext(settings.ConnectionStrings.Web));
    services.AddScoped<ICompetitorService, CompetitorService>();
}

The MVC project uses dependency injection through Unity like this (shortened):

public static void RegisterComponents()
{
    _container = new UnityContainer();

    var settings =
        JsonConvert.DeserializeObject<Settings>(
            File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
            @"appsettings.json")));

    _container.RegisterInstance(typeof(CompetitorContext), new CompetitorContext(settings.ConnectionStrings.Web));
    _container.RegisterType<ICompetitorService, CompetitorService>();

    DependencyResolver.SetResolver(new UnityDependencyResolver(_container));
}

When calling one of the services' method that makes a call to the CompetitorContext (which inherits from DbContext) it works fine in the Core project but in the MVC project I get this error:

System.TypeInitializationException
  HResult=0x80131534
  Message=The type initializer for 'Bid' threw an exception.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

  This exception was originally thrown at this call stack:
    Bid.internalInitialize()
    Bid.Bid()

Inner Exception 1:
EntryPointNotFoundException: Unable to find an entry point named 'DllBidEntryPoint' in DLL 'System.Data.dll'.

Other services that do not use EntityFrameWorkCore works fine, so I think the issue is with using EntityFrameWorkCore together with an .NET MVC 4.6.2 project but I'm not sure.

What might the issue to this exception be or how can I found out more information?

Edited:
The CompetitorService:

public class CompetitorService : ICompetitorService
    {
        private readonly CompetitorContext _ctx;

        public CompetitorService(CompetitorContext ctx)
        {
            _ctx = ctx;
        }

        public IList<CompetitorModel> GetAll()
        {
           return _ctx.Competitors.OrderBy(c => c.ID).ToList();
        }

        public CompetitorModel GetById(int id)
        {
            return this.GetAll().Where(c => c.ID == id).First();
        }

        public CompetitorModel GetByCompetitorKey(string competitorKey)
        {
            return this.GetAll().Where(c => c.CompetitorKey == competitorKey).FirstOrDefault();
        }
    }

The CompetitorContext:

public class CompetitorContext : DbContext
    {
        public DbSet<CompetitorModel> Competitors { get; set; }

        public CompetitorContext(string connectionString) :
            base(SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options)
        {
        }
    }

The CompetitorModel:

[Table("vw_competitors")]
    public class CompetitorModel
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ID { get; set; }
        public string CompetitorKey { get; set; }
        public string Name { get; set; }
        public string ShortName { get; set; }
        public string Experience { get; set; }
        public string BBB_Rating { get; set; }
        public string BBB_URL { get; set; }
        public string BBB_Complaints { get; set; }
        public string BBB_Accredited { get; set; }
        public string TrustPilot_URL { get; set; }
        public string TrustPilot_Rating { get; set; }
        public string TrustPilot_Reviews { get; set; }
        public string RipoffReport_Complaints { get; set; }
        public string MoneyBackGuarantee { get; set; }
        public DateTime LastUpdated { get; set; }
    }

Note: The referenced Bid class is not a data model of mine nor do I have any knowledge of it


问:
How do I update the PATH in bash_profile on OSX
I'm trying to install flutter on my Mac, in order to do so I need to add a path to the .bash_profile. But when I run the command vim .bash_profile in the terminal ,I'm met with the following message.

```<code># The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH

export M2_HOME=/Applications/apache-maven-3.6.3
export PATH=$PATH:$M2_HOME/bin# added by Anaconda3 2019.10 installer
# >>> conda init >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$(CONDA_REPORT_ERRORS=false '/Users/sofie-amaliepetersen/opt/anaconda3/bin/conda' shell.bash hook 2> /dev/null)"
if [ $? -eq 0 ]; then
    \eval "$__conda_setup"
else
    if [ -f "/Users/sofie-amaliepetersen/opt/anaconda3/etc/profile.d/conda.sh" ]; then
        . "/Users/sofie-amaliepetersen/opt/anaconda3/etc/profile.d/conda.sh"
        CONDA_CHANGEPS1=false conda activate base
    else
        \export PATH="/Users/sofie-amaliepetersen/opt/anaconda3/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda init <<<
</code>```

This is my first time adding a PATH, I've tried looking at setting path in terminal
But I'm not sure how it applies to my problem.

Any suggestions would be appreciated. Thanks

答:
Anywhere in your .bash_profile, add this line

```<code>export PATH=$PATH:/your/new/path/to/add
</code>```

This simply add /your/new/path/to/add to your existing $PATH

Body:
I'm trying to install flutter on my Mac, in order to do so I need to add a path to the .bash_profile. But when I run the command vim .bash_profile in the terminal ,I'm met with the following message.

# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH

export M2_HOME=/Applications/apache-maven-3.6.3
export PATH=$PATH:$M2_HOME/bin# added by Anaconda3 2019.10 installer
# >>> conda init >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$(CONDA_REPORT_ERRORS=false '/Users/sofie-amaliepetersen/opt/anaconda3/bin/conda' shell.bash hook 2> /dev/null)"
if [ $? -eq 0 ]; then
    \eval "$__conda_setup"
else
    if [ -f "/Users/sofie-amaliepetersen/opt/anaconda3/etc/profile.d/conda.sh" ]; then
        . "/Users/sofie-amaliepetersen/opt/anaconda3/etc/profile.d/conda.sh"
        CONDA_CHANGEPS1=false conda activate base
    else
        \export PATH="/Users/sofie-amaliepetersen/opt/anaconda3/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda init <<<

This is my first time adding a PATH, I've tried looking at setting path in terminal
But I'm not sure how it applies to my problem.

Any suggestions would be appreciated. Thanks

Body:
Anywhere in your .bash_profile, add this line

export PATH=$PATH:/your/new/path/to/add

This simply add /your/new/path/to/add to your existing $PATH


问:
Difference between InnoDB and MyISAM?

Possible Duplicate:

  MyISAM versus InnoDB

Ok I read this information of Wikipedia and InnoDB seems better. Here is my question would it be OK to use InnoDB instead of MyISAM for selecting user data from the database? Or would it be better to stay with MyISAM for this.

And if I would to change to Inno would PDO still work with it and some old style query's?

```<code>$q = ("SELECT * ... );
$r = mysql_query($q);
</code>```

答: The biggest advantage of innodb over myisam is that innodb supports transactions/rollbacks. myisam will provide better performance overall, as it does not incur the same overhead. For a simple user table you might be best to stick with myisam.</p>

Title: Difference between InnoDB and MyISAM?

Body:
Possible Duplicate:

  MyISAM versus InnoDB

Ok I read this information of Wikipedia and InnoDB seems better. Here is my question would it be OK to use InnoDB instead of MyISAM for selecting user data from the database? Or would it be better to stay with MyISAM for this.

And if I would to change to Inno would PDO still work with it and some old style query's?

$q = ("SELECT * ... );
$r = mysql_query($q);


问:
Uninstall Chrome silently using Powershell
I have the following PowerShell script, which I am using to get the uninstall string for Google Chrome, and then I want to uninstall it silently. Line 3 in the script will pop up the GUI uninstaller (so it seems like everything is correct thus far), but if I add "/qn" or "/quiet" to the argument list, the uninstall doesn't seem to run at all, even if I let it sit for a couple hours.

What am I missing?

```<code>    $AppName = "Google Chrome"
    $Chrome = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object {$_.DisplayName -match $($AppName)}
    Start-Process -Wait -FilePath MsiExec.exe -Argumentlist "/X",$Chrome.UninstallString.TrimStart("MsiExec.exe /X")
</code>```

答:
instead of trying to use /X and remove /X and other things, try the following

```<code># Get the key to uninstall
$chromeUninstall = $Chrome.Pspath.Split("\")[-1]

Start-Process -Wait -FilePath MsiExec.exe -Argumentlist "/X $ChromeUninstall /quiet /norestart"
</code>```

or even simpler would be,

```<code>Start-Process -Wait cmd.exe -ArgumentList "/c msiexec /X $ChromeUninstall /quiet /norestart"
</code>```

/c - Carries out the command specified by string and then terminates

Note

On my system I get two uninstall strings. You might want to think about looping or selecting first one in the list with the use of [0]

Body:
I have the following PowerShell script, which I am using to get the uninstall string for Google Chrome, and then I want to uninstall it silently. Line 3 in the script will pop up the GUI uninstaller (so it seems like everything is correct thus far), but if I add "/qn" or "/quiet" to the argument list, the uninstall doesn't seem to run at all, even if I let it sit for a couple hours.

What am I missing?

    $AppName = "Google Chrome"
    $Chrome = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object {$_.DisplayName -match $($AppName)}
    Start-Process -Wait -FilePath MsiExec.exe -Argumentlist "/X",$Chrome.UninstallString.TrimStart("MsiExec.exe /X")

Body:
instead of trying to use /X and remove /X and other things, try the following

# Get the key to uninstall
$chromeUninstall = $Chrome.Pspath.Split("\")[-1]

Start-Process -Wait -FilePath MsiExec.exe -Argumentlist "/X $ChromeUninstall /quiet /norestart"

or even simpler would be,

Start-Process -Wait cmd.exe -ArgumentList "/c msiexec /X $ChromeUninstall /quiet /norestart"

/c - Carries out the command specified by string and then terminates

Note

On my system I get two uninstall strings. You might want to think about looping or selecting first one in the list with the use of [0]


问:
How can I use gitlab CI/CD variables to change in docker-compose.yml
I have been trying to understand this process of having an docker-compse.yml file that I can re-use for many production with diffrent hosts, sql password and user and so on.

I've been trying out on this file fx.

```<code>
services:
 db_node_domain:
   image: mysql:5.7
   volumes:
     - db_data:/var/lib/mysql
   restart: always
   environment:
     MYSQL_ROOT_PASSWORD: PASSWORD
     MYSQL_DATABASE: wordpress
     MYSQL_USER: wordpress
     MYSQL_PASSWORD: PASSWORD
   container_name: wordpress_db

 wordpress:
   depends_on:
     - db_node_domain
   image: wordpress:latest
   expose:
     - 80:80
   restart: always
   environment:
     VIRTUAL_HOST: sub.domain.example
     WORDPRESS_DB_HOST: db_node_domain:3306
     WORDPRESS_DB_USER: wordpress
     WORDPRESS_DB_PASSWORD: $TEST
   container_name: wordpress
volumes:
   db_data:

networks:
 default:
   external:
     name: nginx-proxy
</code>```

And then I've tried to use varibales in gitlab to change the WORDPRESS_DB_PASSWORD in many ways. This is just one example of trying.

I also tried to use sed -i in .gitlab-ci.yml to change password but I wanted to know if someone could help me out on how to do this.

Thx

答:
You just need to replace hardcoded creds with environment variables.

Then each stages will have creds/settings.

In Gitlab go your project, then Settings > "CI / CD" > Variables.

Then populate each ENV variable needed, hey will be present on each run

```<code>services:
 db_node_domain:
   image: mysql:5.7
   volumes:
     - db_data:/var/lib/mysql
   restart: always
   environment:
     MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
     MYSQL_DATABASE: ${MYSQL_DATABASE}
     MYSQL_USER: ${MYSQL_USER}
     MYSQL_PASSWORD: ${MYSQL_PASSWORD}
   container_name: wordpress_db

 wordpress:
   depends_on:
     - db_node_domain
   image: wordpress:latest
   expose:
     - 80:80
   restart: always
   environment:
     VIRTUAL_HOST: ${VIRTUAL_HOST}
     WORDPRESS_DB_HOST: ${WORDPRESS_DB_HOST}
     WORDPRESS_DB_USER: ${WORDPRESS_DB_USER}
     WORDPRESS_DB_PASSWORD: ${WORDPRESS_DB_PASSWORD}
   container_name: wordpress
volumes:
   db_data:

networks:
 default:
   external:
     name: nginx-proxy
</code>```

Body:
I have been trying to understand this process of having an docker-compse.yml file that I can re-use for many production with diffrent hosts, sql password and user and so on.

I've been trying out on this file fx.

services:
 db_node_domain:
   image: mysql:5.7
   volumes:
     - db_data:/var/lib/mysql
   restart: always
   environment:
     MYSQL_ROOT_PASSWORD: PASSWORD
     MYSQL_DATABASE: wordpress
     MYSQL_USER: wordpress
     MYSQL_PASSWORD: PASSWORD
   container_name: wordpress_db

 wordpress:
   depends_on:
     - db_node_domain
   image: wordpress:latest
   expose:
     - 80:80
   restart: always
   environment:
     VIRTUAL_HOST: sub.domain.example
     WORDPRESS_DB_HOST: db_node_domain:3306
     WORDPRESS_DB_USER: wordpress
     WORDPRESS_DB_PASSWORD: $TEST
   container_name: wordpress
volumes:
   db_data:

networks:
 default:
   external:
     name: nginx-proxy

And then I've tried to use varibales in gitlab to change the WORDPRESS_DB_PASSWORD in many ways. This is just one example of trying.

I also tried to use sed -i in .gitlab-ci.yml to change password but I wanted to know if someone could help me out on how to do this.

Thx

Body:
You just need to replace hardcoded creds with environment variables.

Then each stages will have creds/settings.

In Gitlab go your project, then Settings > "CI / CD" > Variables.

Then populate each ENV variable needed, hey will be present on each run

services:
 db_node_domain:
   image: mysql:5.7
   volumes:
     - db_data:/var/lib/mysql
   restart: always
   environment:
     MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
     MYSQL_DATABASE: ${MYSQL_DATABASE}
     MYSQL_USER: ${MYSQL_USER}
     MYSQL_PASSWORD: ${MYSQL_PASSWORD}
   container_name: wordpress_db

 wordpress:
   depends_on:
     - db_node_domain
   image: wordpress:latest
   expose:
     - 80:80
   restart: always
   environment:
     VIRTUAL_HOST: ${VIRTUAL_HOST}
     WORDPRESS_DB_HOST: ${WORDPRESS_DB_HOST}
     WORDPRESS_DB_USER: ${WORDPRESS_DB_USER}
     WORDPRESS_DB_PASSWORD: ${WORDPRESS_DB_PASSWORD}
   container_name: wordpress
volumes:
   db_data:

networks:
 default:
   external:
     name: nginx-proxy


问:
Writing values as an arbitrary amount of bits into a byte buffer in C++
Hey, I need to pack bit values into a byte buffer in C++.  My Buffer class has a char array and a position, similar to Java's ByteBuffer.  I need a good way to pack bits into this buffer, like so:

```<code>void put_bits(int amount, uint32_t value);
</code>```

It needs to support up to 32 bits.  I've seen a solution implemented in Java (that requires start/end access methods before bits can be packed) but I'm not sure how to do this in C++ because the endianness and other low level factors aren't hidden like they are in Java.

I have an inline function declared as endianness() which returns 0 (defined as BIG_ENDIAN) or 1 (defined as LITTLE_ENDIAN) that can be used, but I'm just not sure how to properly pack bits into a byte buffer.

This is the Java version of what I need to implement:

```<code>public void writeBits(int numBits, int value) {
    int bytePos = bitPosition >> 3;
    int bitOffset = 8 - (bitPosition & 7);
    bitPosition += numBits;

    for(; numBits > bitOffset; bitOffset = 8) {
        buffer[bytePos] &= ~ bitMaskOut[bitOffset];
        buffer[bytePos++] |= (value >> (numBits-bitOffset)) & bitMaskOut[bitOffset];

        numBits -= bitOffset;
    }
    if(numBits == bitOffset) {
        buffer[bytePos] &= ~ bitMaskOut[bitOffset];
        buffer[bytePos] |= value & bitMaskOut[bitOffset];
    }
    else {
        buffer[bytePos] &= ~ (bitMaskOut[numBits]<<(bitOffset - numBits));
        buffer[bytePos] |= (value&bitMaskOut[numBits]) << (bitOffset - numBits);
    }
}
</code>```

Which requires these two methods as well:

```<code>public void initBitAccess() {
    bitPosition = currentOffset * 8;
}

public void finishBitAccess() {
    currentOffset = (bitPosition + 7) / 8;
}
</code>```

How should I go about solving this?  Thanks.

EDIT: I also still need to be able to write normal bytes before and after writing bits.

答: Just remove all the public keywords, and I would say that you have your C++ implementation right there.

Body:
Hey, I need to pack bit values into a byte buffer in C++.  My Buffer class has a char array and a position, similar to Java's ByteBuffer.  I need a good way to pack bits into this buffer, like so:

void put_bits(int amount, uint32_t value);

It needs to support up to 32 bits.  I've seen a solution implemented in Java (that requires start/end access methods before bits can be packed) but I'm not sure how to do this in C++ because the endianness and other low level factors aren't hidden like they are in Java.

I have an inline function declared as endianness() which returns 0 (defined as BIG_ENDIAN) or 1 (defined as LITTLE_ENDIAN) that can be used, but I'm just not sure how to properly pack bits into a byte buffer.

This is the Java version of what I need to implement:

public void writeBits(int numBits, int value) {
    int bytePos = bitPosition >> 3;
    int bitOffset = 8 - (bitPosition & 7);
    bitPosition += numBits;

    for(; numBits > bitOffset; bitOffset = 8) {
        buffer[bytePos] &= ~ bitMaskOut[bitOffset];
        buffer[bytePos++] |= (value >> (numBits-bitOffset)) & bitMaskOut[bitOffset];

        numBits -= bitOffset;
    }
    if(numBits == bitOffset) {
        buffer[bytePos] &= ~ bitMaskOut[bitOffset];
        buffer[bytePos] |= value & bitMaskOut[bitOffset];
    }
    else {
        buffer[bytePos] &= ~ (bitMaskOut[numBits]<<(bitOffset - numBits));
        buffer[bytePos] |= (value&bitMaskOut[numBits]) << (bitOffset - numBits);
    }
}

Which requires these two methods as well:

public void initBitAccess() {
    bitPosition = currentOffset * 8;
}

public void finishBitAccess() {
    currentOffset = (bitPosition + 7) / 8;
}

How should I go about solving this?  Thanks.

EDIT: I also still need to be able to write normal bytes before and after writing bits.


问:
Fill the body of request in Postman
The body of request are decoded into my own go struct.

```<code>// The go struct.
type NewUser struct {
    User            string   `json:"user" validate:"required"`
    Password        string   `json:"password" validate:"required"`
    PasswordConfirm string   `json:"password_confirm" validate:"eqfield=Password"`
}

---

// the web request with body will be decoded into this struct.
var nu NewUser
if err := web.Decode(r, &nu); err != nil {
    return errors.Wrap(err, "")
}
</code>```

How should I pass this body into postman.

答:
Your question is not eligible for StackOverflow rules.

it's elementary lack of desktop user experience.

Title: Fill the body of request in Postman

Body:
The body of request are decoded into my own go struct.

// The go struct.
type NewUser struct {
    User            string   `json:"user" validate:"required"`
    Password        string   `json:"password" validate:"required"`
    PasswordConfirm string   `json:"password_confirm" validate:"eqfield=Password"`
}

---

// the web request with body will be decoded into this struct.
var nu NewUser
if err := web.Decode(r, &nu); err != nil {
    return errors.Wrap(err, "")
}

How should I pass this body into postman.


问:
Cannot connect to local postgresql DB using DBeaver
I'm trying to connect to a postgresql database which is in localhost:5432 but I keep getting the error:
FATAL: Ident authentication failed for user "".

I installed Postgres11 on virtual machine running Centos7. Created a database through command line, with the name business_db.

I've checked and postgresql is running in localhost:5432.

My pg_hba.conf file is like this:

# TYPE  DATABASE        USER            ADDRESS                 METHOD
local   all             all                                     peer
host    all             all             127.0.0.1/32           ident
host    all             all             ::1/128                 ident
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            ident
host    replication     all             ::1/128                 ident
```

<p>The pg_ident.conf file doesn't hold any configurations:</p>

<pre class="lang-none prettyprint-override"><code># Put your actual configuration here
# ----------------------------------

# MAPNAME       SYSTEM-USERNAME         PG-USERNAME
</code>```

The database exists as shown by the command:

I'm logged into the system as "dev" user but., whatever I try while testing connection whit DBeaver, I allways get the error:

I also tried to set User as postgres and use my system password but get the same error. What am I missing?

答:
When you use JDBC, you have to use password authentication. Neither ident nor peer will work for that.

You will need to add, e.g.:

host    all             all             127.0.0.1/32           md5
```

at the top of your pb_hba.conf

(replace md5 with scram-sha-256 if you are using that)

Body:
I'm trying to connect to a postgresql database which is in localhost:5432 but I keep getting the error:
FATAL: Ident authentication failed for user "".

I installed Postgres11 on virtual machine running Centos7. Created a database through command line, with the name business_db.

I've checked and postgresql is running in localhost:5432.

My pg_hba.conf file is like this:

# TYPE  DATABASE        USER            ADDRESS                 METHOD
local   all             all                                     peer
host    all             all             127.0.0.1/32           ident
host    all             all             ::1/128                 ident
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            ident
host    replication     all             ::1/128                 ident

The pg_ident.conf file doesn't hold any configurations:

# Put your actual configuration here
# ----------------------------------

# MAPNAME       SYSTEM-USERNAME         PG-USERNAME

The database exists as shown by the command:

I'm logged into the system as "dev" user but., whatever I try while testing connection whit DBeaver, I allways get the error:

I also tried to set User as postgres and use my system password but get the same error. What am I missing?

Body:
When you use JDBC, you have to use password authentication. Neither ident nor peer will work for that.

You will need to add, e.g.:

host    all             all             127.0.0.1/32           md5

at the top of your pb_hba.conf

(replace md5 with scram-sha-256 if you are using that)


问:
Making a Python test think an installed package is not available
I have a test that makes sure a specific (helpful) error message is raised, when a required package is not available.

def foo(caller):
    try:
        import pkg
    except ImportError:
        raise ImportError(f'Install "pkg" to use {caller}')
    pkg.bar()

with pytest.raises(ImportError, match='Install "pkg" to use test_function'):
   foo('test_function')
```

However, pkg is generally available, as other tests rely on it.
Currently, I set up an additional virtual env without pkg just for this test. This seems like overkill.

Is it possible to "hide" an installed package within a module or function?

答:
I ended up with the following pytest-only solution, which appears to be more robust in the setting of a larger project.

import builtins
import pytest

@pytest.fixture
def hide_available_pkg(monkeypatch):
    import_orig = builtins.__import__

    def mocked_import(name, *args, **kwargs):
        if name == 'pkg':
            raise ImportError()
        return import_orig(name, *args, **kwargs)

    monkeypatch.setattr(builtins, '__import__', mocked_import)

@pytest.mark.usefixtures('hide_available_pkg')
def test_message():
    with pytest.raises(ImportError, match='Install "pkg" to use test_function'):
        foo('test_function')
```

Body:
I have a test that makes sure a specific (helpful) error message is raised, when a required package is not available.

def foo(caller):
    try:
        import pkg
    except ImportError:
        raise ImportError(f'Install "pkg" to use {caller}')
    pkg.bar()

with pytest.raises(ImportError, match='Install "pkg" to use test_function'):
   foo('test_function')

However, pkg is generally available, as other tests rely on it.
Currently, I set up an additional virtual env without pkg just for this test. This seems like overkill.

Is it possible to "hide" an installed package within a module or function?


问:
C++ initialization in template function - new Initializer expression list treated as compound expression
I am trying to initialize widgets of different types in a template function. But I am getting an error "new Initializer expression list treated as compound expression".

```<code>template <class T>
void setProperties(T &widget, QString input)
{
    widget = new T(input, view());
}
</code>```

Unfortunately couldn't find what is the error.

答:
```<code>new T(input, view())
</code>```

gives you a pointer, but you are trying to assign it to a reference. Change your widget to be of type T*& widget.

Body:
I am trying to initialize widgets of different types in a template function. But I am getting an error "new Initializer expression list treated as compound expression".

template <class T>
void setProperties(T &widget, QString input)
{
    widget = new T(input, view());
}

Unfortunately couldn't find what is the error.

Body:
new T(input, view())

gives you a pointer, but you are trying to assign it to a reference. Change your widget to be of type T*& widget.


问:
Template setting page for Symfony/Twig missing after PhpStorm IDE Error
I just tried to configure my Twig settings for PhpStorm, to get autocomplete and quick jumping for template files. However it seems like I entered a wrong path which killed the settings page and generated an fatal error.

Here is the PhpStorm stacktrace:

```<code>java.lang.IllegalArgumentException: Argument for @NotNull parameter 'path' of fr/adrienbrault/idea/symfony2plugin/templating/path/TwigPath.<init> must not be null
at fr.adrienbrault.idea.symfony2plugin.templating.path.TwigPath.$$$reportNull$$$0(TwigPath.java)
at fr.adrienbrault.idea.symfony2plugin.templating.path.TwigPath.<init>(TwigPath.java)
at fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil.getTwigNamespaces(TwigUtil.java:1337)
at fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil.getTemplateNamesForFile(TwigUtil.java:1242)
at fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil.getTemplatesExtendingFile(TwigUtil.java:2180)
at fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil.getTemplatesExtendingFile(TwigUtil.java:2168)
at fr.adrienbrault.idea.symfony2plugin.twig.loader.FileImplementsLazyLoader.getFiles(FileImplementsLazyLoader.java:35)
at fr.adrienbrault.idea.symfony2plugin.twig.utils.TwigBlockUtil.hasBlockImplementations(TwigBlockUtil.java:66)
at fr.adrienbrault.idea.symfony2plugin.templating.TwigLineMarkerProvider.attachBlockImplements(TwigLineMarkerProvider.java:197)
at fr.adrienbrault.idea.symfony2plugin.templating.TwigLineMarkerProvider.collectSlowLineMarkers(TwigLineMarkerProvider.java:80)
at com.intellij.codeInsight.daemon.impl.LineMarkersPass.a(LineMarkersPass.java:197)
at com.intellij.codeInsight.daemon.impl.LineMarkersPass.a(LineMarkersPass.java:96)
at com.intellij.codeInsight.daemon.impl.Divider.divideInsideAndOutsideInOneRoot(Divider.java:80)
at com.intellij.codeInsight.daemon.impl.LineMarkersPass.doCollectInformation(LineMarkersPass.java:91)
at com.intellij.codeHighlighting.TextEditorHighlightingPass.collectInformation(TextEditorHighlightingPass.java:69)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.e(PassExecutorService.java:423)
at com.intellij.openapi.application.impl.ApplicationImpl.tryRunReadAction(ApplicationImpl.java:1161)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.d(PassExecutorService.java:416)
at com.intellij.openapi.progress.impl.CoreProgressManager.a(CoreProgressManager.java:580)
at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:525)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:85)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.a(PassExecutorService.java:415)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.b(PassExecutorService.java:391)
at com.intellij.openapi.application.impl.ReadMostlyRWLock.executeByImpatientReader(ReadMostlyRWLock.java:147)
at com.intellij.openapi.application.impl.ApplicationImpl.executeByImpatientReader(ApplicationImpl.java:222)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.run(PassExecutorService.java:389)
at com.intellij.concurrency.JobLauncherImpl$VoidForkJoinTask$1.exec(JobLauncherImpl.java:161)
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
</code>```

And that's how the settings page looks:

How can I reset the settings page? I already uninstalled the Symfony plugin (which adds/remove the setting page) which had no effect, I still had the empty page on reinstall.

答:
This solution worked for me:

Open the project .idea directory in your OS file explorer

Locate the symfony2.xml file

Rename the file to something like symfony2_bkup.xml

Re-install the plugin

Restart PHPStorm

Allow the prompt to enable with auto configuration

Go to Settings > Languages & Frameworks > PHP > Symfony > Twig / Template

Should now work OK.

If you have previous settings, copy them from the backup xml file to the new one thats been generated.

UPDATE

After further debugging, it turns out if you have something like this in your xml file:

```<code><option name="twigNamespaces">
  <list>
    <twig_namespace custom="true" namespace="MyCompany" namespaceType="ADD_PATH" />
  </list>
</option>
</code>```

Then you need to add the path attribute like so:

```<code><option name="twigNamespaces">
  <list>
    <twig_namespace custom="true" namespace="MyCompany" namespaceType="ADD_PATH" path="path/to/custom/views" />
  </list>
</option>
</code>```

Once you save the xml file changes, be sure to restart PHPStorm!

Body:
I just tried to configure my Twig settings for PhpStorm, to get autocomplete and quick jumping for template files. However it seems like I entered a wrong path which killed the settings page and generated an fatal error.

Here is the PhpStorm stacktrace:

java.lang.IllegalArgumentException: Argument for @NotNull parameter 'path' of fr/adrienbrault/idea/symfony2plugin/templating/path/TwigPath.<init> must not be null
at fr.adrienbrault.idea.symfony2plugin.templating.path.TwigPath.$$$reportNull$$$0(TwigPath.java)
at fr.adrienbrault.idea.symfony2plugin.templating.path.TwigPath.<init>(TwigPath.java)
at fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil.getTwigNamespaces(TwigUtil.java:1337)
at fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil.getTemplateNamesForFile(TwigUtil.java:1242)
at fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil.getTemplatesExtendingFile(TwigUtil.java:2180)
at fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil.getTemplatesExtendingFile(TwigUtil.java:2168)
at fr.adrienbrault.idea.symfony2plugin.twig.loader.FileImplementsLazyLoader.getFiles(FileImplementsLazyLoader.java:35)
at fr.adrienbrault.idea.symfony2plugin.twig.utils.TwigBlockUtil.hasBlockImplementations(TwigBlockUtil.java:66)
at fr.adrienbrault.idea.symfony2plugin.templating.TwigLineMarkerProvider.attachBlockImplements(TwigLineMarkerProvider.java:197)
at fr.adrienbrault.idea.symfony2plugin.templating.TwigLineMarkerProvider.collectSlowLineMarkers(TwigLineMarkerProvider.java:80)
at com.intellij.codeInsight.daemon.impl.LineMarkersPass.a(LineMarkersPass.java:197)
at com.intellij.codeInsight.daemon.impl.LineMarkersPass.a(LineMarkersPass.java:96)
at com.intellij.codeInsight.daemon.impl.Divider.divideInsideAndOutsideInOneRoot(Divider.java:80)
at com.intellij.codeInsight.daemon.impl.LineMarkersPass.doCollectInformation(LineMarkersPass.java:91)
at com.intellij.codeHighlighting.TextEditorHighlightingPass.collectInformation(TextEditorHighlightingPass.java:69)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.e(PassExecutorService.java:423)
at com.intellij.openapi.application.impl.ApplicationImpl.tryRunReadAction(ApplicationImpl.java:1161)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.d(PassExecutorService.java:416)
at com.intellij.openapi.progress.impl.CoreProgressManager.a(CoreProgressManager.java:580)
at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:525)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:85)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.a(PassExecutorService.java:415)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.b(PassExecutorService.java:391)
at com.intellij.openapi.application.impl.ReadMostlyRWLock.executeByImpatientReader(ReadMostlyRWLock.java:147)
at com.intellij.openapi.application.impl.ApplicationImpl.executeByImpatientReader(ApplicationImpl.java:222)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.run(PassExecutorService.java:389)
at com.intellij.concurrency.JobLauncherImpl$VoidForkJoinTask$1.exec(JobLauncherImpl.java:161)
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)

And that's how the settings page looks:

How can I reset the settings page? I already uninstalled the Symfony plugin (which adds/remove the setting page) which had no effect, I still had the empty page on reinstall.

Body:
This solution worked for me:

Open the project .idea directory in your OS file explorer

Locate the symfony2.xml file

Rename the file to something like symfony2_bkup.xml

Re-install the plugin

Restart PHPStorm

Allow the prompt to enable with auto configuration

Go to Settings > Languages & Frameworks > PHP > Symfony > Twig / Template

Should now work OK.

If you have previous settings, copy them from the backup xml file to the new one thats been generated.

UPDATE

After further debugging, it turns out if you have something like this in your xml file:

<option name="twigNamespaces">
  <list>
    <twig_namespace custom="true" namespace="MyCompany" namespaceType="ADD_PATH" />
  </list>
</option>

Then you need to add the path attribute like so:

<option name="twigNamespaces">
  <list>
    <twig_namespace custom="true" namespace="MyCompany" namespaceType="ADD_PATH" path="path/to/custom/views" />
  </list>
</option>

Once you save the xml file changes, be sure to restart PHPStorm!


问:
Rails: Communicating between RSpec helper modules
I would be very grateful for some advice on the following.

Below I have a simplified example for our setup.

I have defined some Helper modules on our RSpec test suite:

```<code>## spec/rails_helper.rb

Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

RSpec.configure do |config|
  config.include ViewHelpers
end

### spec/support/view_helpers/base.rb

# frozen_string_literal: true

module ViewHelpers
  class Base
    # class content
  end
end

### spec/support/view_helpers/admins/payments/new.rb

# frozen_string_literal: true

module ViewHelpers
  module Admins
    module Payments
      class New < Base
        # class content
      end
    end
  end
end
</code>```

With this setup the specs run perfectly locally; the sub-class New inherits from Base as expected. However, when the tests are running on Travis CI, we get the following error:

```<code>NameError:
1433  uninitialized constant ViewHelpers::Admins::Payments::Base
1434# ./spec/support/view_helpers/admins/payments/new.rb:6:in `<module:Payments>'
1435# ./spec/support/view_helpers/admins/payments/new.rb:5:in `<module:Admins>'
1436# ./spec/support/view_helpers/admins/payments/new.rb:4:in `<module:ViewHelpers>'
1437# ./spec/support/view_helpers/admins/payments/new.rb:3:in `<top (required)>'
1438# ./spec/rails_helper.rb:34:in `block in <top (required)>'
1439# ./spec/rails_helper.rb:34:in `each'
1440# ./spec/rails_helper.rb:34:in `<top (required)>'
1441# ./spec/controllers/admins/billpayers_controller_spec.rb:3:in `<top (required)>'
</code>```

I have also tried inheriting with explicit namespacing:

```<code># frozen_string_literal: true

module ViewHelpers
  module Admins
    module Payments
      class New < ViewHelpers::Base
        # class content
      end
    end
  end
end
</code>```

Again, this runs successfully locally but Travis CI errors:

```<code>NameError:
1433  uninitialized constant ViewHelpers::Base
1434# ./spec/support/view_helpers/admins/payments/new.rb:6:in `<module:Payments>'
1435# ./spec/support/view_helpers/admins/payments/new.rb:5:in `<module:Admins>'
1436# ./spec/support/view_helpers/admins/payments/new.rb:4:in `<module:ViewHelpers>'
1437# ./spec/support/view_helpers/admins/payments/new.rb:3:in `<top (required)>'
1438# ./spec/rails_helper.rb:34:in `block in <top (required)>'
1439# ./spec/rails_helper.rb:34:in `each'
1440# ./spec/rails_helper.rb:34:in `<top (required)>'
1441# ./spec/controllers/admins/billpayers_controller_spec.rb:3:in `<top (required)>'
</code>```

I am rather stumped as to why this works locally but not on CI.
Would be very grateful for any support and insight.

Thanks
Sam

答:
Hi did you double checked your autoload configurations? (https://guides.rubyonrails.org/autoloading_and_reloading_constants.html)

Autoload and cache classes may be configured differently based on your environment configs:

```<code>├── config/environments
    ├── development.rb
    ├── production.rb
    └── test.rb
</code>```

Body:
I would be very grateful for some advice on the following.

Below I have a simplified example for our setup.

I have defined some Helper modules on our RSpec test suite:

## spec/rails_helper.rb

Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

RSpec.configure do |config|
  config.include ViewHelpers
end

### spec/support/view_helpers/base.rb

# frozen_string_literal: true

module ViewHelpers
  class Base
    # class content
  end
end

### spec/support/view_helpers/admins/payments/new.rb

# frozen_string_literal: true

module ViewHelpers
  module Admins
    module Payments
      class New < Base
        # class content
      end
    end
  end
end

With this setup the specs run perfectly locally; the sub-class New inherits from Base as expected. However, when the tests are running on Travis CI, we get the following error:

NameError:
1433  uninitialized constant ViewHelpers::Admins::Payments::Base
1434# ./spec/support/view_helpers/admins/payments/new.rb:6:in `<module:Payments>'
1435# ./spec/support/view_helpers/admins/payments/new.rb:5:in `<module:Admins>'
1436# ./spec/support/view_helpers/admins/payments/new.rb:4:in `<module:ViewHelpers>'
1437# ./spec/support/view_helpers/admins/payments/new.rb:3:in `<top (required)>'
1438# ./spec/rails_helper.rb:34:in `block in <top (required)>'
1439# ./spec/rails_helper.rb:34:in `each'
1440# ./spec/rails_helper.rb:34:in `<top (required)>'
1441# ./spec/controllers/admins/billpayers_controller_spec.rb:3:in `<top (required)>'

I have also tried inheriting with explicit namespacing:

# frozen_string_literal: true

module ViewHelpers
  module Admins
    module Payments
      class New < ViewHelpers::Base
        # class content
      end
    end
  end
end

Again, this runs successfully locally but Travis CI errors:

NameError:
1433  uninitialized constant ViewHelpers::Base
1434# ./spec/support/view_helpers/admins/payments/new.rb:6:in `<module:Payments>'
1435# ./spec/support/view_helpers/admins/payments/new.rb:5:in `<module:Admins>'
1436# ./spec/support/view_helpers/admins/payments/new.rb:4:in `<module:ViewHelpers>'
1437# ./spec/support/view_helpers/admins/payments/new.rb:3:in `<top (required)>'
1438# ./spec/rails_helper.rb:34:in `block in <top (required)>'
1439# ./spec/rails_helper.rb:34:in `each'
1440# ./spec/rails_helper.rb:34:in `<top (required)>'
1441# ./spec/controllers/admins/billpayers_controller_spec.rb:3:in `<top (required)>'

I am rather stumped as to why this works locally but not on CI.
Would be very grateful for any support and insight.

Thanks
Sam

Body:
Hi did you double checked your autoload configurations? (https://guides.rubyonrails.org/autoloading_and_reloading_constants.html)

Autoload and cache classes may be configured differently based on your environment configs:

├── config/environments
    ├── development.rb
    ├── production.rb
    └── test.rb


问:
Missing Values in a Time Period Difference Measurement
I have some time stamp data:

```<code>df = pd.DataFrame({'t' : [dt.datetime(2016,1,7),float('NaN'),dt.datetime(2016,1,8),float('NaN')],
                   'A' : [0,1,1,1]})
</code>```

Some of my t values are NaT. I would like to change A to make it zero on rows with a NaT please, like this:

I tried:

```<code># Missing values of time
def MVOT(t,A):
    if math.isnan(t):
        return 0
    else:
        return A
MVOT = np.vectorize(MVOT,otypes=[float])
df["A"] = MVOT(df['t'],df['A'])
</code>```

but I got:

```<code>TypeError: must be real number, not NoneType
</code>```

答:
Convert the time to a number

```<code>df['t'] = pd.to_numeric(df.t)
</code>```

the NaT values are converted to negative numbers so:

```<code>df.loc[df.t < 0,'A'] = 0
</code>```

Body:
I have some time stamp data:

df = pd.DataFrame({'t' : [dt.datetime(2016,1,7),float('NaN'),dt.datetime(2016,1,8),float('NaN')],
                   'A' : [0,1,1,1]})

Some of my t values are NaT. I would like to change A to make it zero on rows with a NaT please, like this:

I tried:

# Missing values of time
def MVOT(t,A):
    if math.isnan(t):
        return 0
    else:
        return A
MVOT = np.vectorize(MVOT,otypes=[float])
df["A"] = MVOT(df['t'],df['A'])

but I got:

TypeError: must be real number, not NoneType

Body:
Convert the time to a number

df['t'] = pd.to_numeric(df.t)

the NaT values are converted to negative numbers so:

df.loc[df.t < 0,'A'] = 0