text:
Q: Local composer package in Laravel does not match the expected JSON scheme I'm trying to load a local package into my Laravel 8 project, but am getting the following error in ./composer.json:
  "./composer.json" does not match the expected JSON schema:
   - repositories[5].url : The property url is required
   - repositories[5].type : Does not have a value in the enumeration ["composer"]
   - repositories[5].type : Does not have a value in the enumeration ["vcs","github","git","gitlab","bitbucket"
  ,"git-bitbucket","hg","fossil","perforce","svn"]
   - repositories[5].type : Does not have a value in the enumeration ["artifact"]
   - repositories[5].type : Does not have a value in the enumeration ["pear"]
   - repositories[5].package : The property package is required
   - repositories[5].type : Does not have a value in the enumeration ["package"]
   - repositories[5] : Failed to match at least one schema
   - repositories[5] : Must contain no more than 1 properties
   - repositories[5].type : String value found, but a boolean is required
   - repositories[5].type : Does not have a value in the enumeration [false]
   - repositories[5].path : String value found, but a boolean is required
   - repositories[5].path : Does not have a value in the enumeration [false]

My composer.json file contains the following for the require and repos section:
"repositories": [
    {
      "type": "vcs",
      "url": "git@github.com:company/pkg-fudge-inbound-management-bridge.git"
    },
    {
      "type": "vcs",
      "url": "git@github.com:company/pkg-inbound-management.git"
    },
    {
      "type": "vcs",
      "url": "git@github.com:company/pkg-blog.git"
    },
    {
      "type": "vcs",
      "url": "git@github.com:company/pkg-credit-score.git"
    },
    {
      "type": "vcs",
      "url": "git@github.com:company/pkg-policies.git"
    },
    {
      "type": "path",
      "path": "/Users/ryanholton/Sites/laravel-packages/pkg-cms"
    }
],
"require": {
    "php": "^7.3",
    "doctrine/dbal": "^2.11",
    "fideloper/proxy": "^4.2",
    "fruitcake/laravel-cors": "^2.0",
    "guzzlehttp/guzzle": "^7.0.1",
    "laravel/framework": "8.60.*",
    "laravel/tinker": "^2.0",
    "company/pkg-fudge-inbound-management-bridge": "1.1.*",
    "company/pkg-inbound-management": "2.0.*",
    "company/pkg-blog": "1.4.*",
    "company/pkg-credit-score": "1.2.*",
    "company/pkg-policies": "1.0.*",
    "company/pkg-cms": "*"
}

Not sure why I'm getting this error, never had it with local packages before, what am I missing?

A: As error said your last item in repositories array should look like:
{
  "type": $type,
  "url": //here you have to define url
  "path": "/Users/ryanholton/Sites/laravel-packages/pkg-cms"
}

and your $type variable should have 1 of the values below:
"vcs","github","git","gitlab","bitbucket" ,"git-bitbucket","hg","fossil","perforce","svn","composer","artifact","pear","package"

If you are trying yo add package, then $type should be "package".

A: Try this!
{
"repositories": [
        {
            "type": "package",
            "package": {
                "name": "name/example-package",
                "version": "dev-master",
                "source": {
                    "url": "git@github.com:company/pkg-policies.git",
                    "type": "git",
                    "reference": "dev-master"
                }
            }
        }
    ]
}

A: Based on the docs: https://getcomposer.org/doc/05-repositories.md#path
You need to define like this
{
    "repositories": [
        {
            "type": "path",
            "url": "/Users/ryanholton/Sites/laravel-packages/pkg-cms"
        }
    ],
}

So it seems you just need to replace path with url.


text:
Q: Combine if and countif in Google Sheets I am trying to make a list on Google sheets that increases according to the value of the number. So it would look like this as you go down: 2,2,4,4,4,4,6,6,6,6,6,6,8...
I have tried putting 2 in column A1 and below it putting this formula: =if(A2<(COUNTIF(A$2:A2,A2)),A2,+2)
But all I get when I drag it down are rows of 2s.
Is there some way of combining if and countif so I can count how many occurences of the number in A2 there are, and once there are, say, four 4s, it adds 2 (and once there are six 6s, it adds two, and so on)?
Thanks
Tardy

A: You just need to change A2 to A1 otherwise you would be getting a circular reference:-
=IF(COUNTIF(A$1:A1,A1)<A1,A1,A1+2)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular bloqueando submit de formulário GET Tenho um formulário onde eu envio uma consulta para a url atual, através de parâmetros GET. Por exemplo, eu tenho url/teste, ao enviar a consulta por esse formulário, ficará url/teste?term=minha+consulta.
Eu não usei Angular nessa parte, pois já estava pronta, então o formulário já existia antes.
Quando coloquei o angular, esse formulário parou de fazer o submit.
Exemplificando meu cenário:
<body ng-app="my_app">
    <!-- esse input manda para mesma página uma pesquisa GET, por isso não usei "ACTION" -->
    <form id="form-pesquisa">
        <input type="search" name="term" />
        <button type='submit'>Pesquisar</button>
    </form>

    <!-- uso esse formulário no Angular -->
    <form ng-controller="UserCreateController">
        <input type='text' name="email" ng-model="user.email" />
        <input type='password' name="password" ng-model="user.password" />
    </form>
</body>

Percebi que o angular está adicionando as classes ng-submitted nesse formulário quando eu envio a submissão.
Gostaria de saber como posso usar um formulário, dentro do contexto do ng-app, mas podendo fazer uma submissão via GET.
O angular realmente bloqueia essas requisições? Como contornar isso?

A: Pela resposta do Vanderlei, concluímos que, o problema era a falta do action no formulário, onde se desejava fazer uma submissão de dados para o servidor.
Na verdade, é possível você usar o formulário sem o action normalmente no HTML. Sempre que você fizer isso, o formulário será submetido para a url atual.
Porém, com a falta do action, quando você utiliza o Angular, ele bloqueia qualquer submissão. E explico o por quê:
Mas por que sem o action não funcionou, como costuma funcionar sem o AngularJS?
De acordo com a documentação do AngularJS:

For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified

Que traduzindo é:

Por esta razão, O Angular impede a ação padrão (envio do formulário para o servidor) a menos que o action seja especificado no elemento .

Então, mesmo que a intenção seja utilizar o formulário para enviar uma submissão para própria página, é necessário usar o atributo action, pois, por padrão, o angular, na falta desse atributo, utiliza o preventDefault para evitar submissões padrão.

A: O AngularJS bloqueia a ação padrão do formulário a não ser que o action seja especificado no <form>. Então apenas adicione o action referenciando a própria página:
<form ng-controller="UserCreateController" action=".">
   ...
</form>

Nesse caso, quando você utiliza o ., é entendido pelo navegador que você está referenciando a própria página.


text:
Q: Tabhost setup() not working I follow the tutorial in android documentation how to use Tabhost within Fragment, But I'm getting always
The method setup(android.content.Context, android.support.v4.app.FragmentManager, int) in the type FragmentTabHost is not applicable for the arguments (android.content.Context, android.app.FragmentManager, int)

My setup command is like this:
mTabHost.setup( getActivity().getApplicationContext(), getChildFragmentManager(), R.layout.fragment_vc_view);

A: Sounds like your class in which you call the setup method extends android.app.Fragment and not android.support.v4.app.Fragment.


text:
Q: Adding Captions to Jquery Fullscreen Slideshow I have been struggling with what seems like should be an easy problem:
I inherited a site that uses what looks to be a combination of a slider and jquery backstretch. The client has requested that one of the slideshows have captions, positioned along the visible bottom of the image.
So I want to turn this:

Into this:

Caption

And destroy each instance of the div, as it does with the images.
However, I can't seem to get the javascript to render the caption div, and keep it in synch with the navigation. For the purposes of clear water, I have removed all of my attempts, and gone back to the JS code I started with.
Here is an example: http://tylonius.net/backstretch/lifestyle-gallery.html
Can anyone help with this?

A: Other answer is not relevant, I didn't notice it was FancyBox.
A similar question was posted here, here and here. As @JFK sated in the first link you could use the data-, prefix to an attribute of image to hold the caption information. And access it with a jquery script.
<!doctype html>

 . . .
    <title>your demo</title>

and the script would be:
$(document).ready(function() {
    $(".fancybox").fancybox({
        helpers : {
        title: { type: 'inside'}
    },
    // use the following if you want to do the caption before the image
    // beforeShow : function(){
    afterLoad: function(){
        this.title = this.title + ' ' + $(this.element).data("caption");
        //you can also do the following to use the alt instead of the caption
        //this.title = this.title + ' ' + $(this.element).find('img').attr('alt');
    }

    }); // fancybox
}); // ready


text:
Q: How can I establish this inequality? I'm trying to show that for $m\geq 1$ and $n>2$, we have the following inequality:

$4(m-1)^{n} + 2nm^{n-1} \geq (m-2)^{n} + 3 m^{n}$

Any ideas?
Thanks for the help!

A: Let $u=m-1.$
Then, we want to show $$4u^n+2n(u+1)^{n-1} \ge (u-1)^n+3(u+1)^n$$
As polynomials, the coefficient of $u^i$ on the left for $i<n$ is $2n{n-1\choose i},$ while on the right it is $2{n\choose i}$ for $n-i$ odd and $4{n\choose i}$ for $n-i$ even. This is by the binomial theorem. The coefficient of $u^n$ is 4 on both the left and the right side.
Note that $n{n-1\choose i} = (n-i){n\choose i}.$ I claim that the coefficient of $u^i$ on the left is greater than the coefficient of it on the right for $i \le n-2$, and is equal to it for $i = n-1, n$. This will solve the problem as $u$ must be nonnegative.
Indeed, for $i = n-1$, $2n{n-1\choose n-1} = 2{n \choose n-1}.$ For $i=n$, both coefficients are 4. And for $i \le n-2$, $2n{n-1\choose i} = 2(n-i){n \choose i}\ge 4{n\choose i},$ the largest possible value of the coefficient on the right.
If we are allowing $m,n$ to not be natural numbers, then this still works if $m > 2$, just use the extended binomial theorem instead of the binomial theorem. And if $m < 2$, then $(m-2)^n$ isn't defined for $n$ not a natural number, and the argument works if $n$ is.


text:
Q: Compiling Foundation 5 without gulp but with Symfony2 I'm running a project where Symfony2 serves the api and back-end; I use bower to install my front-end dependencies, including Angularjs and Zurb Foundation. We're using Assetic––a Symfony2 bundle––to minify, uglify, pre-render and combine our assets. We're also using Sass (as .sass), compiled by Assetic.
I want to work with Foundation's _settings.scss and understand that Foundation needs to recompile itself whenever I change a variable. I've tried running compass watch path_to_file but that doesn't update my Foundation project.
As I understand it, a lot of people run foundation using Compass or gulp. I've read through several docs but am unsure how it relates to my particular case. One source suggests running compass init to start a project and that compass watch to update the project when I make changes, but that doesn't seem appropriate to do with Symfony2, but I may be wrong. Anyone got tips?
I'm using this foundation repo: https://github.com/zurb/bower-foundation,
but there's also this one: https://github.com/zurb/foundation-apps. The second repo seems more suited for people who are running a Foundation project with gulp, the foundation cli, or by running compass init when starting a project.

A: The answer is incredibly simple:
I use Assetic to compile my sass. It typically looks like this:
{% stylesheets
    "@SiteBundle/Resources/public/vendor/foundation/scss/app.scss"
filter="compass" %}
    <link rel="stylesheet" type="text/css" href="{{ asset_url }}"/>
{% endstylesheets %}

