text:
Q: Error with maven release process after upgrade to cloud parent My team started use spring cloud projects long time ago and we have a large number of microservices with working CI configuration. But after upgrading to the cloud parent our builds started to fail.
To configure our microservices we have an internal parent with some default configurations, dependencies and plugins. This parent was using the spring-boot-starter-parent:
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath/>
  </parent>

And for spring-cloud we had the spring-cloud BOM dependency defined:
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-dependencies</artifactId>
    <version>${spring-cloud.version}</version>
  </dependency>

We decided to use the spring-cloud-starter-parent to facilitate some dependency version management. Now we upgraded our own parent to use this parent:
  <parent>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-parent</artifactId>
    <version>Greenwich.RELEASE</version>
    <relativePath/>
  </parent>

Now our release process is getting some weird errors. Taking a single project for example (a simple one) we have this CI configured (for GitLab):
image: maven:3-jdk-8
variables:
  MAVEN_CLI_OPTS: "-s settings.xml --batch-mode --errors --show-version"

cache:
  paths:
  - .m2/repository

deploy:
  stage: deploy
  script:
    - git config --global user.name "Gitlab CI"
    - git config --global user.email "gitlab@email"
    - git checkout -B "$CI_COMMIT_REF_NAME"
    - mvn $MAVEN_CLI_OPTS clean versions:use-releases release:prepare -Dusername=$USERNAME -Dpassword=$USER_TOKEN
    - mvn $MAVEN_CLI_OPTS -Darguments="-Dmaven.test.skip=true" clean release:perform -Dusername=$USERNAME -Dpassword=$USER_TOKEN
    - mvn $MAVEN_CLI_OPTS build-helper:remove-project-artifact

We use this configuration of maven-release-plugin:
  <plugin>
    <artifactId>maven-release-plugin</artifactId>
    <version>2.5.3</version>
    <configuration>
      <tagNameFormat>v@{project.version}</tagNameFormat>
      <tagBase>${git-link}/tags</tagBase>
    </configuration>
  </plugin>

After starting a CI pipeline, our build finished with this error:
    149809 [INFO] 144003 [INFO] --- maven-site-plugin:3.7.1:deploy (default-deploy) @ service-utilities-parent ---
    149820 [INFO] 144014 [ERROR]
    149820 [INFO] Unsupported protocol: 'scp' for site deployment to distributionManagement.site.url=scp://static.springframework.org/var/www/domains/springframework.org/static/htdocs/spring-cloud/docs/spring-cloud-starter-parent/Greenwich.RELEASE.
    149821 [INFO] Currently supported protocols are: http, https, file.
    149821 [INFO]     Protocols may be added through wagon providers.
    149821 [INFO]     For more information, see http://maven.apache.org/plugins/maven-site-plugin/examples/adding-deploy-protocol.html

I really have no clue of what is going on, since I have no maven-site-plugin defined and the spring-cloud-starter-parent should declare plugins only on pluginsManagement section.
I will be very happy if someone can explain me what I'm not seeing.
Thanks.


text:
Q: SEO friendly dynamic url in c# I search into google many times but didn't get any suitable result for that..
I have a dynamic url in c#  Something like

http://192.168.10.120:81/ImgDetails.aspx?id=5702&icod=100-106083

Title of the image is like

Man having breakfast

I want the URL like the following example
http://www.alamy.com/stock-photo-senior-man-looking-out-over-hopi-point-grand-canyon-arizona-focus-73496317.html
So can i rewrite my dynamic URL into the same please help.

A: If you are using ASP.NET version 4 or above the following might help.
https://code.msdn.microsoft.com/Easy-Steps-to-URL-2f792901

redpajama_set_name: RedPajamaStackExchange


text:
Q: Count rows by grouping and reset counter on new group with datatable and R I need to count the number of rows per data pool that a datatable gets. These require that the week column "week" and "Exist" must be filled in.
I have the following data:
week_2020 <- seq(202001, 202015, 1)
week_2021 <- seq(202101, 202110, 1)

Exist <- c("TRUE","TRUE","TRUE","TRUE","TRUE","TRUE","TRUE","TRUE",
           NA,NA,NA,
           "TRUE","TRUE",NA,NA,"TRUE","TRUE","TRUE","TRUE",
           NA,NA,NA,
           "TRUE",NA, NA)

Year <- c(rep(2020,15),rep(2021,10) )

df<-data.table(Store = "store_1", Client = "client_1",
               Year = Year,
               week = c(week_2020, week_2021),
               Exist = Exist)

Store
Client
Year
Week
Exist

Store 1
Client 1
2020
202001
TRUE

Store 1
Client 1
2020
202002
TRUE

Store 1
Client 1
2020
202003
TRUE

Store 1
Client 1
2020
202004
TRUE

Store 1
Client 1
2020
202005
TRUE

Store 1
Client 1
2020
202006
TRUE

Store 1
Client 1
2020
202007
TRUE

Store 1
Client 1
2020
202008
TRUE

Store 1
Client 1
2020
202009
NA

Store 1
Client 1
2020
202010
NA

Store 1
Client 1
2020
202011
NA

Store 1
Client 1
2020
202012
TRUE

Store 1
Client 1
2020
202013
TRUE

Store 1
Client 1
2020
202014
NA

Store 1
Client 1
2020
202015
NA

Store 1
Client 1
2021
202101
TRUE

Store 1
Client 1
2021
202102
TRUE

Store 1
Client 1
2021
202103
TRUE

Store 1
Client 1
2021
202104
TRUE

Store 1
Client 1
2021
202105
NA

Store 1
Client 1
2021
202106
NA

Store 1
Client 1
2021
202107
NA

Store 1
Client 1
2021
202108
TRUE

Store 1
Client 1
2021
202109
NA

Store 1
Client 1
2021
202110
NA

As shown in the table, some data in the "Exist" column is NA, which means that it does not exist, but that grouping should be counted as well.
I have created a variable that helps me to count the weeks until I find the lost weeks, and then I should count them and reset the counter, and another that does the max count "n_week_Count" but I can't do what I need. I hope you can help me to solve this problem. Thanks in advice
This is what i have...
df[, ':=' (n_weekCount = 1:.SD[,(.N)] ), keyby = c("Store", "Client", "Year", "Exist")
   ][, ':=' (MaxweekCount = .SD[, max(n_weekCount)]), keyby = c("Store", "Client", "Year", "Exist")
][order(week)]

Store
Client
Year
Week
Exist
n_weekCount
maxWeek_Count

Store 1
Client 1
2020
202001
TRUE
1
10

Store 1
Client 1
2020
202002
TRUE
2
10

Store 1
Client 1
2020
202003
TRUE
3
10

Store 1
Client 1
2020
202004
TRUE
4
10

Store 1
Client 1
2020
202005
TRUE
5
10

Store 1
Client 1
2020
202006
TRUE
6
10

Store 1
Client 1
2020
202007
TRUE
7
10

Store 1
Client 1
2020
202008
TRUE
8
10

Store 1
Client 1
2020
202009
NA
1
5

Store 1
Client 1
2020
202010
NA
2
5

Store 1
Client 1
2020
202011
NA
3
5

Store 1
Client 1
2020
202012
TRUE
9
10

Store 1
Client 1
2020
202013
TRUE
10
10

Store 1
Client 1
2020
202014
NA
4
5

Store 1
Client 1
2020
202015
NA
5
5

Store 1
Client 1
2021
202101
TRUE
1
10

Store 1
Client 1
2021
202102
TRUE
2
10

Store 1
Client 1
2021
202103
TRUE
3
10

Store 1
Client 1
2021
202104
TRUE
4
10

Store 1
Client 1
2021
202105
NA
1
5

Store 1
Client 1
2021
202106
NA
2
5

Store 1
Client 1
2021
202107
NA
3
5

Store 1
Client 1
2021
202108
TRUE
1
10

Store 1
Client 1
2021
202109
NA
4
5

Store 1
Client 1
2021
202110
NA
5
5

The desired result would be:

Store
Client
Year
Week
Exist
n_weekCount
maxWeek_Count

Store 1
Client 1
2020
202001
TRUE
1
8

Store 1
Client 1
2020
202002
TRUE
2
8

Store 1
Client 1
2020
202003
TRUE
3
8

Store 1
Client 1
2020
202004
TRUE
4
8

Store 1
Client 1
2020
202005
TRUE
5
8

Store 1
Client 1
2020
202006
TRUE
6
8

Store 1
Client 1
2020
202007
TRUE
7
8

Store 1
Client 1
2020
202008
TRUE
8
8

Store 1
Client 1
2020
202009
NA
1
3

Store 1
Client 1
2020
202010
NA
2
3

Store 1
Client 1
2020
202011
NA
3
3

Store 1
Client 1
2020
202012
TRUE
1
2

Store 1
Client 1
2020
202013
TRUE
2
2

Store 1
Client 1
2020
202014
NA
1
2

Store 1
Client 1
2020
202015
NA
2
2

Store 1
Client 1
2021
202101
TRUE
1
4

Store 1
Client 1
2021
202102
TRUE
2
4

Store 1
Client 1
2021
202103
TRUE
3
4

Store 1
Client 1
2021
202104
TRUE
4
4

Store 1
Client 1
2021
202105
NA
1
3

Store 1
Client 1
2021
202106
NA
2
3

Store 1
Client 1
2021
202107
NA
3
3

Store 1
Client 1
2021
202108
TRUE
1
1

Store 1
Client 1
2021
202109
NA
1
2

Store 1
Client 1
2021
202110
NA
2
2

A: We may use rleid for grouping and create the columns (:=) with seq_len(.N) and group size (.N)
library(data.table)
df[, c("n_WeekCount", "maxWeek_Count") := .(seq_len(.N), .N),
      .(grp = rleid(Exist), Store, Client, Year)]

-output
> df
      Store   Client  Year   week  Exist n_WeekCount maxWeek_Count
     <char>   <char> <num>  <num> <char>       <int>         <int>
 1: store_1 client_1  2020 202001   TRUE           1             8
 2: store_1 client_1  2020 202002   TRUE           2             8
 3: store_1 client_1  2020 202003   TRUE           3             8
 4: store_1 client_1  2020 202004   TRUE           4             8
 5: store_1 client_1  2020 202005   TRUE           5             8
 6: store_1 client_1  2020 202006   TRUE           6             8
 7: store_1 client_1  2020 202007   TRUE           7             8
 8: store_1 client_1  2020 202008   TRUE           8             8
 9: store_1 client_1  2020 202009   <NA>           1             3
10: store_1 client_1  2020 202010   <NA>           2             3
11: store_1 client_1  2020 202011   <NA>           3             3
12: store_1 client_1  2020 202012   TRUE           1             2
13: store_1 client_1  2020 202013   TRUE           2             2
14: store_1 client_1  2020 202014   <NA>           1             2
15: store_1 client_1  2020 202015   <NA>           2             2
16: store_1 client_1  2021 202101   TRUE           1             4
17: store_1 client_1  2021 202102   TRUE           2             4
18: store_1 client_1  2021 202103   TRUE           3             4
19: store_1 client_1  2021 202104   TRUE           4             4
20: store_1 client_1  2021 202105   <NA>           1             3
21: store_1 client_1  2021 202106   <NA>           2             3
22: store_1 client_1  2021 202107   <NA>           3             3
23: store_1 client_1  2021 202108   TRUE           1             1
24: store_1 client_1  2021 202109   <NA>           1             2
25: store_1 client_1  2021 202110   <NA>           2             2