app.scss is a file I created because that seems to be how everyone works with foundation. app.scss then imports the foundation components I want as well as normalize.scss and _settings.scss. I don't have to run compass watch because Assetic is already compiling for me.
I might move my app.scss and _settings.scss out of my vendors directory to ensure I don't write over either when updating foundation. But at the moment here's what my app.scss looks like, for anyone interested:
@charset "UTF-8";
// Foundation by ZURB
// foundation.zurb.com
// Licensed under MIT Open Source

// Import normalize and settings

@import "normalize.scss";
@import "foundation/settings";

// Make sure the charset is set appropriately

// Behold, here are all the Foundation components.
@import "foundation/components/grid";
// @import "foundation/components/accordion";
@import "foundation/components/alert-boxes";
@import "foundation/components/block-grid";
// @import "foundation/components/breadcrumbs";
@import "foundation/components/button-groups";
@import "foundation/components/buttons";
@import "foundation/components/clearing";
@import "foundation/components/dropdown";
@import "foundation/components/dropdown-buttons";
@import "foundation/components/flex-video";
@import "foundation/components/forms";
@import "foundation/components/icon-bar";
@import "foundation/components/inline-lists";
// @import "foundation/components/joyride";
@import "foundation/components/keystrokes";
@import "foundation/components/labels";
// @import "foundation/components/magellan";
// @import "foundation/components/orbit";
@import "foundation/components/pagination";
@import "foundation/components/panels";
// @import "foundation/components/pricing-tables";
@import "foundation/components/progress-bars";
@import "foundation/components/range-slider";
@import "foundation/components/reveal";
@import "foundation/components/side-nav";
@import "foundation/components/split-buttons";
@import "foundation/components/sub-nav";
@import "foundation/components/switches";
@import "foundation/components/tables";
@import "foundation/components/tabs";
@import "foundation/components/thumbs";
@import "foundation/components/tooltips";
@import "foundation/components/top-bar";
@import "foundation/components/type";
@import "foundation/components/offcanvas";
@import "foundation/components/visibility";


text:
Q: How to prevent website structure changing when zooming out? Here is my HTML:

        Page 1

        Page 2

        Page 3

        Page 4

And my CSS:
.banner {
    background: orange;
    color: aqua;
    float: left;
    width: 298px;
    height: 50px;
    vertical-align: top;
    border: 1px solid #000000;
    text-align: center;
    font-family: Garamond;
    font-size: x-large;
    display: table-cell;
    vertical-align: middle;
    line-height:50px;
    cursor:pointer;
    font-weight:bold;
}

The body of my website is 1200px wide. The website structure appears to work fine on different sized screens (from the computers I have checked it on) and all major browsers. However, when zooming out, on all devices, the far right  drops down and goes to the left (beneath the first ). Is there any way to do this without any major difficulties? (time is an issue here which is why I only want a simple solution if possible). If there isn't an easy and fast way to do this, then don't worry about it, I'll just leave it as it is.

A: Simple answer is, you can't.  No CSS tweaks or JS detect zooming.

A: See this link about viewport meta tag, It could prevent zoom in/out by determining the views width, so I think it may help you
Using the viewport meta tag to control layout
Update:
See this link also
How can I "disable" zoom on a mobile web page?


text:
Q: 500 error when adding a message item attachment to a message draft Nice, just caused a couple of 500 errors on your server, grins. Tried to add another message as an attachment to a draft.
The payload (body) was
{
  "@odata.type": "#Microsoft.OutlookServices.ItemAttachment"
  IsInline:     false
  ContentType:  "message\rfc822"
  Name"         "original message.eml"
  Id"           originalMessageId
}

Here's the whole CURL command
'https://outlook.office365.com/api/v2.0/me/messages/AAMkAGQyZTBkZjQ1LWQ3M2QtNDk2MS04MWI4LTJhNWY1MGRmYzkyNwBGAAAAAABPZeBlIKL6TJIRMaoqmdhGBwAP_JVVr_HSRLiiYMDstTKcAAAAAAEPAAAP_JVVr_HSRLiiYMDstTKcAAADdPhwAAA=/attachments'
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3436.0 Safari/537.36' -H 'Referer: https://localhost:3443/index.html?et=' -H 'Origin: https://localhost:3443' -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkJnRDU5blJpQnpmbk5BVGloOFJhZ1l5M3pyZyJ9.eyJvaWQiOiI0NDQ1NGRkOC02ZDRmLTRlY2QtYTNkMi0yYmZlZjIyZTI3ZmIiLCJwdWlkIjoiMTAwMzdGRkVBQUQzNzhDMCIsInNtdHAiOiJhZG1pbkB0ZXN0aW5nbnoub25taWNyb3NvZnQuY29tIiwidXBuIjoiYWRtaW5AdGVzdGluZ256Lm9ubWljcm9zb2Z0LmNvbSIsInZlciI6IkV4Y2hhbmdlLkNhbGxiYWNrLlYyIiwiYXBwaWQiOiIwMDAwMDAwMi0wMDAwLTBmZjEtY2UwMC0wMDAwMDAwMDAwMDAiLCJkZXBsb3ltZW50aWQiOiJodHRwczovL291dGxvb2sub2ZmaWNlMzY1LmNvbS8iLCJ0aWQiOiI5MTI3MzU0YS1iMzczLTQyOTQtOTRmNy02YmFjNzliZjk0ZWYiLCJhY3IiOiIxIiwiYXBwaWRhY3IiOiIwIiwic2NwIjoiTWFpbC5SZWFkV3JpdGUgTWFpbC5TZW5kIENhbGVuZGFycy5SZWFkV3JpdGUgQ29udGFjdHMuUmVhZFdyaXRlIiwiaXNzIjoiaHR0cHM6Ly9vdXRsb29rLm9mZmljZTM2NS5jb20vIiwiYXVkIjoiaHR0cHM6Ly9vdXRsb29rLm9mZmljZTM2NS5jb20iLCJleHAiOjE1MjY4Nzg1MjEsIm5iZiI6MTUyNjg3NzYyMX0.hw7Vt6fvZNtpBMuvj0oikWGBRYL0AqhmZvMhJKPMoyIjXNrG0cXgDD74XcUtkGYl4hBM1IdHObXFeCazE7o2OYqzKAdBFznpJzYA-3svg0H8NjJuP1ZiObDYfsJiTySN9r7OpecImBnqp8KYxzSiDd6EUxlK3QvdUOW57bUCcZ3rRsgq4v5i5v7rV6Lz6WG-wkz_n7mbOlBuPlnjCQ0oGvYUhSYtabG6RLgVTC4Is6r6hSy0LdmmJ3030CYWQJS3Fc5amAWtV9y-6YgZesaZoJy1au1C2LcqSIjdxdQ_CSiU1bGt8Lwom5My5v5VXun-qfr8W7l5HFU2kSYjAjsCpg'
-H 'DNT: 1' -H 'content-type: application/json' --data-binary '{"@odata.type":"#Microsoft.OutlookServices.ItemAttachment","IsInline":false,"ContentType":"message\rfc822","Name":"original message","Id":"AAMkAGQyZTBkZjQ1LWQ3M2QtNDk2MS04MWI4LTJhNWY1MGRmYzkyNwBGAAAAAABPZeBlIKL6TJIRMaoqmdhGBwAP_JVVr_HSRLiiYMDstTKcAAAAAAEdAAAP_JVVr_HSRLiiYMDstTKcAAADdQAfAAA="}'
--compressed

and the 500 response is this
{
  "error": {
    "code": "ErrorInternalServerError",
    "message": "An internal  server error occurred. The operation failed."
  }
}

Been reading https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/message_post_attachments but doesn't help much with this problem.
Any clues?

A: Got it working now. No, using ItemAttachment. Just the Id parameter was wrong. Replaced that with the "Item" parameter using original JSON of message to be attached.


text:
Q: Multiple S3 Inputs into Glue Pipeline I have 3 separate data sources (files) in 3 separate S3 buckets. The schema in these 3 sources are different from one another but the timestamp is the same (hourly in epoch).
Previously, I used Glue to read from 1 bucket and apply transformations to the files in that bucket and write to a resulting bucket.
With the 3 data sources, can I still read them from 3 different buckets and somehow join them on the epoch timestamp and then spit out the unified datasource (combination of all 3) .. I guess Glue will have to do row level JOINS in this case.
The blog posts about Glue I have found on the web so far only talk about single source input and transformations.
If this is not possible the way I am asking it? How else would you do it?

A: I'm not quite sure what you're asking, but the Glue Dynamic Dataframe supports a join operation, though it's limited to inner joins. The Spark dataframe has a robust join method that supports inner, outer, and cross joins. So you should be able to load all three S3 locations into (dynamic) dataframes and join them to get a single result set that you can transform and write out.


text:
Q: Equality between double factorial and binomial coefficient I read this formula, but I don't think it's right
$$ \binom{1/4}{j} = \frac{(-1)^j(4j-5)!!}{4^j j!} $$
First off, I think that's $(-1)^{j+1}$. Then I have a product like $3\cdot7 \cdot11\cdot15 $. Does this expressed by $(4j-5)!!$?


text:
Q: I'm having some trouble with li::before content and the bullet unicode I'm trying to change the color of a list bullet, i followed some tutorials and it's working fine, except that when i type the unicode "\2022" and refresh the page, the "\" is gone and the website displays something like:
2
0
2
2 "li text"
.li-especialidades::before {
    content: "\2022"; /* when i load the page \ is gone */
    color: #e5cf00;
    font-weight: bold;
    display: inline-block;
    width: 1em;
    margin-left: -1em;
}

ps: it's a wordpress website

A: I lack some reputation to comment. But your code should actually work. Did some research and I found some way to achieve the result you want. Hope this will help.
.li-especialidades::before {
    content: "•"; /* I copied the disk itself */
    color: #e5cf00;
    font-weight: bold;
    display: inline-block;
    width: 1em;
    margin-left: -1em;
}


text:
Q: import .csv file in R containing strings and numerics how to convert? Suppose I have a .csv file and imported it in R:
    X        A       B       C
1           good    luck    man
2 string1
3 string2   2.2     3.3     4
4 string3   0.1     10      3

I used:
read.csv("~/Desktop/test.csv", stringsAsFactors=FALSE)

This is of class data.frame. Now I delete the first row and set the first column as rownames
test <- test[-1,]
rownames(test) <- test[,1]
test <- test[,-1]

This gives
> test
          A   B C
string1
string2 2.2 3.3 4
string3 0.1  10 3

The problem is, all the values are of class character. I would like to change them to numeric and convert the empty "cells" (i.e. empty strings "") to NA but still having a data.frame. How can this be achieved?

A: I couldn't find a good duplicate, so here goes. Use [] in order to preserve the class of test in combination with sapply which by default operates over columns of the data frame (or the arguments, as data.frame is essentially a list with columns as its arguments)
test[] <- lapply(test, as.numeric)

Note: Make sure that non of your columns is of class factor, otherwise this will return wrong results (without triggering a warning)

A: So your problem is that your CSV has two heading lines, and you want to use the first as column names?
Read in, skipping both header lines with skip=2 and (probably) head=FALSE in read.csv.
Then you have a data frame with generic column names but correct types.
Then read the second line of the file again, using readLines, and split that to get column names for the data frame you read in.
> df = read.csv("twohead.txt",skip=2,head=FALSE)
> colnames(df)=strsplit(readLines("twohead.txt",n=2)[2],",")[[1]]
> df
          good luck man
1 string1   NA   NA  NA
2 string2  1.2  1.1 2.2
3 string3  1.5  3.2 1.2

Rowname processing is as you have it, although I'd do:
> rownames(df)=df[,1]
> df[[1]]=NULL

Giving a df:
> summary(df)
      good            luck            man
 Min.   :1.200   Min.   :1.100   Min.   :1.20
 1st Qu.:1.275   1st Qu.:1.625   1st Qu.:1.45
 Median :1.350   Median :2.150   Median :1.70
 Mean   :1.350   Mean   :2.150   Mean   :1.70
 3rd Qu.:1.425   3rd Qu.:2.675   3rd Qu.:1.95
 Max.   :1.500   Max.   :3.200   Max.   :2.20
 NA's   :1       NA's   :1       NA's   :1


text:
Q: Bring back the "newest" tab on the users page The traditional users page has recently been replaced by a more dynamic reputation-league-style page. While I welcome this change in general, I would like to have the "newest" tab back.
While I agree that for example the "oldest" tab served little purpose, the newest tab can be useful: For example if you want to keep track of the rate with which new users sign up on a beta site (or if you want to see whether a recent blog post/reddit post/whatever caused an increase in sign ups or whether a friend you've been nagging to sign up has done so yet).
So I propose that in the addition to the league-style tabs, there should also be a "newest" tab which sorts the user by the date they registered, newest first.

A: Whether this came and went, it's back with the ability to sort "new users" based on "creation date":

"New users" are defined as those "who joined in the last 45 days".
Of course, the following query will also do the trick (with a bit of a delay from data in SEDE):
select Id, DisplayName, CreationDate
from Users
where DateDiff("d",CreationDate,getdate()) <= 45
order by CreationDate desc;


text:
Q: C# service fails to start I have created a C# Windows service but it fails to start. I get the following message when I attempt to start it:

The System Usage Monitor service on Local Computer started and then stopped.  Some services stop automatically if they have no work to do, for example, the Performance Logs and Alerts service.

The following is my OnStart override ...
  /// <summary>
  /// OnStart(): Put startup code here
  ///  - Start threads, get inital data, etc.
  /// </summary>
  protected override void OnStart(string[] args)
     {
     base.OnStart(args);

     broadcaster = new UdpBroadcaster(IP_Address, Port);
     itm = new IdleTimeMonitor(1 * 1 * 3000, 1000);
     aam = new ActiveApplicationMonitor(1000);

     itm.IdleTimeExceeded += new IdleTimeExceededDelegate(itm_IdleTimeExceeded);
     itm.IdleTimeReset += new IdleTimeResetDelegate(itm_IdleTimeReset);
     itm.IdleTimeEvaluated += new IdleTimeEvaluatedDelegate(itm_IdleTimeEvaluated);

     aam.StartedUsingApplication += new StartedUsingApplicationDelegate(aam_StartedUsingApplication);
     aam.EndedUsingApplication += new EndedUsingApplicationDelegate(aam_EndedUsingApplication);
     aam.ApplicationEvaluated += new ApplicationEvaluatedDelegate(aam_ApplicationEvaluated);
     }

Do I need to block at the end of that function or something? Why wont my service start?

A: Did you kick off a thread?
If you don't have a thread that does something then the application will close so when onstart finishes there is no thread (unless you kick one off in UdpBrodacaster) so the service closes.
EDIT: Just declare a ManualResetEvent that isn't signalled and have the thread call WaitOne() on it.  Then in your OnStop() signal the event (.Set()) to have the thread wake up and exit thus closing your service.

A: Take a look in the event log, if your service is starting then crashing for some reason there will be an exception event in the Application Log.

A: Put your code in the OnStart(string[]) in a try-catch-Block and log the exception to a log file (if one is raised). I think there is a problem on creating the instances.


text:
Q: Changing label color for each call of the \chapter command I would like to change the color of the chapter label (small rectangle box) everytime I call the command \chapter{}, possibly passing the color as an argument.
Thus the part I need to address with the argument is the command \draw[fill=black].
Here a compilable example:
\documentclass{book}
\usepackage{color}
\usepackage{tikz}
\usepackage[explicit]{titlesec}

\newcommand*\chapterlabel{}
%\renewcommand{\thechapter}{\Roman{chapter}}
\titleformat{\chapter}[display]  % type (section,chapter,etc...) to vary,  shape (eg display-type)
{\normalfont\fontsize{24}{26}\bfseries} % format of the chapter
{\gdef\chapterlabel{\thechapter\ }}     % the label
{0pt} % separation between label and chapter-title
  {\begin{tikzpicture}[remember picture,overlay]
\node[yshift=-8cm] at (current page.north west)
  {\begin{tikzpicture}[remember picture, overlay]
    \draw[fill=black] (0,0) rectangle(35.5mm,15mm);
    \node[anchor=north east,yshift=-7.2cm,xshift=34mm,minimum height=30mm,inner sep=0mm] at (current page.north west)
    {\parbox[top][30mm][t]{15mm}{\raggedleft $\phantom{\textrm{l}}$\color{white}\chapterlabel}};  %the black l is just to get better base-line alingement
    \node[anchor=north west,yshift=-7.2cm,xshift=37mm,text width=\textwidth,minimum height=30mm,inner sep=0mm] at (current page.north west)
          {\parbox[top][30mm][t]{\textwidth}{\color{black}#1}};
   \end{tikzpicture}
  };
 \end{tikzpicture}
  \gdef\chapterlabel{}
  } % code before the title body
 \usepackage[utf8]{inputenc}

 \title{test}

 \begin{document}

 \maketitle

 \chapter{Introduction}

 \end{document}

I tried to pass the argument to the \chapterlabel function but didn't work. I also found a very similar question
"https://tex.stackexchange.com/questions/641554/change-color-for-each-chapter" that didn't really received an answer (I tried the solution proposed but didn't work).
I would be really greatful if someone can help.

A: I suggest to define a series of colours with numbers in their names and the chapter will then use the colour depending on the current chapter number:
\documentclass{book}
\usepackage{color}
\usepackage{tikz}
\usepackage[explicit]{titlesec}

\colorlet{chapter1}{red}
\colorlet{chapter2}{blue}

\newcommand*\chapterlabel{}
%\renewcommand{\thechapter}{\Roman{chapter}}
\titleformat{\chapter}[display]  % type (section,chapter,etc...) to vary,  shape (eg display-type)
{\normalfont\fontsize{24}{26}\bfseries} % format of the chapter
{\gdef\chapterlabel{\thechapter\ }}     % the label
{0pt} % separation between label and chapter-title
  {\begin{tikzpicture}[remember picture,overlay]
\node[yshift=-8cm] at (current page.north west)
  {\begin{tikzpicture}[remember picture, overlay]
    \draw[fill=chapter\the\value{chapter}] (0,0) rectangle(35.5mm,15mm);
    \node[anchor=north east,yshift=-7.2cm,xshift=34mm,minimum height=30mm,inner sep=0mm] at (current page.north west)
    {\parbox[top][30mm][t]{15mm}{\raggedleft $\phantom{\textrm{l}}$\color{white}\chapterlabel}};  %the black l is just to get better base-line alingement
    \node[anchor=north west,yshift=-7.2cm,xshift=37mm,text width=\textwidth,minimum height=30mm,inner sep=0mm] at (current page.north west)
          {\parbox[top][30mm][t]{\textwidth}{\color{black}#1}};
   \end{tikzpicture}
  };
 \end{tikzpicture}
  \gdef\chapterlabel{}
  } % code before the title body
 \usepackage[utf8]{inputenc}

 \title{test}

 \begin{document}

 \maketitle

 \chapter{Introduction}

  \chapter{foo}

 \end{document}

Alternatively you could colour the chapter with a user defined colour and change its definition before each chapter:
\documentclass{book}
\usepackage{color}
\usepackage{tikz}
\usepackage[explicit]{titlesec}

\colorlet{chapter}{red}

\newcommand*\chapterlabel{}
%\renewcommand{\thechapter}{\Roman{chapter}}
\titleformat{\chapter}[display]  % type (section,chapter,etc...) to vary,  shape (eg display-type)
{\normalfont\fontsize{24}{26}\bfseries} % format of the chapter
{\gdef\chapterlabel{\thechapter\ }}     % the label
{0pt} % separation between label and chapter-title
  {\begin{tikzpicture}[remember picture,overlay]
\node[yshift=-8cm] at (current page.north west)
  {\begin{tikzpicture}[remember picture, overlay]
    \draw[fill=chapter] (0,0) rectangle(35.5mm,15mm);
    \node[anchor=north east,yshift=-7.2cm,xshift=34mm,minimum height=30mm,inner sep=0mm] at (current page.north west)
    {\parbox[top][30mm][t]{15mm}{\raggedleft $\phantom{\textrm{l}}$\color{white}\chapterlabel}};  %the black l is just to get better base-line alingement
    \node[anchor=north west,yshift=-7.2cm,xshift=37mm,text width=\textwidth,minimum height=30mm,inner sep=0mm] at (current page.north west)
          {\parbox[top][30mm][t]{\textwidth}{\color{black}#1}};
   \end{tikzpicture}
  };
 \end{tikzpicture}
  \gdef\chapterlabel{}
  } % code before the title body
 \usepackage[utf8]{inputenc}

 \title{test}

 \begin{document}

 \maketitle

\colorlet{chapter}{green}
 \chapter{Introduction}

\colorlet{chapter}{orange}
  \chapter{foo}

 \end{document}


text:
Q: SAP Commerce: Implementation of AutoPick function in 2005 I am currently implementing configurableBundle extension and testing the auto pick functionality. Is see that there is an "isAutoPick" function in configurableBundle addon. But I do not see any usages. In this article (https://help.sap.com/viewer/9d346683b0084da2938be8a285c0c27a/2005/en-US/8b887b9d866910148ac4c2ee46e16461.html?q=auto%20pick%20subscription), it states that the addToCart functionality is implemented in the subscriptionservice addon. But looking through the source code, I do not see the implementation for it. How does the auto pick functionality is implemented by default? If there is no default implementation, how would you set it up?
I tried to ask this question in community.sap.com but so far no answer. So I hope the StackoverFlow community is quicker and better with the response.
Best regards
Andy


text:
Q: Can I Invoke a nancy Module by myself Let's assume I have this Nancy Module
public class ProductModule : NancyModule
{
    public ProductModule(IProductRepository repo)
    {
        Get["/products/list"] = _ =>
        {
            ViewBag.Categories = repo.GetAllCategories();
            return repo.GetAllProducts();
        };
    }
}

I am using Razor as ViewEngine and I am able to display a list of products.
Now I want to be able to execute the same request within a Windows Forms application. I know I can do something like
var bootstrapper = new CustomBootstrapper();
bootstrapper.Initialise();
var engine = bootstrapper.GetEngine();
var request = new Request("GET", "/products/list.xml", "http");
var context = engine.HandleRequest(request);

Anyway that does not fit my needs since it involves the whole http pipeline and serializes my IQueryable. But in my windows Forms application I already have a proper pageing support for IQueryable<> objects. Currently I am supposed to have some redundant code with
public class ProductController
{
    dynamic ViewBag = new ExpandoObject();
    public dynamic List()
    {
        ViewBag.Categories = repo.GetAllCategories();
        return repo.GetAllProducts();
    }
}

And I want to get rid of that and only use my nancy modules.
Basically this has to be possible somehow, since, in my razor view I have exactly what I want and have full access to the ViewBag and Model.
I already downloaded the source but have not managed to find the right buttons to push.
Any suggestings would be appreciated.

A: Although I am not sure why the advice of @eth0 is not appropriate in your specific case, Nancy.Testing at least provides a way of circumventing the network stack.
var bootstrapper = new CustomBootstrapper();
var browser = new Browser(bootstrapper);
var result = browser.Get("/products/list.xml", with => { with.HttpRequest(); });

For more details see the official documentation: Testing your application

A: I think I found a solution within the nancy testing framework
Digging deeper with test extensions
public class GetModelExtententionsTests
{
    private readonly Browser _browser;
    public GetModelExtententionsTests()
    {
        this._browser = new Browser(with => {
           with.Module<AModuleToTestExtensionMethodsWith>();
           with.ViewFactory<TestingViewFactory>();
        });
    }

    [Fact]
    public void Can_get_the_model_and_read_the_values()
    {
       var response = this._browser.Get("/testingViewFactory");
       var model = response.GetModel<ViewFactoryTestModel>();
       Assert.Equal("A value", model.AString);
    }
}

Note: Use of these extension methods requires the use of the
  TestingViewFactory, set on the testing Browser object. It's a wrapper
  ViewFactory that saves the Model and then exposes it with the
  extension method. You don't have to think too hard about that though,
  only make sure to set the TestingViewFactory (e.g.
  with.ViewFactory();).

So basically the solution is to implement a viewfactory that store the model before rendering the view.


text:
Q: facebook payment tester gets error code 1353028 trying to implement the new Facebook local currencies, and I keep getting error code 1353028 if I set a user as a payment tester. if I remove the user from the payment user the payment dialog will open correctly.
the app is in sandbox mode, and the mentioned user has a "tester" role.
I also tried disabling sandbox and removing the user from being a tester, just leave him as a payment tester, but still not working.
what else remains to try? anyone else experienced this and found a solution?
and why on earth would Facebook prevent app admin/developers from being also payment testers??

A: well, I tried it again the day after, without changing anything, and there it is working properly, showing me the payment dialog with 2 options (success, failure) just like in Facebook's tutorial...
so for anyone having the same issue, try leaving it for a night...


text:
Q: Horizontal border between 2 DIVs I have the following:

And instead of 2 separate borders which causes alignment issues (As you can probably tell) I want to put a long border which spans the first left div and continues into the second bigger div so it's clear which description belongs to which group.
Here's what I'm currently working with:

Name of Group

      Centennial College Dance Group

      Basketball Group

      Weight Loss Group

      Asian Social Group

      LGBTQ Group

      Study Group - Math 185

      Study Group - Web

      Study Group - Linux

Description

Centennial College Dance Group provides the opportunity for dancers, fanatics and coaches who enjoy all kinds of dance to participate in dance events every week catering to various levels of media involving dance.
Centennial College Dance Group programs and volunteer activities are funded and supported by the Scarborough Dance Recreation Parks and Wildlife Foundation, membership fees, user fees, corporate sponsors and fund raising activities.

Thursdays at the gym open time we book a court – need at least 6 people for pick-up games.

Meet in gym – work out in groups of 3 or 4.  Arrange times/events on our site.

As you can see I'm currently using break lines to align, which is causes a lot of problems.
Doing tables causes this:

How would I align and size them properly?

A: Here is a good basic set up without css classes with some of your data that should help you start making your table. Hope it helps. if you include the table in one div it will look nice and neat.The table border is not supported in html5.

  Name of group
  Description

  Centennial College Dance Group
  Centennial College Dance Group provides the opportunity for dancers, fanatics and coaches who enjoy all kinds of dance to participate in dance events every week catering to various levels of media involving dance.
Centennial College Dance Group programs and volunteer activities are funded and supported by the Scarborough Dance Recreation Parks and Wildlife Foundation, membership fees, user fees, corporate sponsors and fund raising activities.

  Basketball Group
  Thursdays at the gym open time we book a court – need at least 6 people for pick-up games.

  Weight Loss Group
  Meet in gym – work out in groups of 3 or 4.  Arrange times/events on our site.

A: Yeah, your
 and  tags are making this much more difficult than it should be. I would recommend replacing them with a

Name of Group

Centennial College Dance Group

Basketball Group

Weight Loss Group

Asian Social Group

LGBTQ Group

Study Group - Math 185

Study Group - Web

Study Group - Linux

As far as your alignment issues go, you'll need to make sure both containers (#sideleftsmall and #content) have the same top padding and top margin. You will also need to make sure and style both of your
 tags identically. This means you need to get away from the inline style="" and assign them the same class instead.
Here's some CSS to start out with
.title {
    padding: 5px;
    margin: 0;
}
#sideleftsmall ul {
    list-style-type: none;
    margin: 0;
    padding: 0 0 0 5px; /*align with header*/
}

#sideleftsmall ul li {
    padding: 3px 0;
}

A: If we talk about Semantic Code in this case we should use Definition List (check below why). First lets see the DEMO.
A Small Description is here why we should use Definition List here?

: Container

: Definition Term (like a title)

: Definition Description

Here is the CSS Code to align the items.
* {
 padding:0;
  margin:0;
}
dl {
 width:100%;
 overflow:hidden;
 background:#f5f5f5;
  clear:left;
}

dt, dd
{float:left;
  min-height:70px; /* will work till you know the max height of dd i.e. definition*/
border-bottom:1px solid #999;
width:50%;
  padding:15px 0;
}
dd{width:50%;}

UPDATED VERSION  check DEMO
The problem with the above approach it was not responsive i.e. when resize the browser the layout brakes. this could be solved by adding one extra markup and wrapping dt and dd inside the div.
New CSS Code is
dl > div {
  display: table-row;
  width:100%;
 overflow:hidden;
 background:#f5f5f5;

}
dl > div > dt {
  display: table-cell;
   min-height:70px;
  width:50%;
   padding:15px 0;
  border-bottom:1px solid #999;

}
dl > div > dd {
  display: table-cell;
  width:50%;
   padding:15px 0;
  border-bottom:1px solid #999;
}

HTML code is

Centennial College Dance Group

And instead of 2 separate borders which causes alignment issues (As you can probably tell) I want to put a long border which spans the first left div and continues into the second bigger div so it's clear which description belongs to which group.

NOTE: But This trick will work till you know the max height of the dd i.e. if you know how much amount of content
  will be in dd.


text:
Q: UILabel view disappear when the height greater than 8192 Assigning large string to UILabel. And, adding this label into a scroll view.
The UILabel disappear when the UILabel height larger than 8192pt (which is 2^13).
Is this an iOS bug?
And should I use other implementation to render such amount of string?
Should I use table view with cell?
UPDATE
The code that will display the UILabel:
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor clearColor];
label.text = rumor.displayText;
label.frame = CGRectMake(0, 0, self.view.frame.size.width, 8192);
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;

And the code that UILabel does disappear
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor clearColor];
label.text = rumor.displayText;
label.frame = CGRectMake(0, 0, self.view.frame.size.width, 8193);
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;

A: First of all - it doesn't have to be a bug. It is just undefined behavior. Note that with every component, there will be some upper size limit when the component stops working correctly . 8192 points seems to be a low limit but still it's about 8 times the iPad screen in portrait mode.
You are not supposed to make views that big. Note that UIViews are often rendered into memory and buffered, to make redrawing faster. With 8192 height, the buffer will have to be very big.
Splitting the text into several UILabels (e.g. by paragraph) would definitely be an improvement.
See https://stackoverflow.com/a/1494496/669586

A: I ran into this same issue with UITextViews, and came up with a fairly effective solution.
If you'd like to see it, check out my answer here!:
https://stackoverflow.com/a/37147533/2155673
It should be fairly easily to adapt for UILabels.


text:
Q: Fredo and Array Update in python I will have an interview with a company which like the hackerearth.com. I don't know how to work and doing the code perfectly. Could you help me with the following example?
This is the example for the .hackerearth.com, however, I don't know that I should consider the constraint in the code? can I use a package like NumPy? or I should only use the basic calculation with my self? Could you check my response and let me know the problem with that? Thank you so much
Input Format:
First line of input consists of an integer N denoting the number of elements in the array A.
Second line consists of N space separated integers denoting the array elements.
Output Format:
The only line of output consists of the value of x.
Input Constraints:
1<N<100
1<A[i]<100
explanation:
An initial sum of array is 1+2+3+4+5=15
When we update all elements to 4, the sum of array which is greater than 15 .
Note that if we had updated the array elements to 3,  which is not greater than 15 . So, 4 is the minimum value to which array elements need to be updated.
# Write your code here
import numpy as np
A= [1, 2, 3,4,5]

for i in range(1, max(A)+1):
    old = sum(A)
    new = sum(i*np.ones(len(A)))

    diff = new-old
    if diff>0:
        print(i)
        break

A: You don't need numpy or looping for this. Get the average of the array elements, then get the next higher integer from this.
N = 5
A = [1, 2, 3, 4, 5]
total = sum(A)
avg = A/N # not checking for zero-divide because conditions say N > 1
x = floor(avg + 1)
print(x)

Adding 1 is necessary to make the new sum greater than the original sum when the average is an exact integer (e.g. 15/5 == 3).

A: Well this isn't Code Review stack exchange, but:

*

*You don't say how to calculate x. It seems to be something to do with finding an average value, but no-one can judge your code without know what it's trying to do. A web search suggests it is this:

Fredo is assigned a new task today. He is given an array A containing N integers. His task is to update all elements of array to some minimum value x , that is, ; such that sum of this new array is strictly greater than the sum of the initial array. Note that x should be as minimum as possible such that sum of the new array is greater than the sum of the initial array.

*

*Given that the task starts by accepting input, it's important that your program does this part.

N = int(input()) # you can put a prompt string in here, but may conflict with limited output
A = list(map(int,input().split()))
# might need input checks
# might need range checks
# might check that A has exactly N values

*

*you don't need to recalculate old = sum(A) every time around your search loop

*calculation of new doesn't need a sum at all - it's just new = i * len(A)

*there's no point in checking values of i at or below min(A)

*your search will fail if all values of A are the same (try it), because you never look above max(A)
These remarks apply to your approach; a more efficient search would be binary chop, and there is also a mathematical way to go straight to the answer from sum(A) without any searching:
x = sum(A) // len(A) + 1


text:
Q: Merge Dictionaries with different TimeStamp Data1:
    Time                Header  Header  Header  Header
    2015-08-01 07:00    14.4    14.4    14.4    68
    2015-08-01 07:01    14.4    14.4    14.4    68
    2015-08-01 07:01    14.4    14.4    14.4    68

Data2:
Time        Header  Header  Header  Header  Header
07:00       34      31      37      51      72
07:02       32      31      17      56      12

I'd like to merge those two files so I get the output:
    Time                Header  Header  Header  Header Header  Header  Header   Header  Header
    2015-08-01 07:00    14.4    14.4    14.4    68     34       31      37      51      72

if there's no reference file for the timestamp I need only the Data1 one Line in the field so:
           Time                Header  Header  Header  Header Header  Header  Header    Header  Header
    2015-08-01 07:00    14.4    14.4    14.4    68     34       31      37      51      72
    2015-08-01 07:01    14.4    14.4    14.4    68
    2015-08-01 07:02    14.4    14.4    14.4    68     32       31      17      56      12

The Data2 File is a reference File, with entries every 15 Minute while the Data 1 File has one File every Minute. For plotting purposes I want to add the reference file into the Data File. So I guess what I'm looking for is how to check only the %H:%M Part of the Timestamp and do the merge.
I tried the following: There are more Data1 and Data2 files in the Folder so the first thing I did, was looking for a Data1 File and a Data2 file that match (Datewise) and  put them in a File ---> Then I made a Dictionary out of it
for data1files in Data1_List:
with open(files) as csv_files:
    reader = csv.reader(csv_files, dialect='excel-tab')
    header_1 = next(csr_reader)
    for rows in csr_reader:
        k=rows[0]
        v=rows[1:4]
        Data1Dict[k]=v

same for the Reference File Data2:
for data2files in Data2_List:
with open(data2files) as csv_files:
    csr_reader = csv.reader(csv_files, dialect='excel-tab')
    header_2 = next(csr_reader)
    for rows in csr_reader:
        k=rows[0]
        v=rows[1:5]
        Data2Dict[k]=v

so The Keys in both Dictionary is the the first row: In Data1 it is 2015-08-01 07:00 and in Data2 it is 07:00. Is there a cool way to compare those two Keys in order to merge the Date from the reference file on the right timestamps

A: This
merge_d = {d1k: d1v+Data2Dict.get(d1k[-5:]) for d1k,d1v in Data1Dict.items()
           if d1k[-5:] in Data2Dict }

is a dictionary with the values merged.
For example with:
Data1Dict = {'2015-08-01 07:00': ['14.4', '14.4', '14.4', '68'],
             '2015-08-01 08:00': ['15.4', '15.4', '15.4', '69']}

Data2Dict = {'07:00': ['34', '31', '37'],
             '08:00': ['38', '38', '39']}

it produces
{'2015-08-01 07:00': ['14.4', '14.4', '14.4', '68', '34', '31', '37'],
 '2015-08-01 08:00': ['15.4', '15.4', '15.4', '69', '38', '38', '39']}

Note: it's a brutal hard-coded solution which assumes the time has a positional and fixed representation (i.e. always hh:mm and always in the same place).
EDIT after further details were added
In case there may be no corresponding time in Data2Dict (i.e. the Data1 sequence has a higher sampling frequency than Data2) things are even easier:
merge_d = {d1k: d1v+Data2Dict.get(d1k[-5:],[]) for d1k,d1v in Data1Dict.items() }

with an input of
Data1Dict = {'2015-08-01 07:00': ['14.4', '14.4', '14.4', '68'],
             '2015-08-01 07:01': ['12.2', '12.3', '12.4', '99'],
             '2015-08-01 07:02': ['15.4', '15.4', '15.4', '69']}

Data2Dict = {'07:00': ['34', '31', '37'],
             '07:02': ['38', '38', '39']}

it produces
{'2015-08-01 07:00': ['14.4', '14.4', '14.4', '68', '34', '31', '37'],
 '2015-08-01 07:01': ['12.2', '12.3', '12.4', '99'],
 '2015-08-01 07:02': ['15.4', '15.4', '15.4', '69', '38', '38', '39']}


text:
Q: in scala what is cleaner code - to def (~member) versus pass function parameter? Which is cleaner?
def version
trait Foo {
  def db: DB
  def save() = db.save()
  def load() = db.load()
}

versus parametric version:
trait Foo {
  def save(db: DB) = db.save()
  def load(db: DB) = db.load()
}

*

*(left out intentionaly other parameters/members I want to focus on this one).

I have to say that when I look at complex projects I thank god when functions are taking all their dependencies in

*

*I can unit test them easily without overriding members, the functions tells me all that it's dependent upon on its signature.

*I don't have to read their internal code to understand better what the function does, I have its name, I have its input, I have its output all in function signature.

But I also noticed that in scala its very conventional to use the def version, and I have to say that this code when it comes bundled in complex projects such code is much less readable for me.  Am I  missing something?

A: I think in this case it highly depends on what the relationship is between Foo and DB.  Would it ever be the case that a single instance of Foo would use one DB for load and another for save?  If yes, then DB isn't really a dependency of Foo and the first example makes no sense.  But it seems to me that the answer is no, that if you call load with one DB, you'll be using the same DB when you call save.
In your first example, that information is encoded into the type system.  You're effectively letting the compiler do some correctness checking for you, since now you're enforcing at compile-time that for a single Foo, load and save will be called on the same DB (yes it's possible that db is a var, but that in itself is another issue).
Furthermore, it seems inevitable that you're just going to be passing around a DB every place you pass a Foo.  Suppose you have a function that uses Foo.  In the first example, your function would look like
def loadFoo(foo: Foo) {
  foo.load()
}

whereas in the second it would look like:
def loadFoo(foo: Foo, db: DB) {
  foo.load(db)
}

So all you've done is lengthened every function signature and opened up room for errors.
Lastly, I would argue that your points about unit testing and not needing to read a function's code are invalid.  In the first example, it's true that you can't see all of load's dependencies just by looking at the function signature.  But load is not an isolated function, it is a method that is part of a trait.  A method is not identical to a plain old function and they exist in the context of their defining trait.
In other words, you should not be thinking about unit testing the functions, but rather unit testing the trait.  They're a package deal and you should have no expectations that their behavior is independent of each other.  If you do want that kind of independance, than Foo should be an object which basically makes load and save static methods (although even then objects can have internal state, but that is far less idiomatic).
Plus, you can never really tell what a function is doing just by looking at its dependencies.  After all I could write a function:
def save(db: DB){
  throw new Exception("hello!!")
}


text:
Q: Elastic Potential Energy, Rubber, and Areas In a spring obeying Hooke's law, load and extension are proportional anyway, so whether you consider the elastic potential energy to be tha area under the F-x graph or the x-F graph, it doesn't matter, and this can be easily proved mathematically and intuitively (I mean, physics-wise).
However, in rubber (i.e. polymers), it matters, which area you choose. So on what basis do we decide that the elastic potential energy is $\int F dx$ and not $\int x dF$? Is it specifically because $\frac {dF}{dx}$ is the "spring constant" and then the value for the elastic potential energy is just a convention which could have easily been the opposite way round if Hooke's law was $x=kF$? Or is there a reason related to the kinetic energy produced after a polymer is released? Thanks.

A:
So on what basis do we decide that the elastic potential energy is $\int F\, dx$ and not $\int x\,dF$

$\int F\, dx$ is essentially the definition of work done on the polymer. You have to remember that the independent variable is $x$ and the load $F$ depends on $x$. It would not make sense for the integral to be the other way round.

Edit:
In a comment below my answer the OP has made a very important point about whether it is the force or the extension that is the dependent or independent variable. I know we are not dealing with springs in this question but lets just consider them for a moment:

The conventional way of plotting the results would be to have the force $F$ along the horizontal axis and the extension $x$ along the vertical axis (where the force is the independent variable) and this results in a change in the extension (which is the dependent variable). The graph shown below has extension on the horizontal axis and force on the vertical axis.

This is a departure from the convention because the gradient of the straight section of this graph turns out to be an important quantity known as the force constant $k$ and for a spring this is sometimes called the "spring constant".

So basically you were right to say what you mentioned in the comment. But I stand by what I said originally the integral really wouldn't make any sense the other way round. For a variable force it would be very difficult to integrate $\int x\,dF$ over infinitesimal $dF$. So we must have $\int F\,dx$ as extension $x$ is much easier to integrate over.

A: The definition of work done is $\int F\,dx$.

It just so happens that if force is proportional to extension, ie a graph of force against extension is a straight line through the origin, then $\int x \,dF$ will yield the same result as $\int F\,dx$.
Update as a result of some comments made by the OP.
Because work done is defined simply in words as the force times the distance moved in the direction of the force. So for a force that changes with position one takes the value of the force at a given position and then considers how much work is done by moving the force by a very small amount.
The force at the new position will be different and so one now repeats the process.
The result is that you need to do a summation or in the limit of infinitesimal steps, an integration $\int F\,dx$.
This is not the same noting that the position changes so choosing a position and multiplying that position by a change in the force $\int x\,dF$.
As I have noted it just so happens that for a particular situation the two integrals give the same result.
That is not so for your rubber.
The definition of work is useful to us because it ties in with energy conservation.
Of what use is $\int x\,dF$?

A: If we have a conservative force field $\vec{F}$, then we define the potential energy $U$ associated to it as : $$\Delta U=-W_\vec{F}$$
Work $W$ is defined in the differential form as: $$dW=\vec{F}.d\vec{r}$$or, in the case of one dimension only, $dW=F.dx$, ( and not $xdF$).
That's why $\Delta U=-\int{Fdx}$ and not the other way round.


text:
Q: truncate double value to 6 decimal places I was solving a problem which requires the output to be truncated and to my surprise I haven't been able to find a way to truncate numbers in java.
The output needs to be the a number followed by 6 decimal places.
What I want is
double truncate(double number,int places) and the output to be
truncate(14/3.0) = 4.666666.
but what I'm getting is
public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
  }
// rounds( 14/3.0 , 6 ) = 4.666667

With String.format I get
String.format("%.6f", 14/3.0) = 4.666667

I also tried a solution that I found on stackoverflow that suggested using BigDecimal and that gave me the very same answer.
NumberFormat also seems to work in the same way
java.text.NumberFormat f = java.text.NumberFormat.getNumberInstance();
f.setMinimumFractionDigits(6);
System.out.println(f.format(14/3.0)); // 4.666667

Is there a built in method that does this or do I need to write my own using something like BigInteger?
Is there something I'm doing wrong?

A: It's because you are not truncating but rounding:
long tmp = Math.round(value);

If you use a cast instead it should work:
long tmp = (long) value;

So the code below outputs 4.666666 as you expect:
public static void main(String[] args) throws Exception {
    System.out.println(truncate(14/3.0, 6));
}

public static double truncate(double value, int places) {
    if (places < 0) {
        throw new IllegalArgumentException();
    }

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = (long) value;
    return (double) tmp / factor;
}

A: Doubles don't have decimal places, ergo you can't truncate to any specific number of them. They have binary places. If you need a specific decimal representation, use DecimalFormat or BigDecimal.

A: The following piece of code helped me in restricting the number of decimal places (truncating) for a double value.
public static Double truncate (double valueToTruncate, int numberOfDecimalPlaces) {

if (valueToTruncate > 0) {
    return new BigDecimal(String.valueOf(valueToTruncate)).setScale(numberOfDecimalPlaces, BigDecimal.ROUND_FLOOR).doubleValue();
} else {
    return new BigDecimal(String.valueOf(valueToTruncate)).setScale(numberOfDecimalPlaces, BigDecimal.ROUND_CEILING).doubleValue();
}

}
Hope this helps someone :)


text:
Q: Pushing updates to specific users I've seen this technique used by Facebook, they have a join list feature which would allow certain users to receive the update version while other people would still be using the old version.
How is this possible to accomplish?

A: Rather than doing the inline approach, Facebook rolls out changes gradually across their server farm. Tech journalists and early adopters are provisioned onto the set of servers that receive the new updates first.

A: Simple way to achieve this:

*

*Mark old and new users with a Database Boolean flag.

*Check this condition and show different versions to old and new users.


text:
Q: Update two elements with two jquery .post responses There are two lists on the page: 'To buy' and 'Recently bought'. Each list can contain items. After clicking on an item the item is supposed to be removed from the original list and inserted into the other list.
It works for some items but sometimes I have to click twice to move the item. I assume there is something wrong with my makeactive and makeinactive functions but what and how would you recommend fixing it?
home.html

To buy:

{% csrf_token %}

{% for item in active %}

{{ item.name }}, id: {{ item.id }}

{% endfor %}

Recently bought:

{% for item in inactive %}

{{ item.name }}, id: {{ item.id }}

{% endfor %}

js
function makeinactive(){
    // changes item from active to inactive (item.active=True into False)
    id = this.id;
    console.log(id);
    var data = {'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()};
    URL =  id + '/switch/'
    $.post(URL, data, function(response){
        $('#recently_bought').html(response);
    });

    // updates the list of active items
    URL =  '/only_active/'
    $.post(URL, data, function(response){
        $('#only_active').html(response);
    });
}

function makeactive(){
    // changes item from inactive to active (item.active=False into True)
    id = this.id;
    console.log(id);
    var data = {'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()};
    URL =  id + '/switch2/'
    $.post(URL, data, function(response){
        $('#only_active').html(response);
    });

    // updates the list of recently bought items
    URL =  '/only_inactive/'
    $.post(URL, data, function(response){
        $('#recently_bought').html(response);
    });
}

$(document).on('click', '.active',  makeinactive);
$(document).on('click', '.inactive',  makeactive);

urls.py
urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^(?P<pk>[0-9]+)/switch/$', views.switch, name='switch'),
    url(r'^only_active/$', views.only_active, name='only_active'),
    url(r'^(?P<pk>[0-9]+)/switch2/$', views.switch2, name='switch2'),
    url(r'^only_inactive/$', views.only_inactive, name='only_inactive'),
]

views.py
def home(request):
    active = Item.objects.filter(active=True)
    inactive = Item.objects.filter(active=False)
    context = {'active': active, 'inactive': inactive}
    return render(request, 'tobuy/home.html', context)

def switch(request, pk=None):
    item = Item.objects.get(pk=pk)
    item.active = False
    item.save()
    inactive = Item.objects.filter(active=False)
    return render(request, 'tobuy/only_inactive.html', {'inactive': inactive})

def only_active(request):
    active = Item.objects.filter(active=True)
    return render(request, 'tobuy/only_active.html', {'active': active})

def switch2(request, pk=None):
    item = Item.objects.get(pk=pk)
    item.active = True
    item.save()
    active = Item.objects.filter(active=True)
    return render(request, 'tobuy/only_active.html', {'active': active})

def only_inactive(request):
    inactive = Item.objects.filter(active=False)
    return render(request, 'tobuy/only_inactive.html', {'inactive': inactive})

only_inactive.html
{% for item in inactive %}

{{ item.name }}, id: {{ item.id }}

{% endfor %}

only_active.html
{% for item in active %}

{{ item.name }}, id: {{ item.id }}

{% endfor %}

A: The below code fix the issue. I'm not entirely sure but probably due to delays I introduced (setTimeout).
myjs.js
function fill_recently_bought(data, textStatus, jgXHR)
{
   $('#recently_bought').html(data);
}

function fill_active(data, textStatus, jgXHR)
{
   $('#only_active').html(data);
}

function makeinactive()
{
    $(this).css('background-color', 'yellow').delay(500).hide(500);

    // changes item from active to inactive (item.active=True into False)
    $.ajax({
                type: "POST",
                url: this.id + '/switch/',
                data: {
                    'pk':  this.id,
                    'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
                },
                success: fill_recently_bought,
                dataType: 'html'
            });

    // updates the list of active items

    setTimeout(function(){
        $.ajax({
                type: "POST",
                url: '/only_active/',
                data: {
                    'pk':  this.id,
                    'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
                },
                success: fill_active,
                dataType: 'html'
            });
    }, 1000);
}

function makeactive()
{
    $(this).css('background-color', 'yellow').delay(500).hide(500);

    // changes item from inactive to active (item.active=False into True)
    $.ajax({
                type: "POST",
                url: this.id + '/switch2/',
                data: {
                    'pk':  this.id,
                    'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
                },
                success: fill_active,
                dataType: 'html'
            });

    // updates the list of active items

    setTimeout(function(){
        $.ajax({
                type: "POST",
                url: '/only_inactive/',
                data: {
                    'pk':  this.id,
                    'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
                },
                success: fill_recently_bought,
                dataType: 'html'
            });
    }, 1000);
}

function show_lists() {
    $('#lists').toggleClass('hidden');
}

// function formsubmit() {
//     alert('submituje2');
// }

$(document).on('click', '.active',  makeinactive);
$(document).on('click', '.inactive',  makeactive);
$(document).on('click', '#select_list',  show_lists);
// $(document).on('submit', '#new_user_form',  formsubmit);


text:
Q: Can SQL Server bcp in a file with Unix line endings? I'm trying to use the SQL Server bcp utility to import a text file from a samba share. bcp is choking on the Unix line endings. I'm sure I could add an intermediate step, either on Unix or Windows, to change the line endings to Windows-style. But I would prefer to import the files from Unix without modification.
Anybody know if there's a way to tell SQL Server bcp to look for Unix line endings?

A: have you tried to set the ROWTERMINATOR = '\n'?

A: You have to use a format file with bcp and specify the terminator as \n. The interactive command line will always append \r, where a format file will use exactly what you specify. Reference http://www.eggheadcafe.com/software/aspnet/32239836/bcp-out-with-char10-as-row-terminator.aspx.
Creating a format file is explained pretty well in BOL but comment/update your original post if you need help.

A: I don't think you can do this from the bcp command line.  But, I think the following SQL version will work.
DECLARE @Command nvarchar(1000)

SET @Command = N'BULK INSERT MyTable
FROM ''<path\file>''
WITH (ROWTERMINATOR = '''+CHAR(10)+''')'

exec sp_executeSQL @Command

A: The simple answer is to use hex, as was mentioned in one of the comments, as the row terminator:
-r 0x0a

A: Alternative solution by presenting process output as file
There is an other convenient way to solve this. My solution is good if you want to upload a simple CSV, for more complex cases write a format file.
Using hex code for linefeed (-r 0x0a) would be also convenient, but it did not work for me for BCP version 17.6.0001.1 on Ubuntu 18.04.
So I used a little trick instead:
Replace unix line-endings with sed, and present its output stream as a file. The relevant part of the code:
<(< iris.csv sed 's/\r*$/\r/')

As you can below see the output of sed is presented as a file:
ls <(< iris.csv sed 's/\r*$/\r/')

output:
/proc/self/fd/11

A whole example
I have the iris.csv in the working directory:
>  head -n 5 iris.csv
sepal_length,sepal_width,petal_length,petal_width,species
5.1,3.5,1.4,0.2,setosa
4.9,3.0,1.4,0.2,setosa
4.7,3.2,1.3,0.2,setosa
4.6,3.1,1.5,0.2,setosa

I can load into MS SQL using bcp like this:
query=$(cat << EOF
IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='iris' and xtype='U')
    CREATE TABLE iris (
        sepal_length FLOAT NOT NULL,
        sepal_width  FLOAT NOT NULL,
        petal_length FLOAT NOT NULL,
        petal_width  FLOAT NOT NULL
    )
GO
EOF
)

sqlcmd \
    -S localhost,31433 \
    -E \
    -d "testdb" \
    -Q "$query"

bcp \
    iris in <(< iris.csv sed 's/\r*$/\r/') \
    -S localhost,31433 \
    -T \
    -d "testdb" \
    -n \
    -t ","

Notice

*

*presenting process output stream as a file with this syntax is a bashism so will not work with some other shells such as dash. It will work with zsh

*I used windows integrated authentication for AD, yes on Linux which can do this with kerberos. Thats why the -E flag for sqlcmd and the -T flag for bcp.

A: If you don't have a lot of time to study bcp in great detail, check out this one:
http://msdn.microsoft.com/en-us/library/ms190759.aspx
It will give you easy example, explain what interactive prompts mean, option to save format once you are done (if you are going to do this repeatedly) etc. etc.
If your data is big and/or you have several filds you'd like, you can make a table first then do a little trial export (bcp will take a simple select as first arg) and still pick formats interactively, column by column. You can dig into saved fmt file latter if you have some extra reason for that.

A: Yes, this is maddening. My understanding is that SQL Server bcp ALWAYS inserts a \r before whatever line terminator you would expect to be used. So, if you don't use -r, you would expect it to use \n only. But it doesn't...it stupidly inserts \r so that it can use \r\n. If you specify -r \r\n then it still won't work; I suspect because it now wants \r\r\n line ends. This is all the work of some idiot coding for the Windows world trying to make life easier for beginners and ending up making things nigh on impossible for everyone else. I experienced this problem when transferring files from Sybase to SQL server and the solution was to specify -r \r\n in the bcp out from Sybase (which works exactly as you ask it to!) and -r \n (or just don't use -r) for the SQL Server bcp in.


text:
Q: Boot console overscan on HiDPI I have a HiDPI screen: the boot console has the native resolution, so it's extremely tiny, almost unreadable. I can "zoom" it by passing (in my case) video=1280x800 BUT there is an overscan I can't get rid of. Passing video=1280x800m rather than video=1280x800,margin_bottom=<a value in pixels> doesn't change absolutely anything.
Is there an effective way to get rid of the overscan?


text:
Q: Python & translucent canvas I'm looking for a way to draw real translucent lines with pygtk or wxPython, I now this is not possible with TKinter (I like this one because its already there). Also, I already now I can do this using PIL, but I want to draw direct to a canvas and it will be a dinamic content so I think using PIL will be a slow solution (and not elegant). Someone know a way to do this? Or maybe another toolkit that allows me to do this.
To get clear what I want is: If I drew lines with distinct colors that overlaps I need to be able to see both lines with a merged color at the intersection. Something like if the color I choose for the pen have a transparence instead of solid color.
Thanks.

A: Pretty much all "canvas" libraries have brushes with alpha.

*

*PyGTK has the gtk.DrawingArea, often used with cairo.

*Cairo can be used with wxPython as well.

*QT has the Graphics View Framework.


text:
Q: Ruby understanding multithreading I'm trying to multithread loop in ruby following this exmaple: http://t-a-w.blogspot.com/2010/05/very-simple-parallelization-with-ruby.html.
I copied that coded and wrote this:
module Enumerable

    def ignore_exception
        begin
            yield
        rescue Exception => e
            STDERR.puts e.message
        end
    end
    def in_parallel(n)
        t_queue = Queue.new
        threads = (1..n).map {
            Thread.new{
                while x = t_queue.deq
                    ignore_exception{ yield(x[0]) }
                end
            }
        }
        each{|x| t_queue << [x]}
        n.times{ t_queue << nil }
        threads.each{|t|
            t.join
            unless t[:out].nil?
                puts t[:out]
            end
        }
    end
end

ids.in_parallel(10){ |id|
 conn = open_conn(loc)
 out = conn.getData(id)
 Thread.current[:out] = out
}

The way I understand it is that it will dequeue 10 items at a time, process the block in the loop per id and join the 10 threads at the end, and repeat until finished. After running this code I get different results sometimes, especially if the size of my ids is less then 10, and I am confused why this is occuring.  Half the time it will not output anything for upto half the ids, even though I can check on server side that output for those ids exists. For example if the correct output is "Got id 1" and "Got id 2", it will only print out {"Got id 1"} or {"Got id 2"} or {"Got id 1", "Got id 2"}. My question is that is that is my understanding of this code correct?

A: The issue in my code was the open_conn() function call, which was not thread safe. I fixed the issue by synchronizing around getting the connection handle:
connLock = Mutex.new
ids.in_parallel(10){ |id|
 conn = nil
 connLock.synchronize {
    conn = open_conn(loc)
 }
 out = conn.getData(id)
 Thread.current[:out] = out
}

Also should use http://peach.rubyforge.org/  for the loop parallelization by using:
 ids.peach(10){ |id| ... }


text:
Q: Is a columnstore index appropriate when all columns are (mostly) unique? I have a longish table ( 60M rows ) where there are only 7 columns. One is a unique ID, two are datetimes, and two are notes and descriptions.
There the notes and descriptions are very regular, except for a tag at the end of the text. So, they're technically unique. I can't take that unique tag out as the tags are signatures and these notes and descriptions are legal documents.
If it wasn't for those tags, they'd be 95% from stock descriptions - maybe 15 variations.
These descriptions are up to 8K chars long. I long for some reasonable compression, and am considering a clustered columnstore index to implement that compression, but I'm unclear as to whether the compression will even occur w/ these columns being tagged into uniqueness.
These descriptive columns comprise more than 90% of the row data.
So...rowstore indexing is appropriate for the 'key' column...but I'm wondering if I should define this after the clustered columnstore index.
Current:
create table dbo.SPECIMEN
(
  ID                        int not null,
  Specimen_Types            varchar(255) null,
  Collected_Date            datetime null,
  Received_Date             datetime null,
  Results                   varchar(4000) null,
  Notes                     varchar(max) null,
  Lab_Report_ID             int not null
)
go
create clustered index [SPECIMEN.ID.Lab_Report_ID.Fake.PrimaryKey]
on dbo.SPECIMEN(ID,Lab_Report_ID);
go
create index [SPECIMEN.Lab_Report_ID.Index]
on dbo.SPECIMEN(Lab_Report_ID);

...and I if I get good compression, I'd change the indexes this way:
go
create clustered columnstore index [SPECIMEN.CCI]
on dbo.SPECIMEN;
go
create index [SPECIMEN.ID.Lab_Report_ID.Fake.PrimaryKey]
on dbo.SPECIMEN(ID,Lab_Report_ID);
go
create index [SPECIMEN.Lab_Report_ID.Index]
on dbo.SPECIMEN(Lab_Report_ID);

Does this make sense? I have very little experience with columnstore indexing and don't want to step on my own foot.
BTW - fake primary key. It is supposed to be unique, but the app that populates the source data occasionally throws in a duplicate. This table is supposed to be an extract from that semi-stable source.


text:
Q: Use Domain in Expressjs 4 for NodeJs In expressjs 3 I could do
var port        = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var domain      = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";

http.createServer(app).listen(port, domain);

in express4
var server = app.listen(app.get(port), function()

how do you add domain in expressjs4

A: Express 4 almost follows the same thing:
var port        = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var domain      = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";

var express = require('express');
var app = express();

app.listen(port, domain);


text:
Q: Listen to chrome extension installation in app How can I listen/track when chrome extension is installed from the web store?
I previously had an inline installation of the extension but by inline installations coming to an end soon, I want the user action to open the web store to install the extension and listen for when they add the extension for UI changes and act based on that.
I tried the messaging approach found in here but it seems not working.
manifest.json looks like:
   "background": {
     "scripts":["index.js"],
     "persistent": false
   },
   "permissions": ["desktopCapture"],
   "externally_connectable": {
        "matches": [
            "*://localhost:*/*",
         "https://*.stageten.tv/*"
        ]
    }

and index.js :
chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
      if (request === screenShareExtensionId) {
          if (request.message) {
              if (request.message == "version") {
                  sendResponse({version: 1.0})
                  alert('Hiiii')
              }
          }
      }
      return true;
  })