text:
Q: Piranha CMS - Custom block won't save Very new to Piranha and Vue, but not to .Net Core. Trying to get my arms around how to create custom blocks.  I've created a new block, attempting to marry the HtmlBlock and ImageBlock:
using Piranha.Extend;
using Piranha.Extend.Blocks;
using Piranha.Extend.Fields;

namespace YR.Models.Piranha.Blocks
{
    [BlockType(Name = "Card", Category = "Content", Icon = "fas fa-address-card", Component = "card-block")]
    public class CardBlock : Block
    {
        public ImageField ImgBody { get; set; }
        public SelectField<ImageAspect> Aspect { get; set; } = new SelectField<ImageAspect>();
        public HtmlField HtmlBody { get; set; }

        public override string GetTitle()
        {
            if (ImgBody != null && ImgBody.Media != null)
            {
                return ImgBody.Media.Filename;
            }
            return "No image selected";
        }
    }
}

If I omit the Component property in the BlockTypeAttribute, the block works, saves the image and content to draft and updates the site perfectly when published. For the full experience in the manager, I tried to also build a Vue component that just combined both the html-block.vue and image-block.vue components.
Here's what I have for the Vue component:
Vue.component("card-block", {
    props: ["uid", "toolbar", "model"],
    data: function () {
        return {
            imgBody: this.model.imgBody.value,
            htmlBody: this.model.htmlBody.value
        };
    },
    methods: {
        clear: function () {
            // clear media from block
        },
        onBlur: function (e) {
            this.model.htmlBody.value = e.target.innerHTML;
        },
        onChange: function (data) {
            this.model.htmlBody.value = data;
        },
        remove: function () {
            this.model.imgBody.id = null;
            this.model.imgBody.media = null;
        },
        select: function () {
            if (this.model.imgBody.media != null) {
                piranha.mediapicker.open(this.update, "Image", this.model.imgBody.media.folderId);
            } else {
                piranha.mediapicker.openCurrentFolder(this.update, "Image");
            }
        },
        update: function (media) {
            if (media.type === "Image") {
                this.model.imgBody.id = media.id;
                this.model.imgBody.media = media;

                // Tell parent that title has been updated
                this.$emit('update-title', {
                    uid: this.uid,
                    title: this.model.imgBody.media.filename
                });
            } else {
                console.log("No image was selected");
            }
        }
    },
    computed: {
        isEmpty: function () {
            return {
                htmlBody: piranha.utils.isEmptyHtml(this.model.htmlBody.value),
                imgBody: this.model.imgBody.media == null
            }
        },
        mediaUrl: function () {
            if (this.model.imgBody.media != null) {
                return piranha.utils.formatUrl(this.model.imgBody.media.publicUrl);
            } else {
                return piranha.utils.formatUrl("~/manager/assets/img/empty-image.png");
            }
        }
    },
    mounted: function () {
        piranha.editor.addInline(this.uid, this.toolbar, this.onChange);
        this.model.imgBody.getTitle = function () {
            if (this.model.imgBody.media != null) {
                return this.model.imgBody.media.filename;
            } else {
                return "No image selected";
            }
        };
    },
    beforeDestroy: function () {
        piranha.editor.remove(this.uid);
    },
    template:
        "
" +
        "   " +
        "
" +
        "
" +
        "        <button :id='uid' class='btn btn-info btn-aspect text-center' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>" +
        "            " +
        "            " +
        "        </button>" +
        "
" +
        "            {{ piranha.resources.texts.aspectLabel }}" +
        "

" +
        "            " +
        "                {{ piranha.resources.texts.aspectOriginal }}" +
        "            " +
        "           " +
        "                {{ piranha.resources.texts.aspectOriginal }}" +
        "            " +
        "           " +
        "                {{ piranha.resources.texts.aspectOriginal }}" +
        "            " +
        "           " +
        "                {{ piranha.resources.texts.aspectOriginal }}" +
        "            " +
        "           " +
        "                {{ piranha.resources.texts.aspectOriginal }}" +
        "            " +
        "
" +
        "        <button v-on:click.prevent='select' class='btn btn-primary text-center'>" +
        "            " +
        "        </button>" +
        "        <button v-on:click.prevent='remove' class='btn btn-danger text-center'>" +
        "            " +
        "         </button>" +
        "
" +
        "
" +
        "
" +
        "             " +
        "
" +
        "
" +
        "            {{ model.body.media.filename }}" +
        "
" +
        "
" +
        "
" +
        "

" +
        "
"
});

It's basically a meld of the two Vue components that I found in the repo on GitHub, but I've massaged it a little to get it to not spit out errors in the DevTools console.  I'll revisit those items if I can just get past saving it.
So, here are my questions for @tidyui or anyone who's successfully implemented something like this:

*

*Am I going about this the right way?  I simply want three columns, each column would contain my CardBlock which has a picture and a blurb of content under it, but I want the CardBlock to be a single unit (kind of like a Bootstrap Card). Is there already a way to do this without creating my own block?  I researched nesting BlockGroups, but quickly found out that it isn't possible.

*If I'm on the right track, I need help with the error I'm getting when I attempt to save the draft. The error is identical to Save ImageBlock error #1117, which appears to have been fixed in 8.2.  I'm on 8.4.2.
I absolutely LOVE the idea of a CMS built for .Net Core, and Piranha blows away the CMS I created for myself. I just need a little push in the right direction, please, I've been at this for most of the day.
Thanks in advance,
D

A: Just in case this helps someone. Turns out I did a poor job merging the two blocks together. Chalk this one up to inexperience with both Piranha and Vue.js. I was mixing the code from the docs with the code in the repo.  Don't do that - the docs are understandably still a bit behind.  I'm not throwing stones at the developers, I really dig what they've created and will continue to put forth the effort to use it proficiently.
Below is what I came up with for the Vue component. There are probably still a few tweaks to be made to separate the Image-Block and Html-Block code better, but it now works, saves, and does not throw errors in the console.
/*global
    piranha
*/

Vue.component("card-block", {
    props: ["uid", "toolbar", "model"],
    data: function () {
        return {
            imgBody: this.model.imgBody.value,
            htmlBody: this.model.htmlBody.value
        };
    },
    methods: {
        clear: function () {
            // clear media from block
        },
        onBlur: function (e) {
            this.model.htmlBody.value = e.target.innerHTML;
        },
        onChange: function (data) {
            this.model.htmlBody.value = data;
        },
        select: function () {
            if (this.model.imgBody.media != null) {
                piranha.mediapicker.open(this.update, "Image", this.model.imgBody.media.folderId);
            } else {
                piranha.mediapicker.openCurrentFolder(this.update, "Image");
            }
        },
        remove: function () {
            this.model.imgBody.id = null;
            this.model.imgBody.media = null;
        },
        update: function (media) {
            if (media.type === "Image") {
                this.model.imgBody.id = media.id;
                this.model.imgBody.media = {
                    id: media.id,
                    folderId: media.folderId,
                    type: media.type,
                    filename: media.filename,
                    contentType: media.contentType,
                    publicUrl: media.publicUrl,
                };
                // Tell parent that title has been updated
                this.$emit('update-title', {
                    uid: this.uid,
                    title: this.model.imgBody.media.filename
                });
            } else {
                console.log("No image was selected");
            }
        },
        selectAspect: function (val) {
            this.model.aspect.value = val;
        },
        isAspectSelected(val) {
            return this.model.aspect.value === val;
        }
    },
    computed: {
        isImgEmpty: function (e) {
            return this.model.imgBody.media == null;
        },
        isHtmlEmpty: function () {
            return piranha.utils.isEmptyHtml(this.model.htmlBody.value);
        },
        mediaUrl: function () {
            if (this.model.imgBody.media != null) {
                return piranha.utils.formatUrl(this.model.imgBody.media.publicUrl);
            } else {
                return piranha.utils.formatUrl("~/manager/assets/img/empty-image.png");
            }
        },
        iconUrl: function () {
            if (this.model.aspect.value > 0) {
                if (this.model.aspect.value === 1 || this.model.aspect.value === 3) {
                    return piranha.utils.formatUrl("~/manager/assets/img/icons/img-landscape.svg");
                } else if (this.model.aspect.value == 2) {
                    return piranha.utils.formatUrl("~/manager/assets/img/icons/img-portrait.svg");
                } else if (this.model.aspect.value == 4) {
                    return piranha.utils.formatUrl("~/manager/assets/img/icons/img-square.svg");
                }
            }
            return null;
        }
    },
    mounted: function () {
        piranha.editor.addInline(this.uid, this.toolbar, this.onChange);
        this.model.getTitle = function () {
            if (this.model.imgBody.media != null) {
                return this.model.imgBody.media.filename;
            } else {
                return "No image selected";
            }
        };
    },
    beforeDestroy: function () {
        piranha.editor.remove(this.uid);
    },
    template:

        "
" +
        "
" +
        "       " +
        "
" +
        "
" +
        "               <button :id='uid + \"-aspect\"' class='btn btn-info btn-aspect text-center' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>" +
        "                " +
        "                   " +
        "               </button>" +
        "
" +
        "                   {{ piranha.resources.texts.aspectLabel }}" +
        "

" +
        "                   " +
        "                       {{ piranha.resources.texts.aspectOriginal }}" +
        "                   " +
        "                   " +
        "                       {{ piranha.resources.texts.aspectLandscape }}" +
        "                   " +
        "                   " +
        "                       {{ piranha.resources.texts.aspectPortrait }}" +
        "                   " +
        "                   " +
        "                       {{ piranha.resources.texts.aspectWidescreen }}" +
        "                   " +
        "                   " +
        "                       {{ piranha.resources.texts.aspectSquare }}" +
        "                   " +
        "
" +
        "               <button v-on:click.prevent='select' class='btn btn-primary text-center'>" +
        "                   " +
        "               </button>" +
        "               <button v-on:click.prevent='remove' class='btn btn-danger text-center'>" +
        "                   " +
        "               </button>" +
        "
" +
        "
" +
        "
" +
        "                    " +
        "
" +
        "
" +
        "                   {{ model.imgBody.media.filename }}" +
        "
" +
        "
" +
        "
" +
        "
" +
        "
" +
        "
" +
        "
" +
        "

 " +
        "
" +
        "
" +
        "
"
});

I'd still love to get some confirmation that I didn't do all of this unnecessarily. If there's a better way to have done it, please don't hold back.


text:
Q: How to find the location of a point in 3D space from projected 2D angle I have points $A,B,C$ in 3D space and I know the position of $A=(x_1, y_1, z_1)$ and $B=(x_2, y_2, z_2)$. I want to find the location for $C$ given that $AB$ and $BC$ is perpendicular in 3D space but on a 2D plane it's $63.8^{\circ}$
Is it possible to find the location of $C$ with the provided information above?


text:
Q: HMM - why we need using sub-state when use HMM for recognition I'm new Machine learning, I'm using Hidden Markov model to recognition activities.
I have 9 different activities.I'm using Jahmm library. My data collect from accelerometer sensor. The vector like[ 270.0 2280.0 390.0 202.706888932921 ] for each sample (2s/sample, 50 record/second).
The first, I using K-means to learn and save all HMM in the arrayList. Then I compare the probability between them when have new feature vector. The result is very good:
Reader reader = new FileReader("My Link file");
            List<List<ObservationVector>> sequences = ObservationSequencesReader
                    .readSequences(new ObservationVectorReader(), reader);
            reader.close();

            OpdfMultiGaussianFactory gMix = new OpdfMultiGaussianFactory(4);
            KMeansLearner kml = new KMeansLearner<>(1, gMix, sequences);

            //Hmm hmm1 = kml.iterate();
            ArrayList<Hmm> listHmm = new ArrayList<>();
            listHmm.add(kml.iterate());

But, new KMeansLearner<>(1, gMix, sequences) - this means with each state (example : walking), I have only sub state. But in the theory, each state have some state inside. My work is recognition activities, so Why i need using sub-state?
I read some project in github, most author using BaumWelchLearner to fit parameters for HMM. But when I using for my Data, I have some error with two case:
    1: if my data like :
[ 270.0 2280.0 390.0 202.706888932921 ] ;
 [ 140.0 2010.0 720.0 165.88948785066606 ] ;
 [ 950.0 1850.0 300.0 209.37353643104433 ] ;
 [ 220.0 2520.0 540.0 225.51551675635858 ] ;
 [ 90.0 1390.0 370.0 92.85073343887925 ] ;
 [ 280.0 2970.0 480.0 206.20770830791443 ] ;
 [ 340.0 1530.0 160.0 154.4395940899849 ] ;
 [ 210.0 3410.0 90.0 208.4459552027285 ] ;
 [ 270.0 1570.0 290.0 163.63963507041333 ] ;
 [ 360.0 2830.0 620.0 201.01313211023808 ] ;
 [ 320.0 1980.0 230.0 120.60316500067711 ] ;
 [ 320.0 1940.0 330.0 185.39230969622733 ] ;
 [ 310.0 2080.0 780.0 217.30981059428305 ] ;

KMeansLearner kMeansLearner = new KMeansLearner(1,gMix,sequences);
            BaumWelchLearner baumWelchLearner = new BaumWelchLearner();
            Hmm initHmm = kml.iterate();
            Hmm finalHmm = baumWelchLearner.iterate(initHmm,sequences);

I get error : Observation sequence too short because each feature vector is an observation.
2. If my data is :

[ 270.0 2280.0 390.0 202.706888932921 ] ;  [ 140.0 2010.0 720.0 165.88948785066606 ] ;  [ 950.0 1850.0 300.0 209.37353643104433 ] ; ...And more for each observation sequences
Then, the result is very bad and the probability is NA when i using ViterbiCalculator to compute them.
My question is :
1:  Why we need to use sub-state in Hidden markov model
2: Why I use BaumWelchLearner to learn, my result is very bad
Sorry about my English. Thanks very much!


text:
Q: How to simulate sandbox "pre-installed by policy" extension I'm developing an extension and I'm trying to use the enterprise.deviceAttributes API, but "This API is only for extensions pre-installed by policy.". How can I simulate a pre-installed by policy extension in sandbox so I can develop it?
Also, I noticed that this API is not "dev channel only" anymore, so now I can use it in production?
Question about Google Admin:
I will require the users to install my extension to their "children"* via Google Admin > Chrome Management > User Settings, so the user won't need to enroll devices, and the extension will be "installed by policy".
In this case, which devices aren't enrolled, can I still get the deviceID of the "children" with my extension and then call the Admin API to get device info?
*Children is an example, could be students, employees....

A: I found a workflow that doesn't require me to wait on approval from the Chrome Web Store, but it's a little clunky.

*This was tried on a Chromebook in developer mode. I don't know if that matters.

*Upload your extension as a draft to the Chrome Web Store

*Note the ID assigned to your draft in the Chrome Web Store developer dashboard

*In Google Admin, under Devices > Chrome > Apps & Extensions select "Add Chrome app or extension by ID"

*Put in the extension ID from the developer dashboard

*Change "From the Chrome Web Store" to "From a custom URL" and put in a junk URL

*Make sure the extension is set to "Available" and not "Forced" (if it is set to forced you won't be able to manually install the extension)

*Download the CRX file from the "package" section of your saved draft from the chrome web store and copy it to your Chromebook. Your CRX file will now be signed by the blessed Google keys

*Drag it in to the chrome://extensions page on the Chromebook to install it

*Disable the extension but do not uninstall it

*Change the extension to "forced" in Google Admin

*Go to chrome://policy and reload policies.

*If you refresh chrome://extensions you should see that the extension is now force-enabled and should be running with enterprise.deviceAttributes permissions (assuming your extension requested them)


text:
Q: DB2 LUW: how to influence query planner's choice of join Suppose I have two tables, A and B.  They "share" the same primary key, which is indexed in both tables.  Table B also has a timestamp column which is separately indexed.
I do a subselect on B using the timestamp column (I give it a 24-hour interval for the timestamp to belong to), and inner join the results against A using the primary keys.
A and B are huge (O(10^9) rows).  When I give the subselect a recent 24-hour period, it seems that the statistics are poor and the planner underestimates the number of rows coming out of the subselect (say, anywhere between O(1) and O(10^5) rows, while there are actually 6M such rows for the queries I run).  It picks a nested loop join, with the subselect output as the "outer" table and A as the "inner" table, accessed via its index.  While NL joins have a bad rep, it only takes a few minutes to complete.
When I tell it to look for older timestamps ("old" 24-hour periods), it does understand that there are about 6M rows coming out of the subselect.  It picks a hash join, with A as the outer/probe table, and the subselect output as the inner/build table.  It does a table scan on A as part of the plan.  It doesn't complete even after 48 hours.
Is there a way to force or hint to the planner that it should use the nested loop join?
While I'd be interested in hearing about DB tuning as a solution, this is a box I have no authorization to tune.
...more information:  the join switches from nested loop to hash when the number of rows returned by the subselect increases beyond about 1.012*10^6.

A: Hash joins require an "equijoin predicate".  So I rewrote the query as an explicit join (instead of IN...(subselect)), and instead of using A.key = B.key as the join condition, I used A.key > B.key - 1 AND A.key < B.key +1.


text:
Q: OCamllex syntax error When defining some identifiers in the definition section of my lexer (as described at here), i'm trying to write something of the form:
    let op_char = ['+' '-' '*' '/']
    let id_char = [^ ' ' '\r' '\n' '\t' op_char]

To define id_char as every char not being a blank char or an op_char. However, i get a syntax error on "op_char" on the second line. How should I write this? Thanks.

A: let id_char = [^ ' ' '\r' '\n' '\t'] # op_char

See manual.


text:
Q: How to save model.summary() to file in Keras? There is model.summary() method in Keras. It prints table to stdout. Is it possible to save this to file?

A: If you want the formatting of summary you can pass a print function to model.summary() and output to file that way:
def myprint(s):
    with open('modelsummary.txt','a') as f:
        print(s, file=f)

model.summary(print_fn=myprint)

Alternatively, you can serialize it to a json or yaml string with model.to_json() or model.to_yaml() which can be imported back later.
Edit
An more pythonic way to do this in Python 3.4+ is to use contextlib.redirect_stdout
from contextlib import redirect_stdout

with open('modelsummary.txt', 'w') as f:
    with redirect_stdout(f):
        model.summary()

A: Here you have another option:
with open('modelsummary.txt', 'w') as f:

    model.summary(print_fn=lambda x: f.write(x + '\n'))


text:
Q: Instance of MongoDB server shut down when creating an AMI image I was trying to clone an instance of a MongoDB server on EC2. When I selected the instance, and did 'create image', it shut down our MongoDB server completely. The IP has not changed, and we are unable to connect to it. I tried to reboot the server, as well as start it and end it. The clone of the AMI has not been touched. How am I able to get the server back up?
When we try to start the server, the terminal just says 'failed.'

A: We need some more information about this to give the exact solution. Please provide how you are taking the AMI. But we can assume what might be happened.
As per AWS, the SNAPSHOT and AMI are not consistent. So to make it as a consistent, they provide an option to reboot while taking the AMI. If you are going to take the AMI from the AWS console they will be a CheckBox to prevent it.
If you are using any Lambda or CLI tools just disable the Reboot option.


text:
Q: Canonical implementation of findAndDelete using ReactiveMongo Using ReactiveMongo, what would be the canonical way to find a single document using a query, delete this document and finally return it. I am also using the ReactiveMongo plugin for the Playframework. So far, I have come up with the following snippet:
def removeOne(query: JsObject)(implicit collection: JSONCollection): Future[Option[MyModel]] = {
  collection.remove(query, firstMatchOnly = true).map(result => result match {
    case success if result.ok => ???
    case failure => throw new RuntimeException(failure.message)
  })
}

The key question is a) Does the LastError contain the single document and b) how can it be transformed to an Option of MyModel class.

A: There is no shortcut for "find and remove" in reactivemongo, like there is for the crud operations etc, but I think you can do it using the db.commands method and the FindAndModify like this:
 val db: DefaultDB = ???
 import reactivemongo.core.commands._
 db.command(
   FindAndModify("collection",
     query = BSONDocument("something" -> "somevalue"),
     modify = Remove
   )
 ).map(maybeDoc =>
   maybeDoc.map(BSON.readDocument[SomeType])
 )

BSON.readDocument implicitly takes reader that can parse SomeType out of BSON. The result of the operation and then map will be a Future[Option[SomeType]]


text:
Q: Existe diferença em "ligar-se" ao container via docker attach ou docker exec? Minha dúvida é: existe diferença em "ligar-se" a um container utilizando a instrução docker attach e docker exec -it container /bin/bash?
Meu container foi criado desta forma:
docker run -it -p 80:80 --name dev debian:stretch /bin/bash
Cheguei a ler alguns posts quanto ao assunto, pelo que pude entender, docker attach é uma instrução utilizada para conectar ao container sem abrir um novo processo, ou seja, ele conecta ao Shell instanciado no momento da criação do container.
Caso eu execute: docker exec -it container /bin/bash estarei criando um novo processo.
Como docker é um mundo razoavelmente novo para mim, não tenho certeza se este entendimento está correto.

A: O docker exec é utilizado para enviar um comando para o container em questão, quando você faz docker exec -it container /bin/bashé enviada uma instrução para o container abrir um processo do bash e mantê-lo aberto até que feche. Olhando a documentação é possível entender melhor essa questão.
Enquanto que o docker attach anexa o stdio do container ao seu terminal, é como se você usasse um ssh, isso está escrito na documentação.
Em todo caso, se você quer visualizar os logs de um container use o docker logs. Se você quiser rodar um comando no container, crie um dockerfile, pois a ideia do container é ser reutilizável e se você fizer o comando com o container rodando, quando reiniciá-lo (possivelmente acontecerá), precisará fazer o comando de novo.


text:
Q: How can I detect support for iframe onload without browser sniffing? I have a website where users can download a formatted PDF document or Excel file of records. To do this without a postback I programmatically create an iframe and set the source to a URL containing an id and a key to identify the data required. A spinner is displayed to indicate that a download is under way. Once the data has been processed by the ASP.NET handler and the iframe receives the results, the onload event is 'supposed' to hide the spinner.
showSpinner();
var i = document.createElement("iframe");
var id = 2;
var key = '1234567890abcd';
var fileType = 'pdf';
i.src = 'Download.ashx?Type=' + fileType + '&ID=' + id + '&Key=' + key;
$(i).on("load", function () { hideSpinner(); })
i.style.display = "none";
document.body.appendChild(i);

I have also tried adding the onload event without jQuery or addEventListener by embedding it directly in the iframe markup using
i.setAttribute("onload", "hideSpinner();");