and inside my app:
chrome.runtime.sendMessage(screenShareExtensionId, { message: "version" },
    function (reply) {
        if (reply) {
            if (reply.version) {
              return true;
            }
        }
        else {
          return false;
        }
    })

and based on the value in my redux logic, the UI either changes or not/waits for the extension to get installed.

A: You can do it at the start of your background page.
You need to save a flag (for example, it can be a version of the extension) to the localStorage.
After that, on each start of the background page, you need to check if this flag is in your storage. If there is no flag - then you need to track install, otherwise, it's just usual reload of the background page.
The same way can be used to track updates of the extension from the store, just need to compare versions.

A: Solved this this in this self-answered question, which I can't mark as a duplicate of this because of no accepted/up votes.

Here's how I solved it from the background script (w/o using a content script):
background.js

*

*Listen for onInstalled event.

*Query all opened tabs that match the URL's you want to notify.

*Execute a small script in each tab that will postMessage notifying
that installation was succesful.

chrome.runtime.onInstalled.addListener(function listener(details) {
  if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) {
    chrome.tabs.query({
      url: [
        'https://localhost:3000/*',
        'https://staging.foo.com/*',
        'https://production.foo.com/*'
      ]
    }, tabs => {
      Array.from(tabs).forEach(tab => {
        chrome.tabs.executeScript(tab.id, {
          code: `window.postMessage('screenshare-ext-installed', window.origin);`
        });
      });
    });

    chrome.runtime.onInstalled.removeListener(listener);
  }
});