Both of these approaches work fine in Firefox and Chrome, but IE and Edge don't fire the onload event in either case. I have searched and found lots of people reporting problems along similar lines. Despite trying several suggestions, it seems that IE just doesn't like this sort of thing.
As jQuery has deprecated browser detection and UserAgent sniffing is frowned upon, is there a more 'acceptable' way of disabling the spinner using feature detection, without me just using
if (/trident/i.test(navigator.userAgent)) hideSpinner();

Alternatively, and to be honest, preferably, any suggestions on how to solve the iframe problem would be gratefully received.


text:
Q: origin youtube api Failed to execute 'postMessage' on 'DOMWindow': I'm getting this error when I use the Youtube API to embed a video on Chrome:
"origin youtube api Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.youtube.com') does not match the recipient window's origin ('XXXXXXX')."
It works fine, but I get that error.
If I'm doing a simple Youtube iframe embed, I typically solve this problem by adding an origin setting to the URL. However, I don't seem to be able to do this with the API. I added an origin to the playerVars but it doesn't resolve the error.
   <script async src="https://youtube.com/iframe_api"></script>
   <script>
      function onYouTubeIframeAPIReady() {
      var player1;
      player1 = new YT.Player('YouTubePlayer', {
      videoId: 'XXXXXXXXXXXX',
      width: 1920,
      height: 1080,
      playerVars: {
      autoplay: 1,
      start: 40,
      end:640,
      controls: 0,
      showinfo: 0,
      enablejsapi: 1,
      origin: 'https://XXXXXXXXX.com',
      modestbranding: 1,
      loop: 1,
      fs: 0,
      cc_load_policy: 0,
      iv_load_policy: 3,
      autohide: 0
         },
         events: {
           onReady: function(e) {
             e.target.mute();
      player1.addEventListener('onStateChange', function(e) {

         var id = 'XXXXXXXXX';

      if(e.data === YT.PlayerState.ENDED){
        player1.loadVideoById({'videoId': id,
               'startSeconds': 40,
               'endSeconds': 640,
               'suggestedQuality': 'large'});

      };
         });
           }
         }
       });

Where should I add an origin? Or is there another way to address this problem? Thanks!


text:
Q: Django object level permission using default auto-created model permissions By default, Django adds 4 permissions for each registered model:

*

*add_modelname

*change_modelname

*delete_modelname

*view_modelname

When a user has one of these permissions it applies to all instances of that model. That's not what I want, I want per instance permission.
When the creator (created_by in database, or some related table of users with access) has delete_modelname permission he can delete only that instance, and not some other created by another user.
I've been looking at other answers and none of them mention the auto-created CRUD permissions that are created for all models, it's mostly new tables or third-party libraries.
What about giving creators of models these permissions (add, change, delete, view) which normally would give them access to all other models, but also having a custom auth backend which checks the object:
from django.contrib.auth.backends import BaseBackend

class ObjectPermissionBackend(BaseBackend):
    def has_perm(self, user_obj, perm, obj=None):
        if not obj:
            return False
        return obj.created_by == user_obj.pk # or something like this

And then using it:
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend', 'path.to.ObjectPermissionBackend']

Is there some downside to this?


text:
Q: VS 201x - How do downloaded Bower .js files get deployed? Waffle
I've now been trying to automate and sort out a VS2013, not vNext, ASP.NET MVC project that started life as a front-end project on a Mac by a digital agency!
Aside: I've not yet used VS 2015, or ASP.NET vNext.
It uses npm, grunt and bower but not in the new VS 2015 template project way. We have to manually install the CLI tools and invoke it all manually, and it fails behind our proxy.
No one really understands this stuff or has the appetite to really tackle the problem. We copy files from a share to fudge it into working. It's a mess.
My Question
One of the things that's completely baffling me is how the dynamically-downloaded JavaScript files, via Bower, can be deployed via MSDeploy.
When a deployment package ZIP is created, it only includes content files declared the .csproj file.
In VS2015 there some kind of mechanism that auto-adds the downloaded Bower packages to the project?
Or some other trick?
Is there something that'll do this for VS 2013?

A: Not exclusive to Visual Studio 2015, but part of the ASP.NET 5 tooling.  You can add an array of "prepublish" commands to your project.json that basically become part of the build/publish pipeline. Therefore, ensuring that Gulp, Bower or NPM commands can be run before the MSDeploy publish happens and are ready to be picked up by MSDeploy for publishing.
Reference:
http://docs.asp.net/en/latest/dnx/projects.html#publishing


text:
Q: NSDateFormatter returns unexpected nil I'm trying to use NSDateFormatter to get the NSDate from String.
I've got the date in this format "Sat, 01 Aug 2015 15:00:12 GMT" and I'm setting date format this way:
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
but dateFormatter.dateFromString("Sat, 01 Aug 2015 15:00:12 GMT") returns nil. Why is that happening and how to fix it?
EDIT:
var date:NSDate?
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
date = dateFormatter.dateFromString("Sat, 01 Aug 2015 15:00:12 GMT")


text:
Q: 3rd party assembly nagging when debugging in Visual Studio I use a third-party dll in my application developed in Visual Studio 2010 and C#. When I debug my application by clicking the "Run (Debug)" button in Visual Studio 2010, that dll can detect and know that I am in so-called "development mode".
When I go the bin/debug folder and double click my application's exe file, the dll doesn't complain.
How can I configure so when I run the application in "development mode", the dll still thinks that it is executed in normal mode?

A: It's probably checking Debugger.IsAttached.
Solution: Don't use the debugger.
Real solution: Buy the library.

A: Depending on what the library does, it may be possible to separate out your application into separate components, one of which uses the library and does not run in debug mode.  This will allow you to debug your application while still using the library.
Pro: What you are trying to do is definitely in violation of the license.  This solution might not be in violation of the license.
Con: This will make it impossible for you to debug your use of the library.  All it accomplishes is to allow you to debug the rest of your application by separating off the library usage.
Con 2: This will probably makes your application more difficult to maintain.  It may also impact performance.


text:
Q: String Interpolation with format variable I can do this:
var log = string.Format("URL: {0}", url);

or even like this
var format = "URL: {0}";
...
var log = string.Format(format, url);

I have a format defined somewhere else and use the format variable, not inline string.
In C# 6, this is seems impossible:
var format = $"URL: {url}"; // Error url does not exist
...
var url = "http://google.com";
...
var log = $format; // The way to evaluate string interpolation here

Is there anyway to use string interpolation with variable declared earlier?
C# 6 seems interpolate the string inline during compile time. However consider using this feature for localization, define a format in config or simply having a format const in a class.

A: String interpolation is not library, but a compiler feature starting with C# 6.
The holes are not names, but expressions:
var r = new Rectangle(5, 4);
var s = $"Area: {r.Width * r.Heigh}":

How would you do that for localization, as you intend to?
Even r only exists at compile time. In IL it's just a position on the method's variable stack.
I've done what you intend to do for resources and configuration files.
Since you can only have a finite set of "variables" to substitute, what I did was have an array (or dictionary, if you prefer) and use a regular expression to replace the names in the holes with its index. What I did even allowed for format specifiers.

A: No, you can't use string interpolation with something other than a string literal as the compiler creates a "regular" format string even when you use string interpolation.
Because this:
string name = "bar";
string result = $"{name}";

is compiled into this:
string name = "bar";
string result = string.Format("{0}", name);

the string in runtime must be a "regular" format string and not the string interpolation equivalent.
You can use the plain old String.Format instead.

A: One approach to work around that would be to use a lambda containing the interpolated string. Something like:
Func<string, string> formatter = url => $"URL: {url}";
...
var googleUrl = "http://google.com";
...
var log = formatter(googleUrl);

In C# 7.0, you could use a local function instead of a lambda, to make the code slightly simpler and more efficient:
string formatter(string url) => $"URL: {url}";
...
var googleUrl = "http://google.com";
...
var log = formatter(googleUrl);

A: This is supposed to be a comment to the answer from i3arnon but I do not have the reputation :-( :
But for those who come to this old thread, in string.Format the format can be a variable:
string name = "bar";
string format = "{0}";
string result = string.Format(format, name);

works.

A: More of an idea as opposed to an answer.
For the example shown in the question, you can do the following.
var format = "URL: ";
...
var url = "http://google.com";
...
var result= $"{format} {url}";

I have an actual project where I have to do something like this a lot:
var label = "Some Label";
var value = "SomeValue";

//both label & value are results of some logic

var result = $"{label}: {value}";

A: You can with the right Nuget package: https://www.nuget.org/packages/InterpolatedStringFormatter
var mystring = "a thing(and something {other})";
Console.WriteLine(mystring.Interpolate("else"));

Outputs:
a thing(and something else)

A: It seems that you can do it like this:
var googleUrl = "http://google.com";
var url = $"URL: {googleUrl}";

System.Console.WriteLine(url);

You can check for more details in https://msdn.microsoft.com/en-us/library/dn961160.aspx


text:
Q: Dynamic dojo/on event I have a scenario where I want to generalize a page scrolling event on button click using dojo. I haven't been able to make a breakthrough for quite sometime. I'm a DOJO beginner, would like some pointers to get a good solution. I have a fiddle:
http://jsfiddle.net/sacnayak/Ej39D/3/
Pasting the code in again for first reference:
require(["dojo/fx", "dojox/fx/scroll", "dojo/dom", "dojo/dom-style", "dojo/on", "dojo/domReady!", "dojo/window", "dojo/dom-geometry", "dojo/_base/fx", "dojo/Deferred", "dojo/query"],

function (coreFx, easing, dom, style, on, ready, win, domGeometry, fx, Deferred, query) {
function asyncProcess() {
    var deferred = new Deferred();

    setTimeout(function () {
        deferred.resolve("success");
    }, 500);

    return deferred.promise;
}

    var currentActiveDomButton = query("#screens .screen.active .card-footer-button")[0];
    console.log(currentActiveDomButton);

    on(dom.byId(currentActiveDomButton.id), "click", function () {

        var currentActiveDomNode = query("#screens .screen.active")[0];
        console.log(currentActiveDomNode);

        var screens = query("#screens .screen");
        var nextActiveDiv;
        for (i = 0; i < screens.length; i++) {
            if (dojo.attr(currentActiveDomNode, "id") != dojo.attr(screens[i], "id")) {
                nextActiveDiv = screens[i];
                console.log(nextActiveDiv);
                break;
            }
        }

        fx.animateProperty({
            node: currentActiveDomNode.id,
            duration: 500,
            properties: {
                opacity: {
                    start: '1',
                    end: '0.5'
                }
            }
        }).play();

        var process = asyncProcess();
        process.then(function () {
            style.set(nextActiveDiv.id, "display", "block");
            //dojo.byId(currentActiveDomButton.id).style.display = 'none';
            dojox.fx.smoothScroll({
                node: nextActiveDiv.id,
                win: window
            }).play();

            require(["dojo/dom-class"], function (domClass) {
                domClass.remove(currentActiveDomNode.id, "active");
                domClass.add(currentActiveDomNode.id, "visited");
                domClass.add(nextActiveDiv.id, "active");
                currentActiveDomButton = query("#screens .screen.active .card-footer-button")[0];
                console.log(currentActiveDomButton.id);

            });

        });

    });

});

A: Was able to fix this. Used a dojo.forEach and set up a event listener for every button.
Here's the fiddle:
http://jsfiddle.net/sacnayak/Ej39D/8/
require(["dojo/fx", "dojox/fx/scroll", "dojo/dom", "dojo/dom-style", "dojo/on", "dojo/domReady!", "dojo/window", "dojo/dom-geometry", "dojo/_base/fx", "dojo/Deferred", "dojo/query", "dojo/dom-class", "dojo/NodeList-traverse"],

function (coreFx, easing, dom, style, on, ready, win, domGeometry, fx, Deferred, query, domClass) {
function asyncProcess() {
    var deferred = new Deferred();

    setTimeout(function () {
        deferred.resolve("success");
    }, 500);

    return deferred.promise;
}

query(".card-footer-button").forEach(function (buttonNode) {
    on(dom.byId(buttonNode.id), "click", function () {

        //fetch the current active screen
        var currentActiveDomNode = query("#screens .screen.active")[0];

        var screens = query("#screens .screen");
        var nextActiveDiv;
        if (buttonNode.value == "Next") {
            for (i = 0; i < screens.length; i++) {

                if (dojo.attr(currentActiveDomNode, "id") != dojo.attr(screens[i], "id")) {
                    if (!domClass.contains(screens[i].id, "visited")) {
                        nextActiveDiv = screens[i];

                        break;
                    }
                }
            }

        } else if (buttonNode.value == "Edit") {

            nextActiveDiv = query("#" + buttonNode.id).parent(".screen")[0];

            /*fx.animateProperty({
                node: nextActiveDiv.id,
                duration: 500,
                properties: {
                    opacity: {
                        start: '0.5',
                        end: '1'
                    }
                }
            }).play();*/
        }

        fx.animateProperty({
            node: currentActiveDomNode.id,
            duration: 500,
            properties: {
                opacity: {
                    start: '1',
                    end: '0.5'
                }
            }
        }).play();

        var process = asyncProcess();
        process.then(function () {
            style.set(nextActiveDiv.id, "display", "block");
            dojo.byId(buttonNode.id).style.display = 'none';

            if(dojo.byId(buttonNode.id + 'Edit') !== null){
                dojo.byId(buttonNode.id + 'Edit').style.display = 'block';
            }

            if (buttonNode.value == "Edit") {
                    //query(".card-footer-button").forEach(function (buttonArray) {
                        //if(buttonArray.value == "Next"){
                           // buttonArray.style.display = "none";
                        //}
                    //});

                if (buttonNode.id.indexOf("Edit") != -1) {
                    //console.log('Here');
                    //console.log('index' + buttonNode.id.indexOf("Edit"));
                    //console.log('length' + buttonNode.id.length);
                    var start = 0;
                    var end = buttonNode.id.indexOf("Edit");
                    var associatedNextButtonNode = buttonNode.id.substring(start, end);
                    //console.log(associatedNextButtonNode);
                    dojo.byId(associatedNextButtonNode).style.display = 'block';
                }
            }

            dojox.fx.smoothScroll({
                node: nextActiveDiv.id,
                win: window
            }).play();

            if(nextActiveDiv.style.opacity == '0.5'){
                fx.animateProperty({
                node: nextActiveDiv.id,
                duration: 500,
                properties: {
                    opacity: {
                        start: '0.5',
                        end: '1'
                    }
                }
            }).play();
            }

            require(["dojo/dom-class"], function (domClass) {
                domClass.remove(currentActiveDomNode.id, "active");
                domClass.remove(nextActiveDiv.id, "visited");
                if (buttonNode.value == "Next") {
                    domClass.add(currentActiveDomNode.id, "visited");
                }
                domClass.add(nextActiveDiv.id, "active");

            });

        });

    });

});

});


text:
Q: Cannot generate unified Allure report from two separate Jenkins maven builds I want to generate a unified report by merging the results from two separate Jenkins maven projects (and I've read that Allure does support that feature - to merge results different allure-results folders), but it does not work properly as I'll explain below.
My objective is to have visibility from all tests results I've from all projects. Currently I can only see the test results specific to a project.
This is the context:
I've two Maven projects (for testNG) running and reporting results via allure on JENKINS. As you can see below, the allure results from those two builds are  working as expected - automatically generated by Allure Jenkins plugin version 2.26.0
Allure Jenkins plugin working fine for separate maven jobs
Now I've also installed the Allure 2.6.0 and added it on system PATH and properly configure ALLURE_HOME environment var.
So when I ran this command here:
allure serve "C:\Users\tester\workspace\scripts-qa\STF\allure-results" --host "127.0.0.1" --port "8081"
It works perfectly to report the results in my Allure-results from my IntelliJ, as you can see below.
Allure serve results from my local worspace
Now when I ran similar command as above one to generate a unified report by merging both reports I got in Jenkins - just the execution trend is been populated - but the total number of tests and its details are not as you can see below.
This is the command I'm executing to generate a unified report:
allure serve "C:\Users\tester\.jenkins\workspace\Regression2\allure-report" "C:\Users\tester\.jenkins\workspace\Regression1\allure-report" --host "127.0.0.1" --port "8081"
Allure problem when trying to merge reports from two separate jenkins projects
Could you please help me to figure out what is wrong here? Is that possible that allure binary cannot serve results generated by allure Jenkins plugin? If yes, what is the work around to fix that?
Thank you!!
Jean.

A: I can see that you are trying to generate cumulative report from already generated reports, which is not correct - Allure needs raw allure-results to generate report
As a workaround, you need

*

*Archive allure-results for each test execution job and attach it to build as artifact

*Copy allure-results artifacts

*Unzip it

*Build a report based on allure-results from artifacts

Below are code snippets for Pipeline job
Attach allure-results as artefact:
zip archive: true, dir: "target/allure-results", glob: '', zipFile: "allure-results.zip"

Copy artefacts to another job:
copyArtifacts filter: 'allure-results.zip', optional: true, projectName: "Regression1", selector: lastCompleted(), target: "Regression1"
unzip dir: "Regression1", glob: '', zipFile: "Regression1/allure-results.zip"
...

Build report
allure serve Regression1 Regression2

A: You can also select reports for aggregation like this:
allure includeProperties: false, jdk: '', results: [
        [path: '../name-of-job-1/target/allure-results'],
        [path: '../name-of-job-2/target/allure-results'],
        [path: '../name-of-job-3/target/allure-results']]
    }


text:
Q: How can i check if a String has a specific form? Hello i am trying to read from a file and check if the form of a line is corect.
Input file:
LoopStep(i,0,m-1,1)
LoopStep(j,0,n-1,1)
    If  (ip_fac_p_d_fast[i][j]>fac_tmp)   #Take care: operations are allowed  If(n_32<n_sp_is-c_n_dif_isc_act_pl_down)
        Calc(fac_tmp,ip_fac_p_d_fast[i][j])
    Endif
Next(j)
LoopStep(j,0,n-1,1)
    Calc(ip_fac_p_d_fast[i][j],fac_tmp)
Next(j)
Calc(fac_tmp,0)
Next(i)

I have to check if each of the statements (LoopStep,If) has the coresponding number of paranthesis .


text:
Q: Cache larger-than-memory dataframe to local disk with Dask I have a bunch of files in S3 which comprise a larger-than-memory dataframe.
Currently, I use Dask to read the files into a dataframe, perform an inner-join with a smaller dataset (which will change on each call to this function, whereas huge_df is basically the full dataset & does not change), call compute to get a much smaller pandas dataframe, and then do some processing. E.g:
huge_df = ddf.read_csv("s3://folder/**/*.part")
merged_df = huge_df.join(small_df, how='inner', ...)
merged_df = merged_df.compute()
...other processing...

Most of the time is spent downloading the files from S3. My question is: is there a way to use Dask to cache the files from S3 on disk, so that on subsequent calls to this code, I could just read the dataframe files from disk, rather than from S3? I figure I can't just call huge_df.to_csv(./local-dir/) since that will bring huge_df into memory which won't work.
I'm sure there is a way to do this using a combination of other tools plus standard Python IO utilities, but I wanted to see if there was a way to use Dask to download the file contents from S3 and store them on the local disk without bringing everything into memory.

A: Doing huge_df.to_csv would have worked, because it would write each partition to a separate file locally, and so the whole thing would not have been in memory at once.
However, to answer the specific question, dask uses fsspec to manage file operations, and it allows for local caching, e.g., you could do
huge_df = ddf.read_csv("simplecache::s3://folder/**/*.part")

By default, this will store the files in a temporary folder, which gets cleaned up when you exit the python session, but you can provide options using an optional argument storage_options={"simplecache": {..}} to specify the cache location, or use "filecache" instead of "simplecache" if you want to enable the local copies to expire after some time or to check the target for updated versions.
Note that, obviously, these will only work with a distributed cluster only if all the workers have access to the same cache location, since the loading of a partition might happen on any of your workers.


text:
Q: Date in MySQL Laravel ORM I store my dates in timestamp type (and I see in PHPMyAdmin for simple 2015-04-14 00:00:00). Is it stupid? Better way is set to int type and save UNIX time?
How can I do query
select * from `values` where `time` < $mytimeinunix

because Model::all()->where('time','<',$mytimeinunix) is not working.
Regards

A: You're looking for UNIX_TIMESTAMP:
Model::where(DB::raw('UNIX_TIMESTAMP(time)'), '<', $mytimeinunix)->get();


text:
Q: Rotationally invariant function in three-sphere I know that every rotationally invariant function $f(x,y,z)$ in two-sphere $S^2$ must satisfy
\begin{align*}
f(x,y,z)=f(h(\theta)(x,y,z)^T)
\end{align*}
for all $\theta$ and $x,y,z$, where
\begin{align*}
h(\theta)=\begin{pmatrix} \cos\theta &-\sin\theta\ &0\\ \sin\theta & \cos\theta & 0\\0&0&1 \end{pmatrix}.
\end{align*}
Here the rotation is assumed to be around $z$-axis.
What I am still confused about is, how to generalize this in case of three-sphere $S^3$? I know that we can somehow use the fact that $S^3$ is a group of unit quaternions but I do not know where to start. Any idea would be appreciated.


text:
Q: chartjs angular update order Got a question about chartjs in an angular11 environment.
I have 2 charts
appcomponent.html:

  <canvas id="bl" ></canvas>

  <canvas id="bl2" ></canvas>

app.component.ts:
export class AppComponent {
            testChart: any;
            testChart2: any;
            ...
  constructor(private dataSvc:DataRetrieverService){
    dataSvc.getUsers.subscribe( data=> {
      if(!data) return;
      this.Users = data;
      this.Users.forEach(x => {
        this.UsersLabels.push(x.StoreDateTime);
        this.UsersAmount.push(x.Amount);
        this.CreateCharts();
      })
    })

    dataSvc.getParts.subscribe( data=> {
      if(!data) return;
      this.Parts = data;
      this.Parts.forEach(x => {
        this.PartsLabels.push(x.StoreDateTime);
        this.PartsAmount.push(x.Amount);
        this.CreateCharts();
      })
    })
  }

  CreateCharts(){
    if(this.testChart){
      this.testChart.destroy()
    }
    if(this.testChart2){
      this.testChart2.destroy()
    }

    this.testChart = new Chart('bl', {
      type: 'line',
      data: {
        labels: this.UsersLabels,
        datasets: [
          {
            label: 'Users',
            data: this.UsersAmount,
            borderColor: '#01c38c',
            backgroundColor: '#01c38c',
            fill: false
          }
        ]
      },
      options: {... }
      }
    });

    this.testChart2 = new Chart('bl2', {
      type: 'line',
      data: {
        labels: this.PartsLabels,
        datasets: [
          {
            label: 'Parts',
            data: this.PartsAmount,
            borderColor: '#01c38c',
            backgroundColor: '#01c38c',
            fill: true
          }
        ]
      },
      options: {...
      }
    });

Is creating the testChart: Any the correct thing to do?
Why do I have to call this.CreateCharts() after every data retrieval from the service in order to make it work?
I would expect if I would do a this.CreateCharts() at the very last step of the constructor it would also work, but then my chart is empty.

A: You're subscribing to two Observable obtained from dataSvc.getUsers and dataSvc.getParts, corresponding results will be delivered asynchronously, certainly after the invocation of the constructor has finished. Therefore, If with given code, you would invoke CreateChart() at the end of the constructor only, you would see two empty charts because UsersLabels, UsersAmount, PartsLabels and PartsAmount are still empty arrays at this point.
It's however needless to recreate both charts each time any Observable delivers new data. You better split CreateChart() into separate methods, one for each chart. Also instead of using chart.destroy(), you should better simply update the existing chart data and invoke chart.update() afterwards. Please take a look at the section Adding or Removing Data of the Chart.js documentation.


text:
Q: Why computers can be modeled as sample and hold system I was reading digital control system from book by Norman S.Nise and in book it is written that
"computers can be modeled as a sample and hold system "
Isn't computer is discrete time system and its output should be discrete  while sample and hold is a analog  system and its output is continuous ?
So how a discrete system (computer )can be replaced by a continuous system (sample +hold) ?
Or I'm missing something?

A: With sampling you convert an infinite variable (time) to a discrete one.
Hold is just a helper for quantization of amplitude values as we haven't invented an converter which needs zero time.
I guess your book tries to emphasize that a computer "transfers" its results to the inputs, fetches other values, then the state is virtually "on hold" while the compute core (ALU) samples and processes the values. When ready, the next cycle starts. So a computer partitions its cycle in 2 or more phases, which is similar but not equal to a AD Converter...
That said we must keep in mind, modern CPU's are much more complex and much more parallel. So while a single CPU Core and its associated Input Registers might be in a "hold" state while computing a result e.g. a division which needs several clock cycles, the instruction fetchers, memory interfaces, DMA, other CPU Cores,... all might be pretty busy.

A: There's no discrete signal physical circuits in the macroscopic scale that we can observe, they can occur only in atomic level. Every physical measurable quantity appears as continuous in macroscopic scale.
Voltages get changed gradually and the logic state is our interpretation of the voltage level or the timing of a pulse. We tend to make discrete classifications because our thinking and communication happens by using a language built of discrete symbols. But our spoken, heard and written texts are transferred with continuous signals where we are used to include and extract discrete information.
Of course we have built automatic circuits which do the interpretations of electric signals for us and launch operations which are based on predetermined rules for the wanted state transitions. That is what the computers are. Taking a sample of a a changing voltage at certain moment, measuring it and setting a voltage to somewhere according the measurement result and a inbuilt rule how to combine several results is what the logic circuits in computers do.


text:
Q: why I cannot open the excel file which create by fastExcel as the title said;
I create a .xls file by the lib called fastExcel successfully,but I cannot open it on my win7 systems normally.
this is my code for create the .xls file:
    private static  List<String[]> readLocationInfos(String path, String type) throws Exception {
        Workbook workBook = FastExcel.createReadableWorkbook(new File(path));
        workBook.open();
        Sheet s = workBook.getSheet(0);
        List<String[]> result = new ArrayList<String[]>();
        for (int i = s.getFirstRow(); i < s.getLastRow(); i++) {
            String[] row = s.getRow(i);
            result.add(row);
        }
        //          if(i!=0)
        //              converte(row, type);
        workBook.close();
        return result;
    }

    private static void output(List<String[]> list, String outputPath) throws ExcelException, IOException {
        File outputFile = new File(outputPath);
        Workbook workBook = FastExcel.createWriteableWorkbook(outputFile);
        workBook.open();
        Sheet sheet = workBook.addStreamSheet("sheet1");
        for(String[] row : list)
            sheet.addRow(row);
        workBook.close();
   }

I read the datas from another .xls file,and i want to do some converte to generate a new .xls file;
At last,I can read the new .xls file by the readLocationInfos method,but only can't open on my win7 system?
Will it was cause by a license problem?
Can anyone help me? thanks a lot..


text:
Q: How to use apply functions on multiple columns in groupby? df.dropna(subset=["home_team_goal_timings","away_team_goal_timings"]).groupby("home_team_name")[["home_team_goal_timings","away_team_goal_timings"]].apply(lambda x: ",".join(x).split())

I grouped the data by the column home_team_name I want to group aggregate data for two columns. This returns [home_team_goal_timings,away_team_goal_timings] for every group. It works fine if you use some aggregate function such as sum on some other attribute. How can you make it work for apply?


text:
Q: Move imagefile based on CSV cell data I know this is intro stuff but I'm not a programmer and I've been working on this for days and I'm about to beat my dog..
I have a csv file with imagenames and attributes, i.e.,
12-123.png,M
12-124.png,F
12-241.phg,M
...
and I'm trying to move them into respective directories, "orig_png/m/" or "orig_png/f/", based on the second row data, "M" or "F". I've tried every script I've found online, and there's always some problem, so I modified one that was close to what I needed and I could understand what was going on.. I know I've probably mangled this, but here's what I have (most PRINT statements were for me to see what was happening):
# Import csv
import csv
# Import os
import os, shutil
# Main Function
# def main():
# Open dataset file
# dataset = open('database_png.csv', newline='')
dataset = open('database_png.csv')
path = "home/darryl/Machine_Learning/ribs/200x200/orig_png/"
moveto1 = "home/darryl/Machine_Learning/ribs/200x200/orig_png/m/"
moveto2 = "home/darryl/Machine_Learning/ribs/200x200/orig_png/f/"
# Initialize csvreader for dataset
reader = csv.reader(dataset)
# Read data from reader
data = list(reader)
# Variables for progress counter
lines = len(data)
i = 0
# Analyze data in dataset
for row in data:
# Assign image name and state to variables
image = row[0]
state = row[1]
# Print image information
print image
print state
print('({}/{}) Processing image ({}): {}'.format(i + 1, lines, state, image))
# Increment i
i += 1
print moveto1
# Determine action to perform
if state is "M":
    print moveto1+image
    src = path+image
    dst = moveto1+image
    dst1 = moveto2+image
    shutil.move(src,dst)
elif state is "F"
    shutil.move(src,dst1)

mostly error messages are,
IOError: [Errno 2] No such file or directory: 'home/darryl/Machine_Learning/ribs/200x200/orig_png/12-094.png', when it LOOKS like it's correct, and
File "move4.py", line 39
    elif state is "F"
                    ^
SyntaxError: invalid syntax
If someone could help me with a simple way to do this (I know I've made this more complicated than necessary), I would be extremely grateful, and I might even learn something in the process!
NOTE: Here is the cut down file, but still errors. how do I fix this?
import csv
import os, shutil
dataset = open('database_png.csv')
path = "/home/darryl/Machine_Learning/ribs/200x200/orig_png/"
moveto = "/home/darryl/Machine_Learning/ribs/200x200/orig_png/m/"
reader = csv.reader(dataset)
data = list(reader)
lines = len(data)
i = 0
for row in data:
    image = row[0]
    state = row[1]
    i += 1
    if state is "M":
        src = path+image
        dst = moveto+image
        shutil.move(src,dst)


text:
Q: Cartoon: crocodile shaman teleports an Indian village into the future to a giant skyscraper roof It's a very old cartoon series maybe from the 90s. The main characters are humanoid animals, who speak and act like people in a little Native American village.
In the past, a crocodile shaman brews his old family potion in a cauldron. Something goes wrong and the whole village is transported into the future to a skyscraper roof. The villagers looks like (buffaloes) foxes with typical Native American traits. There is a fat, ailing Chief who does not know about the whole thing and the others are trying to keep it a secret. There are the youngsters, maybe 2 boys and 1 girl. They have a Beaver neighbor, a typical lumberjack with axe and strong black coffee. And last the clumsy, forgetful crocodile shaman who is trying to prepare new potions to get them back into the past. He have many recipes hiden everywhere, but dont know what is the right one, so that always goes wrong. Any typical thing you can think of, one time it's hypnotize them, other times they switch bodies, get hallucinations, it multiplies them, etc.
The antagonist is maybe a wolf who wants to sell the old, abandoned skyscraper, but first he needs to get rid of them somehow.
Some parts i remember:
The crocodile shaman new potion can multiply people and the antagonist hypnotize the Beaver lumberjack and with his clones try to take over the village.
The Beaver give some coffee to the Chief and he dont like it.
The Chief want's to speak with their ancestors(great spirits) so ask the shaman to give him some potion. It's dont worked instead he is sleepwalking in the night. He use an outside evelator and see some construction workers working on the skyscraper. In the end he thinks that all just was a vision and thanked the shaman.
They where in some trouble, then the shaman find a leaf under his hat use it in the claudron potion and saving the day.

A: The cartoon you are looking for is La Dernière Réserve (2000) (The Last Reservation(2000)), which is apparently a French made cartoon.

When their medicine man, Storm Warning, mucks up the magic potion supposed to protect them from the forthcoming eclipse, the Indian A-choo tribe find themselves in the future, stranded on the roof of a skyscraper in the midst of a huge modern city...

Description from this link, which also has a video (the beginning of which is the opening of the cartoon in English).

Image from this DeviantArt.


text:
Q: White space between tags is breaking my layout I know i could "remove the white space" but that is so inconvenient. There are so many places in the html where i have some inline-block element and it would be hell to go and look for every one of them.
Is there a way to make this white space not appear?
This is my site, as you can see the spaces are breaking my layout: http://www.fashionstore.al/

A: There are a couple of ways of "cheating". The way I used to do it before I learned any server-side code was this:

Text

More text

By commenting out the whitespace, it no longer causes problems for layout but still lets you separate the lines.
With server-side code, it's easier:
<?php
    echo '
'
            .'
Text
'
            .'
More text
'
        .'
';
?>

Or, another method:
<?php ob_start(function($c) {return preg_replace("/>\s+</","><",$c);}); ?>

Text

More text

<?php ob_end_flush(); ?>


text:
Q: how to replace a value for string if letters are missing? I ran into a problem where i have to create a 'LettersOfName' column. As name suggest I have to get letter 2,3 and 5 from ORGANISATIONNAME column and letters 2 and 3 from CLIENTLASTNAME column, then concatenate to form letters of name column. The condition is if letters of name is not equal to length 5 than replace with '22222' also if any of the letters is missing from first name and last name than replace with '22222'. I am using this query.
select

    ( CASE  WHEN LENGTH (UPPER( SUBSTR(ORGANISATIONNAME, 2,2) || SUBSTR(ORGANISATIONNAME,5,1)) || UPPER(SUBSTR(CLIENTLASTNAME,2,2))) != '5' THEN '22222'
            ELSE UPPER( SUBSTR(ORGANISATIONNAME, 2,2) || SUBSTR(ORGANISATIONNAME,5,1)) || UPPER(SUBSTR(CLIENTLASTNAME,2,2)) END)
            AS LETTERSOFNAME

from client;

So, far this query runs fine, but when we have name like 'Jo Anne' or 'J Shark' it is missing letter '2' and '3' but does not replace the string with '22222'. When length is not equal to 5 it replaces with '22222'. I am using Oracle 12c.

A: If after the concatenations of the letters you remove all the spaces and the length of the remaining string is less than 5 then replace with '22222':
SELECT
  CASE
    WHEN LENGTH(REPLACE(SUBSTR(ORGANISATIONNAME, 2, 2) || SUBSTR(ORGANISATIONNAME, 5, 1) || SUBSTR(CLIENTLASTNAME, 2, 2), ' ', '')) < 5 THEN '22222'
    ELSE UPPER(SUBSTR(ORGANISATIONNAME, 2, 2) || SUBSTR(ORGANISATIONNAME, 5, 1) || SUBSTR(CLIENTLASTNAME, 2, 2))
  END LETTERSOFNAME
FROM client

Or with a CTE:
WITH cte AS (
  SELECT
    UPPER(REPLACE(
      SUBSTR(ORGANISATIONNAME, 2, 2) ||
      SUBSTR(ORGANISATIONNAME, 5, 1) ||
      SUBSTR(CLIENTLASTNAME, 2, 2),
      ' ',
      ''
    )) LETTERSOFNAME
  FROM client
)
SELECT
  CASE
    WHEN LENGTH(LETTERSOFNAME) < 5 THEN '22222'
    ELSE LETTERSOFNAME
  END LETTERSOFNAME
FROM cte

See the demo.

A: You should first remove the white space between the string and and then apply your case statement on it
replace ('J Shark', ' ', '')

Reason is white space is being counted as a character in J Shark and that is why second and third characters are missing.
Here is an example demo.

A: Here is my approach:

*

*Put both columns ORGANISATIONNAME and CLIENTLASTNAME to another table with identity column (to identify each row)

*Write a function to split text by a string (in this case pass a space)

*Get the identity and the splitted data to 2 tables each for column 1 and 2

*Consider each table and apply your logic

*Concatenate the row values separated by space, with the ID (1 record per ID)

*Join the 2 tables (by IDs)

Join the 2 tables for matches in Col-Split data, and get the IDs
Now Query for the data in table in above 1


text:
Q: How to find a Jacobian matrix of a vector function in Julia using "IntervalArithmetic.jl" package? Could you please provide a solution for finding a Jacobian matrix for a vector function using the "IntervalArithmetic.jl" package in Julia? The function representation and the required Jacobian matrix is shown below.
f = [f1(x,y,z), f2(x,y,z), f3(x,y,z)]
Jacobian = [df1/dx, df1/dy, df1/dz; df2/dx, df2/dy, df2/dz; df3/dx, df3/dy, df3/dz]

A: Here you go:
(the explanation of this code is left as a self exercise to the user of this code, which should be able to do it, otherwise using this code is a little risky - it isn't so well tested)
using IntervalArithmetic, FiniteDiff, Optim

function interval_jacobian(F, x)
    x0 = mid.(x)
    F0 = F(x0)
    dummy = zero(eltype(x0))/one(eltype(F0))
    restype = typeof(dummy)
    M = length(F0)
    N = length(x0)
    lows = fill(dummy, M, N)
    highs = fill(dummy, M, N)
    xlo = getproperty.(x, :lo)
    xhi = getproperty.(x, :hi)
    inner_optimizer = GradientDescent()
    for i in 1:M
        for j in 1:N
            ff = (x -> FiniteDiff.finite_difference_derivative(t -> F(Base.setindex(tuple(x...), t, j))[i], x[j]))
            gg! = ((G, x) -> ( G .= FiniteDiff.finite_difference_hessian(x -> F(x)[i], x)[:, j]))
            res = optimize(ff, gg!, xlo, xhi, x0, Fminbox(inner_optimizer))
            lows[i,j] = res.minimum
            ff2 = (x -> -ff(x))
            gg2! = ((G, x) -> (gg!(G, x); G .= -G))
            res = optimize(ff2, gg2!, xlo, xhi, x0, Fminbox(inner_optimizer))
            highs[i,j] = -res.minimum
        end
    end
    return [l..h for (l,h) in zip(lows, highs)]
end

With this definition:
# defining a function taking a single tuple parameter

g((x,y)) = [ 3x^2 + 4y^3 + x*y^2, 2x + y^4, x^2 + y^2 ]
# g (generic function with 1 method)

# and another one:

g2((x,y)) = [ 3sin(x)^4*cos(y), 2cos(x)^5+y^3 ]
# g2 (generic function with 1 method)

# some intervals as inputs:

xintervals = [1.0..2.0, 2.0..3.0]
# 2-element Vector{Interval{Float64}}:
# [1, 2]
# [2, 3]

# the interval Jacobian calculated:

interval_jacobian(g, xintervals)
# 3×2 Matrix{Interval{Float64}}:
#  [10, 21]            [52, 120]
#     [1.99999, 2]  [32, 108]
#   [2, 4]               [4, 6]

interval_jacobian(g2, xintervals)
# 2×2 Matrix{Interval{Float64}}:
# [-3.85812, 3.71688]       [-2.7279, -0.212259]
# [-0.717112, 0]       [12, 27]

This is not meant to be performant, or symbolic. Issues with infinities not dealt with, or just issues such as functions being too unstable for Optim optimizer.


text:
Q: Finding the correct ancestor in a 2-3 Tree So I am having trouble finding the correct ancestor in a 2-3 Tree. In a 2-3 Tree of arbitrary height, there are a couple of cases to look for.

My nodes are designed as follows:
template<typename DataType>
struct node{
   Node<DataType> *child1; //left-child
   Node<DataType> *child2; //middle-child (3-node only)
   Node<DataType> *child3; //right-child
   Node<DataType> *extraChild; //for splitting purposes

   Node<DataType> *parent;

   DataType key1; //key1 <= key2
   DataType key2; //key2 <= extraKey (only when node needs to be split)
   DataType extraKey; //for splitting purposes
};

Is there an algorithm or something similar to find the proper ancestor to a node?
For example, say we were looking for the ancestor of H (bottom of the provided tree), it is obvious from a visual perspective that ancestor of H is the H at the root of the tree. But that requires jumping up 4 parent links. The tree could be of arbitrary size which is the issue.
My goal in the end is to create an iterator that does an in order traversal of the 2-3 tree. The purpose of finding an ancestor node is that the ancestor node will be the in-order successor of the leaf node that is the right child of it's parent node. Again, as in the example provided above.

A: If the goal is simply to traverse a 2-3 tree in-order, then you just need to write a recursive function that starts at the root.
The algorithm is as follows:
traverse(Node n)

    if n.left != null
        traverse(n.left)

    if n.middle != null
        visit(n.key1)
        traverse(n.middle)
        visit(n.key2)
    else
        visit(n.key1)

    if n.right != null
        traverse(n.right)

Algorithm taken from this link.


text:
Q: Lambda faster way for variable numbers of different Ids on search Func<vw_UsuarioPerfilAtributo, bool> expressionPerfil = Perf =>
  foreach(int _key in Keys){
    Perf.Id == _key ||
  }

(I need multiple OR ||)
I think this is faster than
    List<vw_UsuarioPerfilAtributo> teste = new List<vw_UsuarioPerfilAtributo>();
    teste.add(context.Find(Id));

Possible?

A: Maybe you need something like:
//use a method because use a foreach in a lambda expression isn't allowed
public bool myFunction(vw_UsuarioPerfilAtributo Perf){
   foreach(int _key in Keys){
        if(Perf.Id == _key || /*other condition here*/)
           return true;
   }

   return false;
}

And:
Func<vw_UsuarioPerfilAtributo, bool> expressionPerfil = Perf => myFunction(Perf);

Or just:
Func<vw_UsuarioPerfilAtributo, bool> expressionPerfil = Perf => Keys.Any(_key => Perf.Id == _key || /*other condition here*/);

I think this is faster than
teste.add(context.Find(Id));

In this case context.Find(id) (where context is a List<>) returns the found element while the previous code returns a boolean because of Func<vw_UsuarioPerfilAtributo, bool>

A: You can the PredicatorBuilder class. It is a famous class about some extensions methods for lambda expressions. Take a look at this link:
http://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder/
After adding this class at yoru project you can do something like:
var result = list.Where(x => condition).And(x => condition).Or(x => condition).ToList();


text:
Q: Loop in database using perl I need to extract each character from the input (input are numbers) and check it against my database, if the number is present the corresponding rows will be printed. But in my code the loop doesn't work and only the first character is printed.
use dbi;
my $seq=<stdin>;
my $r=my$seq;
my $db="hnf1a";
my $user="root";
my $password="";
my $host="localhost";
my $dbh = DBI->connect("DBI:mysql:database=$db:$host",$user,$password);
my @w= split(//, $r);
print @w;
foreach my $b(@w)
{
my $sth=$dbh -> prepare("select an,ano from mody having ano = '$b' ");
my $rv=$sth->execute();
while (my @row =$sth->fetchrow_array())
{
print @row;
}
}
my $rc=my $sth->finish;
}
print "database closed";`

A: Database:
mysql> select * from mody;
+----+---------+------+
| id | an      | ano  |
+----+---------+------+
|  1 | 123     | 456  |
|  2 | abc     | 567  |
|  3 | hello   | 5    |
|  4 | world   | 5    |
|  5 | goodbye | 6    |
+----+---------+------+
5 rows in set (0.00 sec)

Code:

use strict;
use warnings;
use 5.020;
use autodie;
use Data::Dumper;
use DBI;

my $dsn = 'dbi:MariaDB:database=my_db;host=localhost';
my $dbh = DBI->connect($dsn, 'root', '');
my $sth = $dbh->prepare('SELECT an,ano FROM mody where ano = ?');

my $input = "56";
my @numbers = split //, $input;

for my $number(@numbers) {
    say "rows matching input <$number>:";

    $sth->execute($number);

    while(my @data = $sth->fetchrow_array) {
        say "\t@data";
    }
};

Output:
rows matching input <5>:
    hello 5
    world 5
rows matching input <6>:
    goodbye 6


text:
Q: How can align Primefaces datatable left which is inside a Tab? Hi I have this code ...
<p:tab title="Explore More" >
                    <ui:insert name="sideMenu">
                        <ui:include src="../ST/InterestingNumberList.xhtml" />

                    </ui:insert>

and

InterestingNumberList.xhtml

Contain a Datatable. How can i align this whole Datatable left side inside Tab?My Interesting Numberlist page
<div class="col1" xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui">

    <h:form prependId="false">
        <p:dataTable id="companyList" rows="10" style="text-align:left"
            value="${bean_numbers_list}" var="num_feature">
            <p:column  >
                <h:outputLink styleClass="morelinks"
                    value="${facesContext.externalContext.requestContextPath}/topStocks/${num_feature.name}">
                    <h:outputText value="#{num_feature.shortDesc}" />
                    <f:ajax event="click" immediate="true" />
                </h:outputLink>
            </p:column>
        </p:dataTable>
    </h:form>
</div>

Screen i added red rectangle on the listbox which i will want to aligh left.


text:
Q: How do I get data to show up in angular ui.grid from an $http request continuation Okay I'm going to keep this as short as possible.
I've been studying Angular for a bit now and there's still a lot I need to learn, right now I'm trying to figure out how to connect end to end with headers in a service which is completely new to me as I've never done end to end integration.
The code below is provided from another stack overflow answer and what I want to know is how do I connect what they have with say dataService.js. This is all new to me so I'm trying to ask this the best way possible.
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

    <link rel="Stylesheet" type="text/css" href="Scripts/ng-grid/ui-rid.min.css" />

Provided from: How do I get data to show up in angular ui.grid from an $http request

A: The method I use is to pass the URL as an AJAX call and then wait for the data to get back after which I connect the JSON data to the ng-grid. Note that there will be a delay in getting the data back from the URL and you will have to have a timer that will keep checking for the data return begin valid.
function setCar(){
$.ajax({
   type: "POST",
   url: '/Test/ConfigConnect.json?details=&car='+car+'&id=1',
   dataType: 'json',
   success: function(data){
        configData = data;
    }
});}

The timer function that is part of the javascirpt is also given below.
    var timer = setInterval(function() {
      $scope.$apply(updatePage);
}, 500);

var updatePage = function() {
    if (typeof configData !== 'undefined')
    {
        clearInterval(timer);
        $scope.loadData = configData;
    }
};


text:
Q: Find if vector contains pair with second element equal to X I have this vector:
using namespace std;

vector< pair<short, string> > vec = {};

And I want to find out if exists a pair <a, b> with b == X.
I know about std::find from <algorithm> but don't know how to apply it here.
Should I write my own function to do that?
bool is_in_vec(X)
{
    for (auto& e : vec)
        if (e.second == X)
            return true;
    return false;
}

Is that efficient?

A: In fact you can have your cake and eat it, if you are free to sort the vector of pairs based on the second field.
In this case you end up reinventing what Boost calls flat_(multi_)map. The obvious benefit is that searching can be done in O(log(n)) instead of linear time.
See it Live On Coliru
using namespace std;

#include <utility>
#include <vector>
#include <string>
#include <algorithm>

typedef std::pair<short, std::string> Pair;

struct Cmp
{
    bool operator()(Pair const& a, Pair const& b) const { return a.second < b.second; };
    bool operator()(Pair const& a, std::string const& b) const { return a.second < b; };
    bool operator()(std::string const& a, Pair const& b) const { return a < b.second; };
};

int main()
{
    std::vector<Pair> vec = {
        { 1, "aap" },
        { 2, "zus" },
        { 3, "broer" }
    };

    Cmp cmp;
    std::sort(vec.begin(), vec.end(), cmp);

    auto it = std::binary_search(vec.begin(), vec.end(), std::string("zus"), cmp);

    std::cout << it->first << ": " << it->second << "\n";
}

Prints
2: zus
42: zus

A: In C++11, you can use also std::any_of
std::string X{"foobar"};
return std::any_of(vec.begin(), vec.end(),
                   [&X](const pair<short, string>& p)
                   { return p.second == X; });

A: I think that you should use an std::map instead, which will provide a preffy efficient std::map::find member function:
std::map<std::string, short>
// …
auto it = map.find(X);

This is as efficient as it goes for this kind of lookup (which is guaranteed to be O(log(N))).

A: Your solution looks fine if you only want to know if there is an element satisfying your criteria present. I would use const references in the loop, because the loop should not change the elements of the vector:
for (const auto& e : vec) ....

If you want to use a standard library algorithm, you can try std::find_if:
const std::string X{"foobar"};

auto it = std::find_if(vec.begin(),
                       vec.end(),
                      [&X](const pair<short, string>& p)
                      { return p.second == X; });

Here, it is an iterator to the first element satisfying the condition, or equal to vec.end() if no element is found.


text:
Q: Show procedure/function code in MySql Is there any options to view stored procedure/function code in MySql same as like "sp_helptext procedurename" in sql?

A: Yes,
SELECT ROUTINE_DEFINITION FROM information_schema.ROUTINES WHERE SPECIFIC_NAME='procedurename'

A: try "SHOW CREATE PROCEDURE procedurename"

A: You can get the information form the INFORMATION_SCHEMA.ROUTINES table

A: I've been experimenting a bit, and I think one of the following two works best.
To list everything (parameters, collating, etc.), use this.
 SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA in (SELECT DATABASE()) AND ROUTINE_NAME='ProcedureName';

To list only the code, use this.
SELECT ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA in (SELECT DATABASE()) AND ROUTINE_NAME='ProcedureName';

In both of the above, the nested select is required to limit the result to the current database, since INFORMATION_SCHEMA, being the system database, contains details for every database installed in the instance.

A: Go to mySQL workbench

*

*Right click on procedure and then select ALTER. (This Will open the definition of procedure for you(is the easiest way).

OR

*

*You can also use the command, SHOW CREATE PROCEDURE proc_name;


text:
Q: Is it possible to add text underneath a part's title? In a LaTeX report I'm working on, I have used \part{title of part} to organise the chapters into parts.
This gives me distinct pages for each \part specified which is what I want. But if I try to add text beneath the part's title, it is printed on the next page.
Is it possible to place text on the \part page directly under the title of the part?
Thanks Christian. The part pages now look something like what you see below with text added. The only other thing will be to try to move the text up a bit.

A: There seems to be a \newpage at the end of part command, which has to be kicked out, by relaxing it temporarily, in a group.
\documentclass{book}

\usepackage{etoolbox}
\usepackage{blindtext}

\makeatletter

\let\LaTeXStandardPart\part%
\newcommand{\unstarredpart@@noopt}[1]{%
  \unstarredpart@@opt[#1]{#1}%
}%

\newcommand{\unstarredpart@@opt}[2][]{%
  \cleardoublepage% (For clearing content before!!!)
  \begingroup%
  \let\newpage\relax%
  \LaTeXStandardPart[#1]{#2}%
  \endgroup%
}%

\newcommand{\starredpart}[1]{%
  \LaTeXStandardPart*{#1}%
}%

\newcommand{\unstarredpart}{%
  \@ifnextchar[{\unstarredpart@@opt}{\unstarredpart@@noopt}%
}%

\renewcommand{\part}{%
  \@ifstar{\starredpart}{\unstarredpart}%
}%

\begin{document}

\part{Some part}%
\blindtext[10]

\chapter{First chapter}

\section{First section}%

\blindtext

\part{Other part}
\chapter{Other chapter}%

\end{document}

A: Lesser code with xpatch
\documentclass{book}

\usepackage{xpatch}
\usepackage{blindtext}

\makeatletter
\xpatchcmd{\@endpart}{\vfil\newpage}{}{}{}
\xpatchcmd{\@endpart}{\newpage}{}{}{}
\makeatother

\begin{document}
\tableofcontents
\part{Some part}%
\blindtext[10]

\chapter{First chapter}

\section{First section}%

\blindtext

\part{Other part}
\chapter{Other chapter}%

\end{document}


text:
Q: Category theoretic analog of choosing a representative of an equivalence class In a category $\mathcal{C}$ with binary products, a congruence on an object $X$ is a monomorphism $i : R \to X \times X$ satisfying reflexivity, symmetry and transitivity, which take the form of morphisms and commuting squares. In the category of sets, the coequaliser for the projection morphisms
$$
\pi_1\circ i, \pi_2\circ i : R \to X
$$
exists and is the set of equivalence classes. Then I can choose a representative for each equivalence class to get a section of the quotient map.
Is there a name for a category where something similar can always be done, i.e. the coequaliser for a congruence exists and there always exists a section?

A: For starters, let's distinguish three types of epimorphisms.

*

*$f : X \to Y$ is a split epimorphism if it has a section.

*$f : X \to Y$ is a regular epimorphism if it is the coequalizer of some pair of maps to $X$ (not necessarily a congruence).

*$f : X \to Y$ is an effective epimorphism if it has a kernel pair $X \times_Y X$ (which I believe is always a congruence on $X$) and is the coequalizer of its kernel pair.

Split epimorphisms are always regular, and in any category with pullbacks, regular and effective epimorphisms coincide (see e.g. this blog post). I understand these conditions somewhat better than your condition about congruences (which I expect ought to be equivalent to both regular and effective under mild hypotheses) so I'll work with them instead. So one version of the question is:

When are effective epimorphisms always split?

The answer is almost never, and I don't know a name for categories with this property. For example,

*

*effective epimorphisms in $\text{Mod}(R)$ are just quotient maps $M \to N$, but split epimorphisms are projections onto direct summands $N \oplus M/N \to N$. Every effective epimorphism is split iff $R$ is semisimple. More generally, in any abelian category, every effective epimorphism is split iff $\text{Ext}^1(-, -)$ vanishes identically iff every object is projective iff every object is injective.

*effective epimorphisms in $\text{Grp}$ are just quotient maps $G \to H$, which correspond to extensions $N \to G \to H$, but split epimorphisms correspond to semidirect products, and most extensions are not semidirect products. The simplest example is $\mathbb{Z}_2 \to \mathbb{Z}_4 \to \mathbb{Z}_2$.

*effective epimorphisms in $\text{Top}$ are quotient maps $f : X \to Y$ (that is, $Y$ must have the quotient topology), but split epimorphisms are, well, quotient maps with sections. Most quotient maps don't have sections. For example, a fiber bundle is an effective epimorphism, but most fiber bundles don't have sections; think of the bundle of nonzero tangent vectors on a smooth manifold.

As Daniel Schepler says, even the claim that this is possible in $\text{Set}$ is more or less equivalent to the axiom of choice.


text:
Q: How to deploy a functionapp from remote zip file using powershell I want to deploy a functionApp in azure using a zip file which is in another azure blob storage using powershell.
I tried like following method
#PowerShell
$username = "<deployment_user>"
$password = "<deployment_password>"
$filePath = "https://xxxxx.blob.core.windows.net/container/zzzz.zip"
$apiUrl = "https://<app_name>.scm.azurewebsites.net/api/zipdeploy"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f
$username, $password)))
$userAgent = "powershell/1.0"
Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -UserAgent $userAgent -Method POST -InFile $filePath - ContentType "multipart/form-data"

But I got the following error message like

Invoke-RestMethod : Cannot find drive. A drive with the name 'https' does not exist.

How I do the deployment from a remote url file?

A: Since Invoke-RestMethod InFile accepts the content from a file, blob content needs to be explicitly downloaded first.
Option 1
$fileUrl = "https://xxxxx.blob.core.windows.net/container/zzzz.zip"
$token = 'sp=r&st=2019-07-06T21:41:45Z&se=2019-07-07T05:41:45Z&spr=https&sv=2018-03-28&sig=9ud%2FiJ6GBccxZfyrKsZtP69lwuralu1D0QiiESa%2FXgo%3D&sr=b'
$filePath = [System.IO.Path]::GetFileName($fileUrl)
Invoke-WebRequest ('{0}?{1}' -f $fileUrl, $token) -OutFile $filePath

Prerequisite
Instead of resource Url, SAS (Shared Access Signature) URI needs to be provided
  which includes a SAS token to perform the authenticated
  request

Option 2
Via Azure Storage Cmdlets:
$StorageAccountName = 'yourstorageaccount'
$StorageAccountKey = Get-AzureStorageKey -StorageAccountName $StorageAccountName
$StorageContext = New-AzureStorageContext $StorageAccountName -StorageAccountKey $StorageAccountKey.Primary
$FileName = 'zzzz.zip'
$OutputPath = 'C:\Temp'
$ContainerName  = 'yourcontainer'
Get-AzureStorageBlobContent -Blob $FilebName -Container $ContainerName -Destination $OutputPath -Context $StorageContext

A: Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -UserAgent $userAgent -Method POST -InFile $filePath - ContentType "multipart/form-data"

-InFile $filePath

param expect the path of file locally.
Check the documentation:
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod?view=powershell-6
Use something like:

*

*First, download the blob from Azure Storage.

*Convert into byte stream.

*Set as a part of your request (Body).

Sample Code for reference:
$base64Image = [convert]::ToBase64String((get-content $path -encoding byte))

Invoke-WebRequest -uri $uri -Method Post -Body $base64Image -ContentType "application/base64"