manifest.json
Just make sure both externally_connectable and permissions declare
the URL patterns of the sites you want to notify.
"externally_connectable": {
    "matches": [
    "https://localhost:3000/*",
    "https://staging.foo.com/*",
    "https://production.foo.com/*"
  ]
},
"permissions": [
  "desktopCapture",
  "https://localhost:3000/*",
  "https://staging.foo.com/*",
  "https://production.foo.com/*"
],

Web page
Just listen somewhere for the postMessage message fired by
the extension on succesful installation.
window.onmessage = e => {
  if (e.data === 'screenshare-ext-installed') {
    // extension successfully installed
    startScreenShare()
  }
}

Credits

*

*@wOxxOm's comment


text:
Q: OpenGL ES 2.0 Shader - 2D Radial Gradient in Polygon I am trying to paint a radial gradient inside a Polygon. My Stage is 600x320. I am able to draw a gradient but it`s 'distorted/streched'. The goal is a gradient like a light would produce.
u_lightPosition is passed as a relative value: {0.5, 0.5}.
Currently unused lightPositionAbsolute is passed in as absolute value {300.0, 160.0}.
My fragment-shader currently looks like this:
#ifdef GL_ES
precision lowp float;
#endif
varying vec4 v_fragmentColor;

uniform vec2 u_lightPosition;
uniform vec2 u_lightPositionAbsolute;
uniform vec4 u_outerColor;
uniform vec4 u_innerColor;
uniform float u_radius;

void main()
{
    vec2 resolution = vec2(600,320);
    vec2 position = ( gl_FragCoord.xy / resolution.xy );

    float distanceFromLight = length(position - u_lightPosition);

    gl_FragColor = mix(u_outerColor, u_innerColor, distanceFromLight);
}

With a circle Polygon this results in:

A: Ok i found the solution which now that it works is quiet obvious. I worked with relative values opposed to absolute ones which resulted in the stretching. The shader now looks like this:
#ifdef GL_ES
precision lowp float;
#endif
uniform vec2 u_lightPosition;
uniform float u_radius;

void main()
{
    float distance  = length( u_lightPosition - gl_FragCoord.xy );
    float intensity = 1.0 - min( distance, u_radius )/u_radius;

    gl_FragColor = vec4(intensity, intensity, intensity, 1.0);
}

Edit: Changed the falloff of the 'light':
#ifdef GL_ES
precision lowp float;
#endif
uniform vec2 u_lightPosition;
uniform float u_radius;

void main()
{
    float distance  = length( u_lightPosition - gl_FragCoord.xy );

    float maxDistance = pow( u_radius, 0.23);
    float quadDistance = pow( distance, 0.23);

    float quadIntensity = 1.0 - min( quadDistance, maxDistance )/maxDistance;

    gl_FragColor = vec4(quadIntensity, quadIntensity, quadIntensity, 1.0);
}

A: I believe that your shader is just fine, your problem is most likely in the geometry (or in the vertex shader).
I have created an example of your shader in the KickJS GLSL editor, where you can see it works just fine:
http://goo.gl/viDKB
You can change the type of mesh under settings.

A: You are passing radius as float so x & y are the same but they shouldnt be.
ie. screen : 1280 x 800 , radius 300 = {300.0/1280.0,300.0/800.0 }
"float u_radiusX = (100.0/1280.0);\n"+
"float u_radiusY = (100.0/800.0);\n"+
"float distanceFromLightX  =  length(v_lightPos.x   - v_Pos.x );\n"+
"float distanceFromLightY  =  length(v_lightPos.y   - v_Pos.y );\n"+
"float quadIntensityX = (1.0-min(distanceFromLightX,u_radiusX)/u_radiusX);\n"+
"float quadIntensityY = (1.0-min(distanceFromLightY,u_radiusY)/u_radiusY);\n"+
//finally
"float quadIntensity = quadIntensityX*quadIntensityY;\n"+
"gl_FragColor = vec4(color.r*quadIntensity, color.g*quadIntensity, color.b*quadIntensity, 1.0);\n"

I got this working this way. , where v_Pos is attribute position ( NOT the light position )  * matrix passed via variable from previous shader.


text:
Q: List of checkboxes not getting selected I have a checkbok as selectAll
Select All
<input class="all-select" type="checkbox" value="" name="">

i also have a list of friends with a checkbox each which is populated dynamically.

Name

Email
        <input name="" type="checkbox" value="" class="chk-box">

.....

when i click the select all checkbox, then all the checkboxes of my list should get selected, the javascript code for which is given below :
$("#slide_top_pop").on("click", ".all-select", function (event) {
    if ($(this).is(':checked')) {
        $('input.chk-box').attr('checked', true);
    } else {
        $('input.chk-box').attr('checked', false);
    }
});

Now the problem is this that when i first time select the Select All check box then the list get selected but when i unchecked it and check again then the list is not selected  and when i tried to verify it on Mozilla what is the checked property(attribute) for the list then i get this :
 <input class="chk-box" type="checkbox" value="" name="" checked="checked">

which says that the checkbox is selected but i cant see the selected tick in the list.
I dont understand what the problem is .
any solution is appreciated thanks.

A: Use .prop() instead of .attr() like:
$("#slide_top_pop").on("click", ".all-select", function (e) {
    $('input.chk-box').prop('checked', this.checked);
});


text:
Q: is there anyway to extract numerical values (or equivalently eliminate the text) of CSV so that the numerical values can be used as a regular feature how to clean all numerical features and the target variable price so that they can be used in training algorithms. For instance, host_response_rate feature is in object format containing both numerical values and text.

A: You should elaborate, But from what i understand you want to convert
Object to integer
You could try:
df['column'].astype(str).astype(int)


text:
Q: How to replace a String of text from a text file with an ArrayList from user input I have a text file "test.txt" in which I store student details such as I.D number and course taken.
I want new students to be added immediately before the line that with "LASTSTUDENTEENTRYLINE".
The problem I have is that I'm collecting the student details in an array list called "objectInputFieldsList". I've been trying to replace "LASTSTUDENTEENTRYLINE" with "objectInputFieldsList" + "LASTSTUDENTEENTRYLINE".
The problem is that the two don't mix – one is an array list and the other a string. The array list contains input from text field values from users.
How can I approach this successfully and replace LASTSTUDENTEENTRYLINE  with "objectInputFieldsList" + "LASTSTUDENTEENTRYLINE" ?
Thank you all so much in advance.
Here's what I've been trying so far:
Sample text file before update:
123 | Oliver | Muchai
456 | Revilo | Chamu
LASTSTUDENTEENTRYLINENNAMES

Classes | 123 | English
Classes | 456 | Bilogy
LASTSTUDENTEENTRYLINENSUBJECTS

After an update with a new user the text file should look as:
123 | Oliver | Muchai
456 | Revilo | Chamu
678 | Eddys | Rockery
LASTSTUDENTEENTRYLINENNAMES

Classes | 123 | English
Classes | 456 | Biology
Classes | 678 | Kiswahili
LASTSTUDENTEENTRYLINENSUBJECTS

The Code:
        // The ArrayList called from the class that gets the user input from the JTextFields
        AddNewClientSaveAction save = new AddNewClientSaveAction();
        StringBuffer sb = new StringBuffer();

        String lastNames = "LASTSTUDENTEENTRYLINENNAMES ";
        String lastSubject = "LASTSTUDENTEENTRYLINENSUBJECTS";

        String textToEdit1 = lastNames;
        int cnt1 = sb.indexOf(textToEdit1);
        String replacementString1 = "\n" + save + "\n" + lastNames;
        sb.replace(cnt1,cnt1+textToEdit1.length(), replacementString1);

A: Since it is a Java ArrayList, you can use the ArrayList#add(int index, E element) method to insert an element at a specified position in the list.
Use as index the index before the element that contains your end of line "lastName".
This solution in case you want to add the string inside the ArrayList.

A: This is not a complete or full solution, but an example of a concept
This assumes that you are reading all the text from the to start with...life would substantially more difficult if you're not.
This basically uses StringBuilder#indexOf to find the index point where are particular String literal exists.  In this example, we're only looking for LASTSTUDENTEENTRYLINENNAMES, but should get the idea...
From there, for each new record line, we create a temporary String to be inserted and then insert this before the previous obtained index point....
Now.  It wouldn't be a difficult thing to add in the subjects as well...
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileUpdate {

    public static final String LAST_STUDENT_LINE = "LASTSTUDENTEENTRYLINENNAMES";

    public static void main(String[] args) {

        StringBuilder sb = new StringBuilder(128);
        List<Student> objectInputFieldsList = new ArrayList<>(25);
        objectInputFieldsList.add(new Student(128, "Banana", "Pajamas"));

        BufferedReader br = null;
        try {

            br = new BufferedReader(new FileReader("test.txt"));
            String text = null;
            while ((text = br.readLine()) != null) {
                if (sb.length() > 0) {
                    sb.append("\n");
                }
                sb.append(text);
            }

            System.out.println("Before");
            System.out.println(sb);

            for (Student s : objectInputFieldsList) {

                int insertIndex = sb.indexOf(LAST_STUDENT_LINE);
                StringBuilder line = new StringBuilder(128);
                line.append(s.getId()).append(" | ").append(s.getFirstName()).append(" | ").append(s.getLastName()).append("\n");
                sb.insert(insertIndex, line.toString());

                // Find subject mark and add the students subjects in as well...

            }

            System.out.println("\nAfter");
            System.out.println(sb);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException exp) {
            }
        }

    }

    public static class Student {

        private int id;
        private String firstName;
        private String lastName;

        public Student(int id, String firstName, String lastName) {
            this.id = id;
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public int getId() {
            return id;
        }

        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }
    }
}

This outputs...
Before
123 | Oliver | Muchai
456 | Revilo | Chamu
LASTSTUDENTEENTRYLINENNAMES

Classes | 123 | English
Classes | 456 | Bilogy
LASTSTUDENTEENTRYLINENSUBJECTS

After
123 | Oliver | Muchai
456 | Revilo | Chamu
128 | Banana | Pajamas
LASTSTUDENTEENTRYLINENNAMES

Classes | 123 | English
Classes | 456 | Bilogy
LASTSTUDENTEENTRYLINENSUBJECTS

Now...Having done all that...
I'd recommend using a single user database, something like H2 for example, or even XML, which would have to be significantly easier and lot less messy in the long wrong - IMHO

A: If I understood you right, you want to write new Student into your "test.txt" before "LATSTUDENTTEENTRYLINE".
First put your whole txt into a StringBuffer, because than your able to write at a special index.
Use
sb.getIndexOf("LASTSTUDENTEENTRYLINE");

and get the size of your string you want to add
String line = "Student | foo | bar";
int index = line.length();

now you have to write the line at
sb.getIndexOf("LASTSTUDENTTEENTRYLINE") - index;

in your StringBuffer.
At the end you write the whole StringBuffer to the txt.
Maybe you have to put at your line
+ "\n"

to make a new line so it looks better in the txt


text:
Q: Determining a cache key for a generic service search method I'm building a website and I'm starting with the Domain/DAL/whatever-you-want to-call-it layer and have gone with a model/repository/service structure. I have created generic repository base class which takes care of all my CRUD functionality. I also have a generic service which for now is just a wrapper around the repository but also takes care of caching.
The problem I have is that my repository has a GetWhere method which takes a predicate that allows me to grab my entities based on certain criteria. This seemed like quite a common approach when I was doing my research. The service also takes this predicate and will then pass it through to the repository.
The problem I have is that inside the service method, I need to come up with a cache key that is based off what is being searched for in the predicate but I'm not sure how this is done or even if I can get this information at this stage.
Here is my code.
Repository method:
public IQueryable<T> GetWhere(Expression<Func<T, bool>> predicate)
{
    return Context.Set<T>().Where(predicate);
}

Service method:
public IQueryable<T> GetWhere(Expression<Func<T, bool>> predicate)
{
    var cacheKey = "Football." + predicate.Parameters[0].Type.Name + "." + ???;
    var result = cache.Get(cacheKey, () =>
    {
        var dbResult = repository.GetWhere(predicate);
        return dbResult;
    });
    return result;
}

So what I need is to know what to put in place of the "???" so that I can create a cache key that represents what I'm trying to retrieve so that if I call my service method something like this:
teamService.GetWhere(x => x.Name.Contains("Test"));

...I get a cache key something like "Football.Team.Name.Test" or something.
Please let me know if I am approaching this the wrong way, I feel like I might be.


text:
Q: Vuetify Set Toolbar and navigation drawer simultaneously I want to set navigation drawer alone with toolbar and toggle drawer from toolbar.
Code:
<v-navigation-drawer absolute temporary left v-model="drawer">
      <v-list-item-title class="text-h6"> </v-list-item-title>
      <v-list nav dense>
        <div v-for="(link, i) in links" :key="i">
          <v-list-item v-if="!link.subLinks" :to="link.to" class="v-list-item">
            <v-list-item-icon>
              <v-icon>{{ link.icon }}</v-icon>
            </v-list-item-icon>

            <v-list-item-title v-text="link.text" class="subtitle-2" />
          </v-list-item>

          <v-list-group
            v-else
            :key="link.text"
            no-action
            :prepend-icon="link.icon"
            :value="false"
          >
            <template v-slot:activator>
              <v-list-item-title>{{ link.text }}</v-list-item-title>
            </template>

            <v-list-item
              v-for="sublink in link.subLinks"
              :to="sublink.to"
              :key="sublink.text"
            >
              <v-list-item-icon>
                <v-icon>{{ sublink.icon }}</v-icon>
              </v-list-item-icon>
              <v-list-item-title class="subtitle-2">{{ sublink.text }}</v-list-item-title>
            </v-list-item>
          </v-list-group>
        </div>
    </v-list>
 </v-navigation-drawer>
<v-toolbar color="primary" right @click.stop="drawer = !drawer">
  <v-app-bar-nav-icon @click.stop="drawer = !drawer"></v-app-bar-nav-icon>
  <v-spacer></v-spacer>
</v-toolbar>

As you can see I have set both navigation-drawer and toolbar.
Currently:

Expected:

A: *

*Replace the v-toolbar with v-app-bar

*Add app clipped-left props to v-app-bar

*Remove absolute temporary props from the drawer

*Add app clipped fixed props to the drawer


text:
Q: Check If a Number Is Right-Truncatable Prime i wrote this program to check if a prime number exists but it doesn't seem to work. i'm pretty new at this but i thought that checking if a number is prime and if by eliminating the last figure you still obtain a prime number. can anyone help me?
#include <stdio.h>
#include <math.h>

int main(int argc, char * argv[]){
    int n, b;
    int power;
    int temp;
    int prime=1;
    int i,j;

    do{
        printf("insert positive number:\n");
        scanf("%d", &n);
    }while(n<=0);

    power=1;

    while(n>10){

        temp=n/10;
        power++;
    }
    for(j=power;j>=0;j--){

        for(i=2;i<n/2;i++)
        {
            if(n%i==0){
                prime=0;
            }
        }
        n=n-(n/pow(10,pot));
    }

    printf("%d", prime);

    return 0;
}

A: Your primary loop should be somewhat similar to this:
while (n > 10) {
    n = n / 10;
    if (!check_prime(n)) {
        nrt_prime_flag = 1;
        break;
    }
}

where the check_prime() should check if the current n is prime or not, ie, it returns 0 if not prime.


text:
Q: Duplication of data on oracle sql report I am printing tablespace names in oracle but am facing duplicate data issue on the sqlplus console. Please share your thoughts if you know how to avoid this issue.
set heading on
set echo off
set feedback off trimspool on verify off
set lines 120
set pages 2000
prompt DATE
select sysdate from dual;
/
prompt
prompt
prompt =====================================
prompt            Tablespaces
prompt =====================================
break on report
select name from v$tablespace ;
/

clear break
clear compute

A: And as the docs say about "slash": https://docs.oracle.com/cd/E18283_01/server.112/e16604/ch_twelve004.htm

Executes the most recently executed SQL command or PL/SQL block which
  is stored in the SQL buffer.

So select name from v$tablespace ;is executed twice in your case


text:
Q: Grub cannot find Windows 10 I am dual booting windows 10 and ubuntu 17.04 on separate hard drives.  I had recently been running ubuntu 16.04, but I think an update screwed with X11, so I had to wipe it and start fresh.  Grub now cannot find Windows 10.  os-prober didn't work.  I ran boot-repair to get this log. How can I fix this?  All other solutions I have come across either suggest UEFI is not right, which the logs seem to suggest is not the case, or to run update-grub, which didn't work.

A: Your Windows is installed in UEFI-mode. Ubuntu has been installed in UEFI-mode too, but when you reinstalled Ubuntu you reinstalled Ubuntu in legacy-mode. You can still see the Ubuntu files in the ESP from your first install, but a look at fstab shows clearly that the current install is in legacy-mode (EFI-partition is not mounted!), also we can see that Grub is installed in the MBR of sdb.
You may use Boot-Repairs recommended repair to solve this, the important thing is, that you have to boot your installer in UEFI-mode to do that (look at line 791 in your log). When booting from USB you should have two options, on my machine it is something like USB2.0 or UEFI:USB2.0, the first option would boot in legacy mode, the latter in UEFI-mode.
Your mistake happened when you booted the installer to reinstall Ubuntu, remember: how you boot is how you install! If you boot the installer in legacy-mode, Ubuntu will be installed in legacy-mode, if you boot the installer in UEFI-mode, Ubuntu will be installed in UEFI-mode.
Even for the use of Boot-Repair we have to choose the correct boot-mode, as UEFI-features are not supported when we boot in legacy-mode. Your log shows, that you started in legacy-mode to run Boot-Repair, that is ok to create the log, but to reinstall Grub in UEFI-mode you have to run Boot-Repair in UEFI-mode!