text:
Q: Is the sentence "Queueing is so thoughtful of you." grammatically correct? In the following two blog posts ("Illiteracy in Singapore - the Land Transport Authority" and "LTA's illiterate poster") the author accused the poster depicted below of being evidence of illiteracy in Singapore, which I take to mean that there's something grammatically incorrect with it. How so?
The second post actually includes a bit of a response to this question, but his explanation is quite confusing. The blog poster said it had nothing to do with the singular verb, or "the issue of concord" in his words.
Anyone knowledgeable enough about grammar to decode this chunk of text?

What makes the sentence ungrammatical is its utter meaninglessness. Since the copulative verb links the subject and the subject complement, the introduction of an unrelated clause in lieu of the subject complement renders the sentence an absurdity that has no meaning. One cannot ignore the grammatical function of the copula, The addition of a prop or dummy subject is of course one possibility that is available to a writer in a sea of possible variations.

A: Nothing wrong with that sentence, 'Queueing' here is a gerund, essentially a noun.
https://en.oxforddictionaries.com/definition/gerund

A: I would somewhat tentatively say that the sentence on the sign is grammatical. My own intuitions don't seem to give an entirely clear answer, but other people's intuitions and usage seem to support this kind of sentence.
I think the objection to the sentence "Queueing is so thoughtful of you" is based on an objection to the use of the structure "[verb]ing is (so) [adjective] of [someone]" to express the idea "It is (so) [adjective] of [someone] to [verb]". The structure starting with a gerund does seem to be grammatical according to the judgements of at least one linguist, but it sounded a little strange to me when I first thought about the sentence in your question, so it may not feel entirely natural for all English speakers. ("Queueing is so thoughtful" sounds OK to me. So it seems to me that the issue, if there is one, would be with the use of the prepositional phrase "of you" after "thoughtful" in this context.)
I found the following apparently parallel examples marked as grammatical in Adjectives and adjective complement constructions in English, a dissertation by Arlene Berman (1973):

(28) a. Burning the papers was clever of you
      b. Bringing wine was thoughtful of Mary
      c. Continuing to harp on the subject was wrong of you

(p 230)
"Wise-type adjectives" (like "wise of you")
I was led to Berman's dissertation because it was referenced in a paper specifically about the class of adjectives that behave like this: "Wise-type Adjective Constructions and the Uniformity Condition", by Shin Oshima. I wasn't able to find any examples in Oshima's paper that seemed directly relevant to your question, but it has some useful terminology and examples of other constructions that make use of adjectives like this.
Berman's judgements of related constructions
I think to understand Berman's examples better, it will help to look at some of the other things she says about this type of adjective. Actually, Berman's section on adjectives with of-NP complements starts out with examples of extraposed sentences of the type that I feel entirely comfortable with (and that I assume any English speaker would feel entirely comfortable with):

(24) a. It was clever of you to burn the papers
      b. It was thoughtful of Mary to bring wine
      c. It was wrong of you to continue harping on the subject

(p. 229)
Berman points out that sentences like "*It was clever of Max for his sister to do that" and "*It was clever of Max for him to do that" are not grammatical (p. 229). (However, note that Oshima says the latter construction may be possible in some dialects.)
Berman also judges the following sentences unacceptable::

(27) a. *To burn the papers was clever of you
      b. *To bring wine was thoughtful of Mary
      c. *To keep harping on the subject was wrong of you

(28 is the acceptability judgements given above for sentences starting with a gerund)

(29) a. *It was clever of you burning the papers
      b. *It was thoughtful of Mary bringing wine
      c. *It was wrong of you continuing to harp on the subject

and suggests that "It seems reasonable to assume that sentences like (28) are derived from sentences like (27), when Extraposition fails to apply.5" (p. 230).
Endnote 5 says:

This sort of alternation seems to exist more generally. I find, for example, the following:

(i) It was easy for Joe to do that
    (ii) *To do that was easy for Joe
    (iii) Doing that was easy for Joe

Bare infinitives in subject position seem to be quite restricted, although they are not wholly impossible. I have not examined the conditions under which they are and are not acceptable.

(p. 252)
I agree with Berman that bare infinitives are not wholly impossible as subjects. I'm not sure that I agree with her judgement that "To do that was easy for Joe" is unacceptable.
Berman also lists a few restrictions that seem to her to apply to this kind of adjective. The first of the following restrictions seems more obviously correct to me than the second. Berman notes that

While other subject-embedding adjectives allow the noun phrases in their prepositional complement to be questioned and relativized, this is not possible with sentences like (24):

(37) a. To whom is it clear that Max is wrong
        b. the man to whom it is clear that Max was wrong
    (38) a. For whom is it easy to write a dissertation
        b. the man for whom it is easy to write a dissertation
    (39) a. *Of whom was it stupid to do that
        b. *the man of whom it was stupid to do that

(p 233)
Berman has no explanation for these acceptability judgements, but I fully agree with them.
The next judgement seems more iffy to me: Berman feels that

adjectives with of-NP complements do not allow Tough-movement:

(40) a. *That document was careless of Jeb to burn
        b. *That was stupid of you to do

(p 233)
I don't feel certain that these sentences are grammatical for me, but "That was stupid of you to do" doesn't immediately seem unacceptable to me either. I found an example of it on the Internet (I don't know if it was written by a native English speaker):

The pisces men I know/knew (March 13-18th babies) are all fragile ego, sensitive as shit dudes. Don't tell him he's not behaving like a man, his brows look bushy in a picture, that was stupid of you to do because then his whole ego is thrown off; he doesn't wanna play anymore and he's taking his ball home with him.

(comment by Peachyvision, Apr 30, 2015; #18 in the thread "So do pisces men like to get cussed out and called names?", discussion in 'The Lipstick Alley Psychic Hotline' started by StayMadBishes, Apr 30, 2015)
Contexts where it sounds OK to me to use a "wise-type adjective" without a following to-infinitive
For me, "[adjective] of you" definitely works without a following to-infinitive when the subject is one of the following pronouns:

*

*this or that (singular demonstratives)

*which (as a singular inanimate relative pronoun)
Examples:

*

*"That wasn't very nice of you."

*"This is so thoughtful of you!"

*"He helped me with my errands, which was thoughtful of him."
(It also sounds fine to me to use a quantifier before one of these pronouns, as in "All of this is very thoughtful of you.")
And it also sounds fine in exclamatory sentences with "How" at the start (I don't know enough syntax to know how these work):

*

*"How silly of me."

(In some cases, at least when there is a to-infinitive, the "how" can be left out in similar sentences: "How stupid of them to leave it behind!" "Silly of me to forget about that.")
(Also, I don't know if these could be taken to be short versions of "How silly of me that was" or "How silly (?it was) of me to do that")
Other examples I have found of wise-type adjectives used without a to-infinitive (taken from the Internet)

*

*I was able to find "worrying was silly of me" used in a blog post by someone who appears to be a native English speaker: "Internship Assignment A", Keep Calm and Study Abroad.

*"Everything you say about my time with Wade is thoughtful of you" (This was the only example of "is thoughtful of you" that I found on Google Books that didn't have "it", "this" or "that" as the subject)

*From Google as a whole (not Google Books) there are few more examples with a gerund:

*

*"I understand you desire to try something to save the birds, putting a a bell on her for that reason is thoughtful of you"

*"Being vague about a plot thats well know in the novel is thoughtful of you, even though theres no plot beyond what you describe"

*"Considering her feelings is thoughtful of you, but if it's truly the latter situation, go stay with your Dad until she realizes she needs to grow up and..."

*and from Google, a few with other nouns as the subject:

*

*"Very heartfelt, Willis, and the PS is thoughtful of you."

*"Editing is amazing and the music selection is thoughtful of you."
With a plural verb:

*

*"The flowers are very thoughtful of you."

*"The feelings you described regarding entrapment and suffocation are very perceptive of you." (This one sounds very strange to me; it's from an interview, so it probably was spoken spontaneously)

*"I know these things are silly of me to feel." (From some Instagram post; this one also sounds strange to me)
John Lawler's answer to How does the to infinitive work with adjectives like "wrong" and "wise"? provides the example

For me to go home that day was wise (of me).

where the infinitive precedes rather than follows, but I don't know if that is intended to be a grammatical example sentence, or just an ungrammatical illustration of the theorized underlying structure of "It was wise of me to go home that day." (Another example is "It was wise (of me) (for me) to go home that day", which as I mentioned above is ungrammatical for most speakers when both "of me" and "for me" are included.)
Lists of "wise-type" adjectives
Berman gives a short list of adjectives that take of-NP complements: clever, stupid, idiotic, careless, wrong, brilliant, kind, nice, thoughtful (from (23), on p. 229).
Oshima mentions most of these, as well as a few more like foolish, good, wise (from (1), on p. 12).
I found another source that mentions "wise-type" adjectives, the SAL Taxonomy for English Adjectives, but none of the related texts that I found mention the "V-ing is [adjective] of [N]" structure specifically:

*

*SAL Taxonomy for English Adjectives (PDF)

*SAL Adjective Narratives
This resource lists a number of other adjectives that act like "wise" and "thoughtful": audacious, astute, bestial, bold, brilliant, careless, childish, discriminatory, early, far-sighted, heroic, humane, impudent, intelligent, late, negligent, noble, perceptive, polite, provocative, reckless, rude, shrewd, undiplomatic, unprincipled
Works Cited
Berman, Arlene (1973). "Adjectives and Adjective Complement Con-      structions in English." Ph.D. dissertation, Harvard.
Oshima, Shin (1987). Wise-type Adjective Constructions and the Uniformity Condition." Kochi University Academic Research Report 36, Humanities

A: You have asked a thought-provoking question that shows your objective consideration of the author's opinions.
Although I am not at all well-versed with the technical terms that infest that author's paragraph, I am willing to interpret it as an objection to the use of a noun-clause "queuing and giving way to alighting passengers"  as a subject, which he calls 'unrelated' because nowhere does it refer to the actual subject 'you' -- which is probably an overly pedantic opinion.
A crude and simple breakdown of the quoted sentence in its full form (not extracting the gerund 'queueing' out of its clause)  would be [correct me if I am wrong]:

subject = queuing and giving way to alighting passengers (noun clause)
verb =  is (linking verb)
object [more accurately, a 'state of being' because of the use of a linking verb] = so thoughtful of you.

What's not to like? It does not seem to be ungrammatical.
I assume that the most technically correct form of the sentence would be

It is so thoughtful of you to be queueing and giving way to alighting passengers.

The sentence in question is is just a simple reversal of this  order:

(to be) queueing and giving way to alighting passengers is so thoughtful of you

and that by itself proves it is grammatical, the 'to be' having been dropped because implied and redundant --  but the author possibly thinks it is more correct [grammatical but non-standard, and sometimes an awkward construction] to say something that includes some form of 'you' in the subject clause, as for example:

Your queueing and giving way to alighting passengers is so thoughtful (of you)

which would certainly  avoid his pernicious if possibly technically correct accusation of 'unrelated clause': this is the type of sentence construction sometimes chosen by non-native speakers or in dialects like Indian English and Singapore English, and possibly reflects the syntax of regional languages. The author seems determined that some form of or reference to 'you' should appear in the noun clause to avoid any suspicion of illiteracy, but any native speaker of English here at ELU will tell you that the 'your' can be acceptably dropped in common usage to say

Queueing and giving way to alighting passengers is so thoughtful of you.

Calling it illiteracy is a very excessive objection IMHO.

A: The sentence is upbeat and friendly and grammatically correct. Compared to what I have seen in other Asian countries like misspelled English words on the backs of tee shirts and spelling and grammatical errors on instruction and safety signs, this billboard is written rather well. However, you said that one author accused the LTA of contributing to illiteracy in Singapore.
The reason it is difficult to understand what he is saying in his blog is that he is being too vague. From my understanding, he is talking about the link between the first part of the sentence, 'queueing and giving way to passengers' and the second part of the sentence, 'thoughtful of you', joined together by the copula (linking verb) 'is'. The first issue he has is not with the grammar, but with word choice. Thoughtful should be replaced with mindful.
thoughtful - absorbed in or involving thought
mindful - conscious or aware of something
We use thoughtful to described a situation where someone goes out of his way to do something in consideration of the feelings of others. We use mindful in a situation where someone is observing the rules or watching his manners. Therefore, because the LTA is addressing the need to observe the rules when getting on or off the train, 'mindful' is the appropriate choice and 'thoughtful' gives us that uneasy feeling that something is not quite right with the sentence, even if we understand what the LTA is trying to say.
Unfortunately, the blog writer is not only obscure in his meaning, but he also makes poor word choices as well, detracting from what otherwise would be a good point that he is making. First, he says that the sentence is meaningless, despite the fact that we clearly understand what the LTA means. What he intends to say is that writer choses a word with a meaning that does not fit the second half of the sentence. A thoughtful person does not queue or give way. A mindful person queues and gives way. Being thoughtful and giving way are unrelated in the opinion of the blogger.
Secondly, he talks about using a prop or dummy subject. He is suggesting that the sentence is written in an awkward manner and needs reworking, but from what I can tell in the short block of text posted above, he does not go into further explanation or give an example of how he thinks the LTA's message should be written. But I think he means that the subject should go at the beginning of the sentence, so that it reads:
'You are being thoughtful when you queue and give way to alighting passengers.'
When it is written as 'Queueing and giving way is...', 'queueing' and 'giving way' are gerunds acting as the subjects, but the real subject is 'you', while 'queueing' and 'giving way' are props or fakes, holding the place of the subject in the sentence.
The blogger is suggesting that in order to keep the integrity of the English language, it is important to teach learners of English as a second language the appropriate usage and meaning of words. It is also necessary to be mindful poorly written sentences. When displaying improper use of English publicly, rather than improve its citizens' English ability, the Singaporean government causes problems with learning English correctly. This is what the blogger refers to when he talks about illiteracy because ESL learners will, in turn, write poorly as a result.
References: Oxford Online Dictionary, nine years living and teaching English in Asia, China and Korea
(On a side note, I heard this word 'alight' for the first time on a train in China. We Americans say 'get off' or 'exit' the train.)

A: I might not have the prescriptivist grammarian credentials to best answer this question, but it is interesting, so here are my two cents.
The argument against "queueing is thoughtful of you" seems to rely on the idea that "[gerund] is [adjective] [preposition] you" is inherently wrong because the infinitive form should be used instead of a gerund.

It is thoughtful of you to queue

therefore

To queue is thoughtful of you.

But what about this counterexample:

It is good for you to run.
Running is good for you.

If being "grammatical" is connected at all to being idiomatic and observable in use, then "running is healthy for you" or "running is good for you" appear to be acceptable.  The phrases are used with only trivial variations in The Guardian and in The New York Times.
For what it's worth, "running is good for you" also sounds idiomatic to these native ears and probably most others.
So what's the difference between "Running is good for you" and "Queueing is thoughtful of you?"
Syntactically speaking, both follow the "[gerund] is [adjective] [preposition] you" pattern.  I can't see a reason why the OP's sentence in context would be particularly incorrect because it uses the word "of" and not "for."
Furthermore, it seems to me that a grammatically "wrong" sentence ought to be "wrong" all the time.  Would this pair of sentences be incorrect?

Thank you for queueing. It was thoughtful of you.

If it is incorrect, then would this also be incorrect?

Thank you for hurrying.  It was thoughtful of you.

The latter sentence seems to have an implied ellipsis:

Thank you for hurrying.  It was thoughtful of you to hurry.

Yet the mere fact that the ellipsed phrase takes the infinitive form doesn't seem to render the sentences ungrammatical or not idiomatic.
Based on this line of reasoning, I see no problem with the sentence "Queueing is so thoughtful of you."

A: Maybe queueing and not queuing?
Maybe this is the actual error.
From Cambridge Advanced Learner's Dictionary:

queue verb [ I ] UK  /kjuː/ US  /kjuː/ UK US line, US line up, also UK queue up
2 to wait in a line of people, often to buy something:
Dozens of people were queueing up to get tickets.
We had to queue for three hours to get in.
informal to want very much to do something: [ + to infinitive ]
  *There are thousands of young women queueing up to be models.*


text:
Q: JSON Schema reporting error only for first element of array I have the below JSON document.
[
    {
        "name": "aaaa",
        "data": {
            "key": "id",
            "value": "aaaa"
        }
    },
    {
        "name": "bbbb",
        "data": {
            "key": "id1",
            "value": "bbbb"
        }
    }
]

Below is the JSON Schema I have created for the above content.
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "array",
  "items": [
    {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "data": {
          "type": "object",
          "properties": {
            "key": {
              "type": "string",
              "enum": [
                "id",
                "temp",
              ]
            },
            "value": {
              "type": "string",
            }
          },
          "required": [
            "key",
            "value"
          ]
        }
      },
      "required": [
        "name",
        "data"
      ]
    }
  ]
}

As per the schema, the value of data.key is invalid for second item in the array. but any online schema validator does not find that. If we use different value in first array element, it throws the excepted error.
I assume that my schema is wrong somehow. what I expect is that any child items of the array should be reported if they have values out of the enum list.

A: It's an easy mistake to make, so don't beat yourself up about this one!
items can be an array or an object. If it's an array, it validates the object at that position in the instance array. Here's an excerpt from the JSON Schema spec (draft-7)

The value of "items" MUST be either a valid JSON Schema or an array of
valid JSON Schemas.
If "items" is a schema, validation succeeds if all elements in the
array successfully validate against that schema.
If "items" is an array of schemas, validation succeeds if each element
of the instance validates against the schema at the same position, if
any.

JSON Schema (validation) draft-7  items
Removing the square braces provides you with the correct schema...
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "array",
  "items":
    {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "data": {
          "type": "object",
          "properties": {
            "key": {
              "type": "string",
              "enum": [
                "id",
                "temp",
              ]
            },
            "value": {
              "type": "string",
            }
          },
          "required": [
            "key",
            "value"
          ]
        }
      },
      "required": [
        "name",
        "data"
      ]
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to convert variable to double (KeyValue) in KeyDown in Visual Basic I have this code:
Private Sub key(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
    If e.KeyValue = Keys.Enter Then
        If FuSt = False Then
            FuSt = True
            My.Computer.Audio.Play(My.Settings.Full)
        Else
            FuSt = False
            My.Computer.Audio.Play(DIRECOTRY)
        End If
    End If
    If e.KeyValue = b1 Then
        My.Computer.Audio.Play(SoundsDir & "1.wav")
    End If
End Sub

But when I want to play b1 (Z button on the keyboard) I have this error:

Conversation from "z" to Double is incorrect (Somethink like that)

Can you help me?

A: To assign keys to a variable b1 try as said below.
Keys is an enum.
Dim b1 As Keys
b1 = Keys.Z

Like  Hans Passant comment, if you want to use KeyPress event (recommended), try below code.
   Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
        If e.KeyChar = Char.ToLower(ChrW(Keys.Z)) Then
            MsgBox("Z selecetd")
        End If
    End Sub

or if you want to go with KeyDown event, try below code.
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
    If e.KeyCode.Equals(Keys.Z) Then
        MsgBox("Z selecetd")
    End If
End Sub


text:
Q: Transform rotation doesn't start from the centre of a circle In css we can set rotation origin point to indicate the centre of the rotate start, but the below example seems not rotate from the centre of the circle.
HTML:

CSS:
@import "compass/css3";

body {
    cursor:url('http://ionicframework.com/img/finger.png'), auto;
}

@keyframes move-right {
    from {
        transform: rotate(0deg)
                   translate(-50px)
                   rotate(0deg);
    }
    to {
        transform: rotate(360deg)
                   translate(-50px)
                   rotate(-360deg);
    }
}

/**
* Mixin to put items on a circle
* [1] - Allows children to be absolutely positioned
* [2] - Allows the mixin to be used on a list
* [3] - In case box-sizing: border-box has been enabled
* [4] - Allows any type of direct children to be targeted
*/

@mixin putOnCircle(
      $nb-items, //Number of items
      $circle-size, //Parent size
      $item-size, //Item size
      $class-for-IE: false //Base class name, false means use of pseudo-selectors
   ) {
    $half-item:     $item-size / 2;
    $half-parent: $circle-size / 2;

    position: relative;               /* [1] */
    width:  $circle-size;
    height: $circle-size;
    padding: 0;
    border-radius: 50%;
    list-style: none;                 /* [2] */
    @include box-sizing(content-box); /* [3] */

    > * {                             /* [4] */
        display: block;
        position: absolute;
        top:  50%;
        left: 50%;
        width:  $item-size;
        height: $item-size;
        margin: -$half-item;

        $angle: 360 / $nb-items;
        $rot: 0;
        @for $i from 1 to $nb-items+1 {
          // If no support for IE8-

          @if $class-for-IE == false {
            &:nth-of-type(#{$i}) {
              @include transform(rotate(#{$rot}deg) translate($half-parent) rotate(-#{$rot}deg));
            }
          }

          // If support for IE8-

          @else {
            &.#{$class-for-IE}#{$i} {
              // If CSS transforms are not supported
              $mt: sin($rot * pi() / 180) * $half-parent - $half-item;
              $ml: cos($rot * pi() / 180) * $half-parent - $half-item;
              margin: $mt 0 0 $ml;
            }
          }
          $rot: $rot + $angle;
        }
    }
}

.circle-container {
    @include putOnCircle(24, 2*547px, 152px, false);
    margin: 250px auto;
    border: solid 5px tomato;
    background-color: black;

    /*.item1 {
        transform: rotate(90deg);
    }
    .item2 {
        transform: rotate(90+15deg);
    }*/
    /* a {
        display: block;
        border-radius: 50%;
        box-shadow: 0 0 0 5px tomato;
    }*/
    /*  #test {
      transform: rotate(-45deg);
    }*/

    img {
        user-drag: none;
        -moz-user-select: none;
        -webkit-user-drag: none;
        display: block;
        width: 100%;
        /* border-radius: 50%; */
        /* @include  filter(grayscale(100%)); */

        /*transform-origin: center;
        transform: rotate(15deg);*/

        /*&:hover {
          @include filter(grayscale(0));
        }*/
    }
}

JS
/**
 * Apply a class to each child
 * Required for IE8-
 */
jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
};

$( document ).ready(function() {
  $('.circle-container').children().each(function() {
  $(this).children().addClass('item'+($(this).index() + 1));
});

var angle = 90;
for(var i=1; i<=24; i++){
  $('.item'+i).rotate(angle + 15*(i-1));
}
})

var myElement = document.getElementById('test');
var mc = new Hammer(myElement);

var now =0;
mc.on("panleft panright", function(ev) {
  if (ev.type =="panleft") {
    now = now+15;
    $('.circle-container').rotate(now);
  }
  if (ev.type =="panright") {
    now = now-15;
    $('.circle-container').rotate(now);
  }
});

You can check a demo on codepen. How to fix this?

A: Your rotation origin had no issues.  Rather, each of your
's was being given a set width and height that were equal - creating a square.  Your image therefore overflowed the
.

A simple fix would be to re-write your mixin to take an additional parameter for the width and height of the images you'll be using.  Then you can center your image inside the
 so it will be able to rotate without regard for the image height by position:absoluteing the image with a top attribute derived from the new $image-height mixin parameter:

Your new CSS rules would look like this:
img {
    position: absolute;
    top: (-$item-height / 2) + ($item-width / 2);
}

Here is your example with the updated mixin.
Note: There are other ways of centering an image inside a smaller container in CSS - but this one would be very simple if you know your image's heights in advance and they are all the same dimension.


text:
Q: Hazelcast creates 3 nodes/members when configured as Hibernate L2 cache Hazelcast creates 3 nodes/members when configured as Hibernate L2 cache.
Why? How do I control this?
I am using Hazelcast 3.2.6 with default configuration and Grails 2.2.3.

A: You can set up an instanceName for all Hazelcast instances used in the Hibernate configurations. Then all will reuse the same HazelcastInstance (referred to by the name).
To set the instance name please use the following property in the Hibernate config all set to the same value:
hibernate.cache.hazelcast.instance_name

Set as:
<property name="hibernate.cache.hazelcast.instance_name">common_name</property>


text:
Q: Tensorflow value error: Variable already exists, disallowed I am predicting financial time series with different time periods using tensorflow. In order to divide input data, I made sub-samples and used for loop.
However, I got an ValueError like this;
ValueError: Variable rnn/basic_lstm_cell/weights already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:
Without subsample this code works well.
Below is my code.
    import tensorflow as tf
    import numpy as np
    import matplotlib
    import os
    import matplotlib.pyplot as plt

    class lstm:
        def __init__(self, x, y):
            # train Parameters
            self.seq_length = 50
            self.data_dim = x.shape[1]
            self.hidden_dim = self.data_dim*2
            self.output_dim = 1
            self.learning_rate = 0.0001
            self.iterations = 5 # originally 500

        def model(self,x,y):
            # build a dataset
            dataX = []
            dataY = []
            for i in range(0, len(y) - self.seq_length):
                _x = x[i:i + self.seq_length]
                _y = y[i + self.seq_length]
                dataX.append(_x)
                dataY.append(_y)

            train_size = int(len(dataY) * 0.7977)
            test_size = len(dataY) - train_size
            trainX, testX = np.array(dataX[0:train_size]), np.array(dataX[train_size:len(dataX)])
            trainY, testY = np.array(dataY[0:train_size]), np.array(dataY[train_size:len(dataY)])
            print(train_size,test_size)

            # input place holders
            X = tf.placeholder(tf.float32, [None, self.seq_length,         self.data_dim])
            Y = tf.placeholder(tf.float32, [None, 1])

            # build a LSTM network
            cell = tf.contrib.rnn.BasicLSTMCell(num_units=self.hidden_dim,state_is_tuple=True,  activation=tf.tanh)
            outputs, _states = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)
            self.Y_pred = tf.contrib.layers.fully_connected(outputs[:, -1], self.output_dim, activation_fn=None)
            # We use the last cell's output

            # cost/loss
            loss = tf.reduce_sum(tf.square(self.Y_pred - Y))  # sum of the squares
            # optimizer
            optimizer = tf.train.AdamOptimizer(self.learning_rate)
            train = optimizer.minimize(loss)

            # RMSE
            targets = tf.placeholder(tf.float32, [None, 1])
            predictions = tf.placeholder(tf.float32, [None, 1])
            rmse = tf.sqrt(tf.reduce_mean(tf.square(targets - predictions)))

            # training
            with tf.Session() as sess:
                init = tf.global_variables_initializer()
                sess.run(init)

                # Training step
                for i in range(self.iterations):
                    _, step_loss = sess.run([train, loss], feed_dict={X: trainX, Y: trainY})

                # prediction
                train_predict = sess.run(self.Y_pred, feed_dict={X: trainX})
                test_predict = sess.run(self.Y_pred, feed_dict={X: testX})

            return train_predict, test_predict

    # variables definition
    tsx = []
    tsy = []
    tsr = []
    trp = []
    tep = []

    x = np.loadtxt('data.csv', delimiter=',') # data for analysis
    y = x[:,[-1]]
    z = np.loadtxt('rb.csv', delimiter=',')   # data for time series
    z1 = z[:,0] # start cell
    z2 = z[:,1] # end cell

    for i in range(1): # need to change to len(z)
        globals()['x_%s' % i] = x[int(z1[i]):int(z2[i]),:] # definition of x
        tsx.append(globals()["x_%s" % i])

        globals()['y_%s' % i] = y[int(z1[i])+1:int(z2[i])+1,:] # definition of y
        tsy.append(globals()["y_%s" % i])

        globals()['a_%s' % i] = lstm(tsx[i],tsy[i]) # definition of class

        globals()['trp_%s' % i],globals()['tep_%s' % i] = globals()["a_%s" % i].model(tsx[i],tsy[i])
        trp.append(globals()["trp_%s" % i])
        tep.append(globals()["tep_%s" % i])

A: You define some variables in the "model" function.
Try this when you want to call "model" function multiple times:
with tf.variable_scope("model_fn") as scope:
  train_predict, test_predict = model(input1)
with tf.variable_scope(scope, reuse=True):
  train_predict, test_predict = model(input2)

A: Everytime the model method is called, you are building the computational graph of your LSTM. The second time the model method is called, tensorflow discovers that you already created variables with the same name. If the reuse flag of the scope in which the variables are created, is set to False, a ValueError is raised.
To solve this problem you have to set the reuse flag to True by calling tf.get_variable_scope().reuse_variables() at the end of your loop.
Note that you can't add this in the beginning of your loop, because then you are trying to reuse variables that have not yet been created.
You find more info in the tensorflow docs here


text:
Q: How deep is a gravity well of a supermassive black hole? Just for the sake of curiosity I am trying to understand how far we should stay away from the black hole to avoid influence of its gravity on us.
In the first iteration I know about the 2nd and the 3rd cosmic speed that let you reach the orbit and leave it respectively. From another perspective we might look at this issue as a gravity well where we should escape from - get enough speed, pass some distance. It is all depends on the radius and the mass of the object, in our case a black hole. the 2nd cosmic speed formula
Going further I was trying to evaluate the mass of the 'average' black hole. Apparently, it was discovered black holes with intermediate-mass are the more rarest ones. There are three types of black holes and stellar black holes together with supermassive black holes prevalent in the discovered universe. wiki article
In such case let's take the supermassive black hole to evaluate the upper bound of the safe distance from the black hole without starting moving towards it.  If the mass of the supermassive black hole I have found out (~100 000 000 * 'the mass of the Sun'), the others necessary data takes more time.

A: Gravity doesn't have a finite range. In a Universe with just you and the black hole, if you do not take action to move away from the black hole or to orbit the black hole, given enough time it will pull you in no matter where you start from.
In the real Universe, there are more things than just you and one black hole. As a result, you experience pulls in different directions and don't fall toward one particular object unless the gravitational pull for that object is stronger than the accumulated gravitational effect of all other bodies in the Universe. Therefore there is no general way to answer your question without having a model of what other things are in the Universe, at least things that are close enough to the black hole that their influence competes with the black hole's.
If you do start falling into a black hole, you can either escape by accelerating away from the black hole, or reach a stable orbit by accelerating in a direction perpendicular to the line connecting you and the black hole. This is possible to do until you cross the event horizon, at which point you will inevitably hit the singularity. For a non-spinning black hole, the size of the event horizon is given in terms of the mass of the black hole via the Schwarzschild radius.


text:
Q: Python ndb.Model Required Attribute is None I have an ndb.Model class ProjRoute which has an attribute date which I declare in the model as follows:
class ProjRoute(ndb.Model):
  date = ndb.DateTimeProperty(required=True)
  priceValue = ndb.FloatProperty(default=None)
  attachement = ndb.KeyProperty()
  src = PriceFilterProperty()
  dest = PriceFilterProperty()
  # Required qty
  reqQty = ndb.FloatProperty()
  ldQty = ndb.FloatProperty(default=0)
  unldQty = ndb.FloatProperty(default=0)
  amountDue = ndb.FloatProperty(default=0)
  scale1 = ndb.FloatProperty(default=0)
  scale2 = ndb.FloatProperty(default=0)
  toll1 = ndb.FloatProperty(default=0)
  toll2 = ndb.FloatProperty(default=0)
  port_permit = ndb.FloatProperty(default=0)
  port_scale = ndb.FloatProperty(default=0)
  maintenance = ndb.FloatProperty(default=0)
  other = ndb.FloatProperty(default=0)
  fuel = ndb.FloatProperty(default=0)
  gratuity = ndb.FloatProperty(default=0)
  driver_allow = ndb.FloatProperty(default=0)
  adriver_allow = ndb.FloatProperty(default=0)
  driver_bonus = ndb.FloatProperty(default=0)

I am pretty sure that I do set a date value when creating a new ProjRoute instance, and in fact I don't face any problems when calling the put() function.
However, when I try to read the instance I get an error because the date attribute in null.
BadValueError: Entity has uninitialized properties: date

This error also doesn't appear every time I try to read an instance, it's arbitrary.
I think that something must be wrong with the GAE itself, but anyone knows how to fix it or know of a work-around?
By the way, when I log any ProjRoute instance I find that attributes are stored as GenereicProperty not FloatProperty and KeyProperty like I had declared in the model. I think this might be related.
In case you care to look at it, here is the code where I create a new instance:
trsPrices = map(float, self.readAll('trs-price'))
for src, dest, price in zip(self.readAll('trs-price-src'), self.readAll('trs-price-dest'), trsPrices):
    route = ProjRoute(id=newPrice.src+"-"+newPrice.dest, parent=routeParent)
    route.attachement = newPrice.attachement
    route.src, route.dest = newPrice.src, newPrice.dest
    route.date = trsSrv.sdate
    route.priceValue = None
    toSave.append(route)

# ... Some irrelevent code
ndb.put_multi(toSave)

Also FYI, I have tried using route.put() instead of ndb.put_multi but the problem remained.


text:
Q: Middle align an inline paragraph and svg inside a div, why do I have to use a flexbox? Well consider I have two elements: an svg image (icon) and a paragraph (styled to be inline). I wish to render them side to side inside a div, and I wish to align them "in the middle".
Now I "got" this working using display: inline-flex for the outer div as follow:

test

<svg class="icon" focusable="false" viewBox="0 0 24 24" aria-hidden="true" role="presentation"><path d="M12 8l-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z"></path><path fill="none" d="M0 0h24v24H0z"></path></svg>

css:
.grouper {
    display: inline-flex;
    vertical-align: middle;
    align-items: center;
    width: 100%;
}

.borderhelper {
  border-style: solid;
  border-width: 1px;
  border-color: 0;
}

.icon {
    width: 1em;
    height: 1em;
    display: inline-block;
    font-size: 24px;
}

p {
  margin: 0px;
}

fiddle.
However I am wondering: why would I need a flexbox in this case? It makes no sense as there's no flexing to happen, only aligning. Yet when I try to change display to "inline-block" the alignment fails.


text:
Q: how to pass bucket/key name to fargate job via a cloudwatch event trigger on s3 object creation event? I have create a fargate task and trying to trigger it via s3 object creation event ( see sample below) via cloudformation.as it cannot trigger it directly, i have created a cloudwatchevent.  I am trying to pass the bucket and obj name to my fargate task code . doing some research, i came across ->  InputTransformer, but i'm not sure how to pass the value of my bucket and key name and how to read it in my python code. any help will be appreciated.
AWSTemplateFormatVersion: 2010-09-09
Description: An example CloudFormation template for Fargate.
Parameters:
  VPC:
    Type: AWS::EC2::VPC::Id
  SubnetA:
    Type: AWS::EC2::Subnet::Id
  SubnetB:
    Type: AWS::EC2::Subnet::Id
  Image:
    Type: String
    Default: 123456789012.dkr.ecr.region.amazonaws.com/image:tag
Resources:
  mybucket:
    Properties:
      BucketName: 'mytestbucket-us'

  cloudwatchEvent:
    Type: AWS::Events::Rule
    Properties:
      EventPattern:
        source:
          - aws.s3
        detail:
          eventSource:
            - s3.amazonaws.com
          eventName:
            - PutObject
            - CompleteMultipartUpload
          requestParameters:
            bucketName:
              - !Ref mybucket
    Targets:
      - Id: my-fargate-task
        Arn: myclusterArn
        RoleArn: myinvocationrolearn
        Input:
          'Fn::Sub':
             - >-
               {"containerOverrides": [{"name":"somecontainer"]}
        EcsParameters:
          TaskDefinition:
            LaunchType: 'FARGATE'
            ...
          NetworkConfiguration:
            ...

  Cluster:
    Type: AWS::ECS::Cluster
    Properties:
      ClusterName: !Join ['', [!Ref ServiceName, Cluster]]

  TaskDefinition:
    Type: AWS::ECS::TaskDefinition
    DependsOn: LogGroup
    Properties:
      Family: !Join ['', [!Ref ServiceName, TaskDefinition]]
      NetworkMode: awsvpc
      RequiresCompatibilities:
        - FARGATE
      Cpu: 256
      Memory: 2GB
      ExecutionRoleArn: !Ref ExecutionRole
      TaskRoleArn: !Ref TaskRole
      ContainerDefinitions:
        - Name: !Ref ServiceName
          Image: !Ref Image

  # A role needed by ECS
  ExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Join ['', [!Ref ServiceName, ExecutionRole]]
      AssumeRolePolicyDocument:
        Statement:
          - Effect: Allow
            Principal:
              Service: ecs-tasks.amazonaws.com
            Action: 'sts:AssumeRole'
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy'
  # A role for the containers
  TaskRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Join ['', [!Ref ServiceName, TaskRole]]
      AssumeRolePolicyDocument:
        Statement:
          - Effect: Allow
            Principal:
              Service: ecs-tasks.amazonaws.com
            Action: 'sts:AssumeRole'

A: You would use a CloudWatch Event Input Transformer to extract the data you need from the event, and pass that data to the ECS task as environment variable(s) in the target's ContainerOverrides. I don't use CloudFormation, but here's an example using Terraform.

A: You can't. CloudWatch events do not pass data to ECS jobs. You need to develop your own mechanism for that. For example, trigger lambda first, store event in S3 Parameter Store or DynamoDB, and then invoke your ECS job which will get stored data.


text:
Q: A script for making another script deal with all files in sequence? I have found a nicely working script to convert pdf files into txt format, with ocr.
But it converts only one pdf file each time. I need to mass-convert them.
I have no knowledge of script writing. The script is at below.
How can I mass convert them?
#!/bin/bash

## script to:
##   *  split a PDF up by pages
##   *  convert them to an image format
##   *  read the text from each page
##   *  concatenate the pages

## pass name of PDF file to script
INFILE=$1

## split PDF file into pages, resulting files will be
## numbered: pg_0001.pdf  pg_0002.pdf  pg_0003.pdf
pdftk $INFILE burst

for i in pg*.pdf ; do

    ## convert it to a PNG image file
    convert -density 200 -quality 100 $i ${i%.pdf}.png

    ## read text from each page
    tesseract ${i%.pdf}.png ${i%.pdf}.txt

done

## concatenate the pages into a single text file
cat pg*.txt > ${INFILE%.pdf}.txt

exit

Note: I have read the similar questions but couldn't figure it out.

A: You could modify your script:
# instead of INFILE=$1
for INFILE
do
#...

    for i in pg*.pdf ; do
        #...
    done

    ## concatenate the pages into a single text file
    cat pg*.txt > ${INFILE%.pdf}.txt
done

Then call your script thus:
some-script.sh 1.pdf 2.pdf #...

A bash for loop, when not given anything to loop on, loops over all the command-line arguments. Hence,
for INFILE

is equivalent to:
for INFILE in "$@"

A: From what i understand from your question, i guess this is what you expect:
for each in *.pdf
do
  your_conv_script.sh $each
done

where your_conv_script.sh is the script that you have denoted above.
Also note that you need to clean temporarily created files.


text:
Q: Expression for an abrupt change in height Is there an expression for an abrupt change in height? I'm looking for a word for the edge of the change, like in the German word Geländekante.

A: I don't speak German, but looking at this page it seems to me Geländekante can apply to any abrupt change in "level".
Those examples range from "height discontinuities" of hundreds/thousands of feet (cliffs, Ayers Rock) to mere inches (kerb between road and pavement, small mismatch in a loading bay area). So I think the short answer is there is no equivalent "generic" word or common expression for this in English.

1: At the "geological" level there are lots of terms (cliff, escarpment, bluff, etc.), with the same or overlapping meanings.
2: Somewhere in the middle - usually from the "above" perspective, with emphasis on the danger of falling over the edge - are terms like precipice, drop.
3: At smaller scales (the most likely context where you'd need a more general-purpose term) the best bet is probably step (Mind the step = Don't trip over the upcoming small change in level).

A: A cliff or precipice is at the boundary to an abrupt change in altitude.
Google:

cliff
a steep rock face, especially at the edge of the sea.
synonyms: precipice, rock face, crag, bluff, ridge, escarpment, scar,

related: shelf

A: If you are specifically referring to a change in height of a person (a human) - then we call that a "spurt", or more specifically a "growth spurt" - when a child grows inches taller, almost overnight.

A: There are dozens of words for these things that vary in aspect, specificity, origin, and region. Sometimes they emphasize the vertical aspect; other times the line at the top or bottom. Some are for collections of these things; others for singular instances.

*

*cliff

*bluff

*breaks

*palisades

*scarp

*escarpment

*fault

*face

*ridge

*cuesta

*wall

*hogback

*pediment

*cleaver

*sérac

*kame

*buttress

*cornice

*rampart

*cirque

*headwall

*nunatuk

*defile

*quebrada

*huérfano

*rimland

*badlands

*yardang

*arête

*combs ridge

*banco

*postpile

*malpais

*louderback

*castle rock

*tsegi

*slab

*pali

*morro

Some of these terms are common and general; others rare and specific. There are many more.  Some are found in every dictionary; others only in specialty lexicons devoted to geography.  One of the latter can be found at the web site Home Ground: Language for an American Landscape.

A: Scarp, or escarpment.
Wikipedia:

*

*Cliff, a significant vertical, or near vertical, rock exposure

*Escarpment, a steep slope or long rock that occurs from erosion or faulting and separates two relatively level areas of differing elevations

A: Some comments clarified that the context is terrain.
In this case, you could say The road (or path, or ground, or whatever) dropped off sharply OR rose sharply.  If you google these phrases, you'll see they're extremely common.
(Next time, could you provide the context in your question, please?)


text:
Q: JavaScript chart.js syntax error if statement We are using the chart.js library. The framework used is Slim from Rails. I'm using JavaScript.
I get an Error:

Uncaught SyntaxError: Unexpected token 'if' error in the
if(user.activity_type === "groupA").

 script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"
  javascript:
    var users = #{raw @user.to_json}
    let count = 0;
    let month = "";
    let array = [];
    var ct = document.getElementById('ex_chart');
    var ex_chart = new Chart(ct, {
        type: 'horizontalBar',
        data: {
        labels: ["Jan", "Feb", "Mar", "Apr"],
          datasets: [
            {
              data: users.map((user) => (
                    if(user.activity_type === "groupA") {
                        if(month === "" || month === user.month) {
                          count += user.count;
                        } else {
                          array.push(count);
                          count = user.count;
                          month = user.month;
                        }
                      return array;
                    }
              ),
              backgroundColor: '#ff7f50'
            }},
            {
              data: [880, 740, 900, 520, 930],
              backgroundColor: '#ff6347'
            }
          ]
          });
        },
        options: options
    })

    var options = {
        scales: {
            xAxes: [{
                ticks: {
                    min: 300
                }
            }]
        }
    };

A: The arrow function should have curly braces instead of parentheses. Try replacing data with this:
data: users.map((user) => {
    if(user.activity_type === "groupA") {
        if(month === "" || month === user.month) {
          count += user.count;
        } else {
          array.push(count);
          count = user.count;
          month = user.month;
        }
      return array;
    }
}),

Notice the curly brace right after the arrow and the one before the parenthesis on the last line.

A: Use {} rather than () in map
It should be like this:
script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"
javascript:
  var users = #{raw @user.to_json}
  let count = 0;
  let month = "";
  let array = [];
  var ct = document.getElementById('ex_chart');
  var ex_chart = new Chart(ct, {
      type: 'horizontalBar',
      data: {
      labels: ["Jan", "Feb", "Mar", "Apr"],
        datasets: [
            {
            data: users.map((user) => {
                    console.log("user", user);
                    if(user.activity_type === "groupA") {
                        if(month === "" || month === user.month) {
                        count += user.count;
                        } else {
                        array.push(count);
                        count = user.count;
                        month = user.month;
                        }
                    return array;
                    }
            }),
            backgroundColor: '#ff7f50',
            },
            {
            data: [880, 740, 900, 520, 930],
            backgroundColor: '#ff6347'
            }
        ]
      },
      options: options
  })


text:
Q: For $z \in \mathbb C$, define $f(z) = \frac {e^z}{e^z - 1}$, then
*

*$f$ is entire .

*the only singularities of $f$ are poles.

*$f$ has infinitely many poles on the imaginary axis

*each pole of $f$ is simple.
For (1), Since $0$ is a pole of $f$, So $f$ is not entire.
For (2),(3) other Singularities of $f$ are $2n\pi i$, where n $\in \mathbb Z$
For (4), Since zeroes of $e^z - 1$ is $2n\pi i $ and deivative of $e^z - 1$ is $e^z$ is not equal to zero at $2n\pi i$. So (4) is true.

A: $f$ has singularity at the points, where $e^z=1$. And which, according to your calculation, are infinitely many, lies on imaginary axis. And each of them are pole. So, 2),3) and 4) are correct.


text:
Q: xslt - match ID's across two XML files and replace all ids and names I have 2 XML files with data about same items, and i have to change only the IDs from the first XML.
1.xml First data looks like this (with more attributes that are irrelevant to the comparison):
 <channel id="Digi">
    <display-name lang="tr">Digi</display-name>
    <url>http://www.digiturk.com.tr</url>
  </channel>
<channel id="Star">
    <display-name lang="tr">Star</display-name>
    <url>http://www.digiturk.com.tr</url>
  </channel>
<channel id="ATV">
    <display-name lang="tr">ATV</display-name>
    <url>http://www.digiturk.com.tr</url>
  </channel>

2.xml Second data look like this (with more attributes and possible sub-elements):
 <channel id="Digi.TR">
    <display-name lang="tr">Digi.TR</display-name>
    <url>http://www.digiturk.com.tr</url>
  </channel>
<channel id="Star.tr">
    <display-name lang="tr">Star.tr</display-name>
    <url>http://www.digiturk.com.tr</url>
  </channel>
<channel id="ATV.tr">
    <display-name lang="tr">ATV.tr</display-name>
    <url>http://www.digiturk.com.tr</url>
  </channel>

Is it possible to run some script/code/xslt stylesheet to replace the ids in the  First 1.xml with the ids from the Second Date 2.xml?
I am not very familiar with stylesheets and not sure where to begin with coding something like that
For each item in 1.xml, read attributes "id" and "name"find them with same "id" and "name" in 2.xml replace "id" and "name" in 1.xml.
Thank you for any help you can provide

A: Assume that both XMLs have a root node, e.g. called <root>, each wrapping the XML contents. This is necessary for the XMLs to be well-formed because both you XMLs are not.
Now the First 1.xml is copied by the identity template and while copying all relevant id attribute nodes are replaced with the respective id values from Second Date 2.xml by using the document() function to include the second XML file.
To replace the id attributes in the first XML with the respective ones from the second XML each pair is compared with starts-with() in a predicate.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

  <!-- identity template -->
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
   </xsl:template>

  <xsl:template match="channel/@id">
    <xsl:variable name="ID" select="." />    <!-- save @id from First 1.xml in variable $ID -->
    <xsl:attribute name="id">                <!-- reconstruct id attribute -->
        <!-- copy value from second XML to first XML if id attributes partially match -->
        <xsl:value-of select="normalize-space(document('Second Date 2.xml')/root/channel[starts-with(@id,$ID)]/@id)" />
    </xsl:attribute>
  </xsl:template>

</xsl:stylesheet>

Output:
<root>
    <channel id="Digi.TR">
        <display-name lang="tr">Digi</display-name>
        <url>http://www.digiturk.com.tr</url>
    </channel>
    <channel id="Star.tr">
        <display-name lang="tr">Star</display-name>
        <url>http://www.digiturk.com.tr</url>
    </channel>
    <channel id="ATV.tr">
        <display-name lang="tr">ATV</display-name>
        <url>http://www.digiturk.com.tr</url>
    </channel>
</root>


text:
Q: EF 4.1 RC Code First - Mapping to existing database & specifying foreign key name I have two classes.  A Company has a County set against it:
public class Company
{
    public int Id { get; set; }
    public string CompanyName { get; set; }
    public Country HomeCountry { get; set; }
}

public class Country
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

I am trying to map to an existing database where the Company table contains the foreign key of the Country record.  So I presumably need to tell code first the name of the foreign key column.
Below is the complete code example.  It's currently failing with different exceptions based on different things that I try.  There's seems to be a lack of cohesive documentation on this as yet.
So using Code First Fluent API how do I define the name of the foreign key column?
Test app:
Create database as follows:
    CREATE DATABASE CodeFirst;
    GO
Use CodeFirst

create table Companies
(
    Id int identity(1,1) not null,
    HomeCountryId int not null,
    Name varchar(20) not null,
    constraint PK_Companies primary key clustered (Id)
)

create table Countries
(
   Id                    int identity(1,1) not null
,  Code                  varchar(4)        not null
,  Name                  varchar(20)       not null
,  constraint PK_Countries primary key clustered (Id)
)

alter table Companies
  add
     constraint FK_Company_HomeCountry foreign key (HomeCountryId)
        references Countries (Id) on delete no action

Now run the following C# app:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data;

namespace CodeFirstExistingDatabase
{

    class Program
    {
        private const string ConnectionString = @"Server=.\sql2005;Database=CodeFirst;integrated security=SSPI;";

        static void Main(string[] args)
        {

            // Firstly, add a country record, this works fine.
            Country country = new Country();
            country.Code = "UK";
            country.Name = "United Kingdom";

            MyContext myContext = new MyContext(ConnectionString);
            myContext.Countries.Add(country);
            myContext.Entry(country).State = EntityState.Added;
            myContext.SaveChanges();
            Console.WriteLine("Saved Country");

            // Now insert a Company record
            Company company = new Company();
            company.CompanyName = "AccessUK";
            company.HomeCountry = myContext.Countries.First(e => e.Code == "UK");

            myContext.Companies.Add(company);
            myContext.Entry(company).State = EntityState.Added;
            myContext.Entry(country).State = EntityState.Unchanged;
            myContext.SaveChanges();

            Console.WriteLine("Saved Company"); // If I can get here I'd he happy!

        }
    }

    public class MyContext
        : DbContext
    {
        public DbSet<Company> Companies { get; set; }

        public DbSet<Country> Countries { get; set; }

        public MyContext(string connectionString)
            : base(connectionString)
        {
            Database.SetInitializer<MyContext>(null);
            Configuration.LazyLoadingEnabled = false;
            Configuration.ProxyCreationEnabled = false;
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new CountryConfiguration());
            modelBuilder.Configurations.Add(new CompanyConfiguration());

            base.OnModelCreating(modelBuilder);
        }
    }

    public class CompanyConfiguration
        : EntityTypeConfiguration<Company>
    {

        public CompanyConfiguration()
            : base()
        {

            HasKey(p => p.Id);
            Property(p => p.Id)
                .HasColumnName("Id")
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
                .IsRequired();
            Property(p => p.CompanyName)
                .HasColumnName("Name")
                .IsRequired();
            ToTable("Companies");
        }

    }

    public class CountryConfiguration
        : EntityTypeConfiguration<Country>
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="CountryConfiguration"/> class.
        /// </summary>
        public CountryConfiguration()
            : base()
        {

            HasKey(p => p.Id);
            Property(p => p.Id)
                .HasColumnName("Id")
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
                .IsRequired();
            Property(p => p.Code)
                .HasColumnName("Code")
                .IsRequired();
            Property(p => p.Name)
                .HasColumnName("Name")
                .IsRequired();

            ToTable("Countries");
        }

    }

    public class Company
    {
        public int Id { get; set; }
        public string CompanyName { get; set; }
        public Country HomeCountry { get; set; }
    }

    public class Country
    {
        public int Id { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
    }
}

The above fails with the following when saving the country:
Invalid column name 'HomeCountry_Id
Any help would be very much appreciated!!
Thanks, Paul.

A: public CompanyConfiguration()
{
    //...
    HasRequired(x => x.HomeCountry).WithMany()
        .Map(x => x.MapKey("HomeCountryId"));
}

A: We are moving a Web Forms app to MVC3 using Code First against an existing db without any problems. Here are 2 sample Models and the DbContext I'm using. prDepartments & prCategories map to tables in the db and ApplicationDBContext matches the connection string in Web.config
The DeptID field in prCategory is a Foreign Key to prDepartment - Everything works great
public class prCategory
{
    [Key]
    public int CatgID { get; set; }
    public int DeptID { get; set; }
    [Required(ErrorMessage="Category Description Is Required")]
    [DisplayName("Desc Name")]
    [CssClass("ui-Field-Name")]
    public string Description { get; set; }
    public string Route { get; set; }
    public string OrderBy { get; set; }
    public virtual prDepartment Department { get; set; }
    public virtual List<prProduct> prProducts { get; set; }
}

public class prDepartment
{
    [Key]
    public int DeptID { get; set; }
    [Required(ErrorMessage = "Department Description Is Required")]
    [RequiredMessage("This is the Required Message")]
    public string Description { get; set; }
    public string Route { get; set; }
    public string OrderBy { get; set; }

    public virtual List<prCategory> prCategories { get; set; }
}

    public class ApplicationDbContext : DbContext
{
        public DbSet<prDepartment> prDepartments { get; set; }
        public DbSet<prCategory> prCategories { get; set; }
        public DbSet<prProduct> prProducts { get; set; }
}


text:
Q: Can not start new activity I have two classes. The main class is BundleActivity, and another sub class.
I'm trying to start sub activity from BundleActivity but It's not working and app is force closing.
Here is my onClick method in BundleAcitvity class:
public void onClick(View v) {
        // TODO Auto-generated method stub

            Intent i=new Intent(this,sub.class);
            this.startActivity(i);
                            }

My manifest file :
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bundle"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
          <activity
            android:name=".BundleActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".sub"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="com.bundle.sub" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

    </application>

</manifest>

Any one help me to fix it?

A: Did you create a class for your sub activity?
As far as I know, all your classes must begin with a capital letter "Sub".
It feels to me as well as if you didn't need the intent-filters you put in your sub activity.
Aren't you receiving any pre-compiling errors?
What's the error trace in runtime?


text:
Q: C# Is there a compact way to get more than one coordinate in a 2d-array? Trying to make connect4 and I want to check if a column (vertical) is full, so the easy way to do it would be in an if with [i, 1] != O && [i, 2] != O && [i, 3] != O et cetera, but isn't there a more efficient way to go on about this?
A board looks like:
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O

The for-loop:
for (int i = row - 1; i > -1; i--)
{
     if (board[i, column].ToString() == "O" && beurt % 2 == 0)
     {
         board[i, column] = (Veld)player1.color;
         beurt += 1;
         break;
     }
     else if(board[i, column].ToString() == "O" && beurt % 2 == 1)
     {
             board[i, column] = (Veld)player2.color;
             beurt += 1;
             break;
     }
     else if(???)
     {
             //???
     }
}

A: bool isRowFull(char[,] array, int row)
{
    for(int i=0;i<array.GetLength(0); i++)
        if(array[row, i] == 'O') return false;
    return true;
}

And you can call it like:
bool isFull = isRowFull(board, 3); // check if row 3 is full

or
if(isRowFull(board, 3))
{
    //your code
}

To Get First NonFull row:
int FirstNonFull(char[,] array)
{
    for(int i=0;i<array.GetLength(1);i++)
        if(!isRowFull(array, i)) return i;
    return -1; // -1 indicating that all rows are full (not found)
}

A: Similaraly you could use Linq to verify that All items at row equal O:
public static bool IsRowEmpty(char[,]board, int row)
{
    return Enumerable.Range(0, board.GetUpperBound(1)).All(col => board[row, col] == 'O');
}


text:
Q: SQL query to select last X entries for a certain non-primary field I'm having difficulties setting up a slightly more advanced SQL query.
What I'm trying to do is to select the last 24 entries for every zr_miner_id, but I keep getting SQL timeouts (the table has around 40000 entries so far).
So let's say there's 200 entries for zr_miner_id 1 and 200 for zr_miner_id 2, I'd end up with 48 results.
So far, I've come up with the query below.
What this is supposed to do is to select each result in zec_results that has less than 24 newer entries with the same zr_miner_id.
I couldn't think of any better way to perform this task, but then again, I'm not that far advanced at SQL yet.
SELECT results_a.*
FROM   zec_results results_a
WHERE  (
    SELECT COUNT(results_b.zr_id)
    FROM   zec_results AS results_b
    WHERE  results_b.zr_miner_id = results_a.zr_miner_id
    AND    results_b.zr_id >= results_a.zr_id
) <= 24

A: Use variables!
SELECT r.*
FROM (SELECT r.*,
             (@rn := if(@m = r.zr_miner_id, @rn + 1,
                        if(@m := r.zr_miner_id, 1, 1)
                       )
             ) as rn
      FROM zec_results r CROSS JOIN
           (SELECT @m := -1, @rn := 0) params
      ORDER BY r.zr_miner_id, r.zr_id DESC
     ) r
WHERE rn <= 24 ;

If you want to put the query into a view, then the above will not work.  Performance on your approach might improve with an index on (zr_miner_id, zr_id).


text:
Q: Adding extra arguments to ModelForm Constructor using change_view in django admin I would like to be able to access request object in django admins clean() method. How can I customize this getting the user from a admin validation class to work with django admins modelform
What kind of modification do i need to make to change_view below
def change_view(self, request, object_id, extra_context=None):
    self.form = GroupForm
    result = super(GroupsAdmin, self).change_view(request, object_id, extra_context)

    return result

so that it calls the constructor below which has the request argument
class GroupForm(forms.ModelForm):
    class Meta:
        model = Group

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(GroupForm, self).__init__(*args, **kwargs)

A: Seeing as no answer was ever provided for this, I figured I should highlight how I resolved this just in case someone else might find the info useful.
I eventually solved this on defining a custom middleware and using ThreadLocals.
First define a ThreadLocals class in your forms.py as shown below
import threading
_thread_locals = threading.local()

class ThreadLocals(object):
    """
    Middleware that gets various objects from the
    request object and saves them in thread local storage.
    """
    def process_request(self, request):
        _thread_locals.request = request

Then in your settings.py make sure to enable the middleware
MIDDLEWARE_CLASSES = (
    'myproject.myapp.forms.ThreadLocals',
)

And finally accessing the request object is as easy as
class GroupForm(forms.ModelForm):
    class Meta:
        model = Group

        def clean(self):
            cleaned_data = super(GroupForm, self).clean()
            self.request = _thread_locals.request


text:
Q: JAVA. JTABLE - How to count currently selected row(s) I need to count selected row for removing multiple rows. Please help with the steps.
Example in the picture I want to delete/remove those selected rows at the same time.

A: table.getSelectedRows().length


text:
Q: Eclipse + C: unresolved inclusion  I am trying to write a code in C in Eclipse, but I am getting an error while trying to include library ulfius.
#include <stdio.h>
#include <string.h>
#include <time.h>
error "Unresolved inclusion" here-> #include <ulfius.h>

And when I try to run it I'm getting "Launch failed. Binary not found". Any idea how could I fix this?


text:
Q: Como criar um regex para apagar letras e número depois da 3ª casa decimal Preciso de uma expressão regular com as seguintes regras:

*

*Apagar tudo que é letra

*Apagar tudo que é número depois da 3ª casa decimal

Por exemplo, se eu digitar 34,444 qualquer próximo número será apagado. Se eu digitar a também será apagado.
 $scope.validateLimits = function(){
    $scope.numLimiteInferior = $scope.numLimiteInferior.replace(/\d|,/g,'');
 }

A: A regex que você usou (/\d|,/) significa "um dígito ou uma vírgula", o que significa que você está substituindo os números e as vírgulas por '' (ou seja, está removendo todos os números e vírgulas da string).

Sugiro fazer por partes: primeiro remova as letras e depois remova as casas decimais:

let x = '3b4,4444444a';
x = x.replace(/[a-zA-Z]/g, '').replace(/(,\d{3})\d+/, '$1');
console.log(x); // 34,444

Para letras eu usei [a-zA-Z] (qualquer letra de a a z, maiúscula ou minúscula).
Para as casas decimais eu usei parênteses para formar um grupo de captura, e dentro deles coloquei ,\d{3} (vírgula seguida 3 números). Como esta parte está dentro de parênteses, caso exista uma vírgula seguida de 3 números, eles farão parte do grupo de captura. E como é o primeiro par de parênteses, então será o primeiro grupo.
Depois tem \d+ (um ou mais dígitos), e em vez de substituir pela string vazia, eu uso a referência $1, que significa "tudo que corresponde ao primeiro grupo de captura". No nosso caso, é a vírgula seguida de 3 dígitos. Sendo assim, eu mantenho a vírgula e os 3 dígitos seguintes, e elimino todos os números da quarta casa decimal em diante.
Repare também que para remover as letras eu uso a flag g, pois assim todas as letras são removidas. Já na segunda regex eu não uso o g, pois estou assumindo que só haverá uma vírgula seguida de números.
Além disso, a regex /[a-zA-Z]/g não considera letras acentuadas. Se quiser, pode mudá-la para /[a-záàâãéèêíïóôõöúçñ]/ig (com a opção i para aceitar tantos maiúsculas quanto minúsculas, assim ela fica mais curta). Se quiser, nesta pergunta tem outras opções de regex para letras acentuadas.


text:
Q: Basic Azure DevOps flow for ASP .Net I have a standard way of working for building and deploying my asp .net applications on a build server (usually Jenkins). I have a custom build script and publish profile that builds my solution, copies some files and publishes the web project all with a single call to MSBuild.
I am trying to recreate this in Azure DevOps. My first obstacle seems to be that build and "publish" (or "release" in DevOps parlance) are separate steps. But it also seems like maybe I don't need to "publish"?
So

*

*How do I control what ends up in the "artifacts" folder of the build? Is that through Azure? Can I do it with a .MSBuild file? And

*Do I even need the concept of "publish" or does the release step just copy all artifacts to the destination (a VM in this case)? Can I control what gets deployed?

I am having a hard time finding some kind of basic tutorial that cover asp .net projects being deployed this way.

A: If you have existing scripts that work, just use those :). The new YAML builds are moving slowly away from fully featured UI tasks with lots of logic to more bare bones scripts that do what is needed.
It is a common practice though to split build from publish. That way you can put in additional checks, reviews and approvers on the release stage.
In your case it would mean:

*

*Build stage

*

*Use MsBuild to build & create a publish package either in the form of a folder or a zip file.

*Use the Publish Pipeline Artifact task to store this folder or zip file

*Release stage

*

*Use the Download Pipeline Artifact task to restore the file to publish

*Optionally use a Infra as Code tool to prep the target environment.

*Use msdeploy.exe or another tool to publish the package. Optionally generate and pass in a settings file to override certain settings.

This way you can have multiple release stages to generate test environments, temporary POC environments etc by simply using another set of variables and/or settings override file.
There are special tasks in Azure Pipelines that wrap around these tools and provide an easy to use UI and some additional logic. These can be very useful if you don't have intimate knowledge of the commandline tools. If you do know your way around them, there may not be a very strong reason to use the fancy tasks.

A:

*

*How do I control what ends up in the "artifacts" folder of the build? Is that through Azure? Can I do it with a .MSBuild file?

Yes, we could use the MSBuild Arguments parameter /p:PackageLocation=$(build.artifactstagingdirectory) to control what ends up in the "artifacts" folder.
When we use the task Visual Studio build to build the project, we could edit the MSBuild Arguments parameter to be like: /p:DeployOnBuild=true /p:PublishProfile=Test /p:PackageLocation=$(build.artifactstagingdirectory)
Then we could use Publish Build Artifacts task to publish build artifacts to Azure Pipelines, TFS, or a file share.

*Do I even need the concept of "publish" or does the release step just copy all artifacts to the destination (a VM in this case)? Can I control what gets deployed?

Yes, you can simply understand the release step just copy artifacts to the destination. If you want to control what gets deployed, you can filter the artifacts when you use the copy task with contents.
Check the article Deploying Web Applications Using Team Build and Release Management for the details.
Hope this helps.


text:
Q: Скролл до блока с учетом высоты фиксированного меню Здравствуйте,
этим кодом я реализую скролл до блока.
$(document).on("click", ".scroll", function(t) {
    t.preventDefault();
    var i = $(this).attr("href"),
        e = $(i),
        s = e.offset().top;
    return $("html,body").animate({
        scrollTop: s
    }, 1e3), !1
})

Подскажите как изменить код, чтобы при скролле учитывалась высота фиксированного меню? Например высота меню 200px


text: Q: Where should private keys be stored in e2ee? I'm creating an web app which users can make end-to-end encreypted agreements with each other. I think that the most secure way to handle the situation is to store public keys on the server and private keys locally on client's device. But I couldn't find a source on where to store the private keys in user's device. Where would be the best place to store private keys in client's device? Also, when user wants to login from an another device should he transfer his private key through QR everytime?


text:
Q: Stiction, friction and sticking If we have two flat surfaces touching each other and apply a force parallel to the surfaces, one may move relative to the other.
An example would be a polymer block gliding on another.
Dependent on the surface properties, they could smoothly and easily glide,
or be hard to move, or just stick together, with no relative movement.
The first is an example for low friction,
the second shows high friction, and in the third case, there is very high friction, so high that the force we apply is not enough to move it, called static friction. Alternatively, one could say they stick together.
But with some surface properties, there are further variants:
The surfaces can at first stick together, and then begin to move.
And, different from that, there is the case when the surfaces intermittently stick together and move with high friction. I think this case is called stiction, but I have seen this term being used for the previous case also.
I would like to know what the term stiction is referring to,
and ideally, understand how the last two cases are related.

A: According to Webster, Stiction is the force required to cause one body in contact with another to begin to move.
And from Wikipedia we get: Any solid objects pressing against each other (but not sliding) will require some threshold of force parallel to the surface of contact in order to overcome static cohesion. Stiction is a threshold, not a continuous force.
It sounds like both your cases are examples of stiction. In the 2nd case the area of the blocks encounter a large static friction area and stop sliding. Then stiction comes into play again. But ideally it means that two blocks in contact must experience stiction to start sliding.


text:
Q: how to update foreign key in many to many relationship i'm new in php,i have 2 table with many to many relation and another table for relations:

each time i want update foreign table i'm give the error:
Cannot add or update a child row: a foreign key constraint fails (`wikiseda`.`genre_singer`, CONSTRAINT `genre_singer_ibfk_1` FOREIGN KEY (`f_singer_id`) REFERENCES `singers` (`singerid`) ON DELETE CASCADE ON UPDATE CASCADE);

this is my code:
<?php
include('../db_inc.php');
define("UPLOAD_DIR",realpath(dirname(__FILE__)));

$singer_name =$_POST['singer_name'];
$singer_gender=$_POST['singer_gender'];
$singer_des=$_POST['singer_description'];
$singer_genre=$_POST['genre_list'];

    $path = UPLOAD_DIR .'/musics/'.$singer_name;
    if(!file_exists($path)){
        mkdir($path,0777,true);
        }

$sql ="INSERT INTO singers(singer_name,singer_gender,singer_description) VALUES ('$singer_name','$singer_gender','$singer_des')" ;
 $singer_id = mysql_insert_id();
$sql2 =("INSERT INTO genre_singer(f_singer_id,f_genre_id) VALUES ('$singer_id','$singer_genre')");

$result=mysql_query($sql)or die(mysql_error());
$result2=mysql_query($sql2)or die(mysql_error());
if('$result'){
    echo "insert successfully";

    };
?>

A: SQL injection vulnerabilities and overly-loose directory permissions aside for a moment (though you really should pay heed to the comments about them). Try executing your first query before trying to get the id last inserted hence:
$sql ="INSERT INTO singers(singer_name,singer_gender,singer_description) VALUES ('$singer_name','$singer_gender','$singer_des')" ;
$result=mysql_query($sql)or die(mysql_error());

$singer_id = mysql_insert_id();
$sql2 =("INSERT INTO genre_singer(f_singer_id,f_genre_id) VALUES ('$singer_id','$singer_genre')");
$result2=mysql_query($sql2)or die(mysql_error());

A: You are trying to get the id of the inserted record before actually inserting it.
You need to move your first query execution - $result=mysql_query($sql)or die(mysql_error()); before $singer_id = mysql_insert_id();.
Also:

*

*Your code is vulnerable to SQL injection (as others noted).

*Creating a directory on your server with an arbitrary path/name which comes from the user is probably a bad idea. If you follow that up with creating a file in a similar way you will allow any user to execute arbitrary code on your server.

A: For the sake of being complete, here's the work done with PDO:
// note: untested code follows
$pdo = new PDO('mysql:host='.$host.';dbname='.$db_name, $username, $password);

$statement = $pdo->prepare('
    INSERT INTO `singers` (
        singer_name,
        singer_gender,
        singer_description
    ) VALUES (
        :singer_name,
        :singer_gender,
        :singer_des
    )
');

$statement->execute(array(
    'singer_name'=>$_POST['singer_name'],
    'singer_gender'=>$_POST['singer_gender'],
    'singer_des'=>$_POST['singer_description']
));
$singer_id = $pdo->lastInsertId();

if (!$singer_id) {
    // tip: do something nicer than die
    die('Error occurred:'.implode(":",$pdo->errorInfo()));
}

$statement = $pdo->prepare('
    INSERT INTO `genre_singer` (
        f_singer_id,
        f_genre_id
    ) VALUES (
        :singer_id,
        :singer_genre
    )
');
$result = $statement->execute(array(
    'singer_id'=>$singer_id,
    'singer_genre'=>$_POST['genre_list']
));

if (!result) {
    // tip: do something nicer than die
    die('Error occurred:'.implode(":",$pdo->errorInfo()));
}

Documentation

*

*PDO - http://us1.php.net/manual/en/pdo.errorinfo.php

*PDO::prepare - http://us1.php.net/manual/en/pdo.prepare.php

*PDOStatement::execute - http://php.net/manual/en/pdostatement.execute.php

*PDO::errorInfo - http://us1.php.net/manual/en/pdo.errorinfo.php

*PDO::lastInsertId - http://php.net/manual/en/pdo.lastinsertid.php


text: Q: New iOS Token Based Authentication Notifications: how? I watched the video at: The WWDC 2016 session but I am sorry I was not able to make a sense of it to actually register to send notifications with the new system. I downloaded the APNsAuthKey certificate and got stuck there. The video talks about signing tokens with that but I am totally blank about what that means, when to be implemented in php. Is there some tutorial about how to send notifications with the new token based authentication? My old certificates elapse on March 16 and so I am quite in a hurry to implement the new system. May someone help?


text:
Q: Filter a dataframe with dplyr in R Hey I want to make this code work:
data = data %>% filter(value1=="city" & !is.na(value2)) %>% group_by(A_id, B_id)  %>%
    filter(date==min(as.Date(date,"%d.%m.%Y"))) %>% select(A_id, B_id, date)

I get the following error: Caused by error in charToDate(), character string is not in a standard unambiguous format. But if I work with the date column in other lines of code it works fine... Doesnt help to change it to date format before the filtering, same error..
This is my existing dataframe for the example A_id and B_id:

A_id
B_id
date

1
1
01.01.2020

1
1
01.11.2021

1
2
05.12.2019

1
2
31.01.2020

2
1
05.12.2019

2
1
01.11.2021

2
3
01.11.2021

2
3
31.01.2020

I would like to receive the following table: (which date format exactly doesnt matter)

A_id
B_id
date

1
1
01.01.2020

1
2
05.12.2019

2
1
05.12.2019

2
3
31.01.2020

Anybody who could help?

A: Use slice_min which takes the minimum value in each group:
data %>%
  group_by(A_id, B_id) %>%
  slice_min(as.Date(date, "%d.%m.%Y"))

# A tibble: 4 × 3
# Groups:   A_id, B_id [4]
   A_id  B_id date
  <int> <int> <chr>
1     1     1 01.01.2020
2     1     2 05.12.2019
3     2     1 05.12.2019
4     2     3 31.01.2020

If you wanna keep filter, you should format your string on both sides:
data %>%
  group_by(A_id, B_id) %>%
  filter(as.Date(date,"%d.%m.%Y") == min(as.Date(date,"%d.%m.%Y")))


text:
Q: Is force due to pressure equally distributed? Pressure is defined as: $$P=\frac{F}{A}$$
My question is what if we want to find the total force in area of $\frac{A}{2}$. Would be equal to $\frac{F}{2}$? I think that is not true unless we know that the force is equally distributed along the surface contact. It is like trying to find mass from the formula: $\rho=\frac{m}{V}$ when the density is not constant. Why pressure is not defined as: $$P=\frac{dF}{dA}$$
Consider a cube made of two equal smaller cubes. The one half has a mass $m_1=500$ $g$ and the other half has mass $m_2=1$ $g$. The cube is sitting on the table. According to the first formula the pressure would be the same in each side of the area of contact irrespective of the mass which is above that area. Is this true? I came up with this this question when I thought about the pressure from gas particles inside a container. We know that if we measure the pressure with a manometer we would find the same value in every point of the container. But knowing the total force that is exerted on the wall of the container and dividing by the area of the wall does not implies that the pressure must be equal in every point of the wall. Does a more formal definition of pressure exist which takes into account the fact that force maybe is not equally distributed?

A: It seems like you're basically flip-flipping between "average pressure" and "actual pressure" with your $P$.
If the $P$ you use in the equation just represents some average pressure across the measured area, not the actual pressure at each point; of course you might run into issues when you try to use a smaller area than the one the average was calculated on.
That said, you typically just wouldn't do that, because it would be confusing.  If someone says the pressure at the surface is just $P$, you would typically assume that it's $P$ uniform across the entire surface, unless told otherwise.  If you $P$ isn't uniform (it could be a function of time and/or position), then you need to be careful to calculate the forces based on the actual pressure.
This can be seen from your $P = \frac {dF}{dA}$.  You can rearrange to find the net force: $$F = \int_{x_1}^{x_2}\int_{y_1}^{y_2} P(x,y) dx dy$$ The integral basically just adds up all the infinitesimally small "areas" that the different pressures act on, and sum them into the total force. (there's a bit more with vectors typically, but I omitted all that here just to illustrate my main point)
As far as your cube example goes, I don't see how you conclude that they would have the same pressure.  Pressure is force over area, and the heavier cube would apply more force to the same area, and thus have a higher pressure acting on it.


text:
Q: Unmet dependencies error when installing Kali 2016 I have Ubuntu 16.04 with Ubuntu-Gnome3-Desktop/Shell. I immediately performed sudo apt-get upgrade after install, no issues there. Everything worked beautifully until I attempted to install Kali-Linux-2016.1 packages using the Katoolin tool package. Repositories were successfully added, packages were successfully downloaded, but then when I tried sudo apt-get upgrade I ran into some problems as you'll see below in the text taken directly from my terminal
robert@X17:~$ sudo apt autoremove

Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these.
The following packages have unmet dependencies:
 gnupg2 : Depends: gnupg-agent (= 2.1.11-6ubuntu2)
E: Unmet dependencies. Try using -f.

robert@X17:~$ sudo apt-get install gnupg-agent

Reading package lists... Done
Building dependency tree
Reading state information... Done
gnupg-agent is already the newest version (2.1.11-7).
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 gnupg2 : Depends: gnupg-agent (= 2.1.11-6ubuntu2)
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

robert@X17:~$ sudo apt-get -f install

Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages were automatically installed and are no longer required:
  libasn1-8-heimdal libgssapi3-heimdal libhcrypto4-heimdal
  libheimbase1-heimdal libheimntlm0-heimdal libhx509-5-heimdal
  libkrb5-26-heimdal libroken18-heimdal libwind0-heimdal linux-sound-base
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
  gnupg2
Suggested packages:
  gnupg-doc parcimonie xloadimage
The following packages will be upgraded:
  gnupg2
1 upgraded, 0 newly installed, 0 to remove and 969 not upgraded.
70 not fully installed or removed.
Need to get 0 B/1,389 kB of archives.
After this operation, 3,555 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
dpkg: dependency problems prevent processing triggers for gconf2:
 gconf2 depends on python3:any; however:
  Package python3 is not configured yet.

dpkg: error processing package gconf2 (--configure):
 dependency problems - leaving triggers unprocessed
dpkg: dependency problems prevent processing triggers for gconf2:
 gconf2 depends on python3:any; however:
  Package python3 is not configured yet.
#^^^ These dpkg errors repeat maybe 50 times, I have edited out most repeats for your sake
 gconf2
 gconf2
#(This repeats ~50 times)
 gconf2
 gconf2
 gconf2
Processing was halted because there were too many errors.
E: Sub-process /usr/bin/dpkg returned an error code (1)

robert@X17:~$ sudo apt autoremove

Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these.
The following packages have unmet dependencies:
 gnupg2 : Depends: gnupg-agent (= 2.1.11-6ubuntu2)
E: Unmet dependencies. Try using -f.

robert@X17:~$ sudo apt-get remove python3

Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 apparmor : Depends: python3:any
 apport : Depends: python3 but it is not going to be installed
 apport-gtk : Depends: python3 but it is not going to be installed
 aptdaemon : Depends: python3 but it is not going to be installed
             Depends: python3:any (>= 3.2~)
 apturl : Depends: python3:any (>= 3.3.2-2~)
 apturl-common : Depends: python3:any (>= 3.3.2-2~)
#...... (many depend on python3)
 usb-creator-gtk : Depends: python3:any (>= 3.3.2-2~)
 xdiagnose : Depends: python3:any (>= 3.3.2-2~)
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

robert@X17:~$ sudo apt-get autoremove

Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these.
The following packages have unmet dependencies:
 gnupg2 : Depends: gnupg-agent (= 2.1.11-6ubuntu2)
E: Unmet dependencies. Try using -f.

robert@X17:~$ sudo apt-get install python3

Reading package lists... Done
Building dependency tree
Reading state information... Done
python3 is already the newest version (3.5.1-4).
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 gnupg2 : Depends: gnupg-agent (= 2.1.11-6ubuntu2)
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

robert@X17:~$ sudo apt-get -f install

Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages were automatically installed and are no longer required:
  libasn1-8-heimdal libgssapi3-heimdal libhcrypto4-heimdal
  libheimbase1-heimdal libheimntlm0-heimdal libhx509-5-heimdal
  libkrb5-26-heimdal libroken18-heimdal libwind0-heimdal linux-sound-base
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
  gnupg2
Suggested packages:
  gnupg-doc parcimonie xloadimage
The following packages will be upgraded:
  gnupg2
1 upgraded, 0 newly installed, 0 to remove and 969 not upgraded.
70 not fully installed or removed.
Need to get 0 B/1,389 kB of archives.
After this operation, 3,555 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
dpkg: dependency problems prevent processing triggers for gconf2:
 gconf2 depends on python3:any; however:
  Package python3 is not configured yet.

dpkg: error processing package gconf2 (--configure):
 dependency problems - leaving triggers unprocessed
dpkg: dependency problems prevent processing triggers for gconf2:
 gconf2 depends on python3:any; however:
  Package python3 is not configured yet.
#^^^ These dpkg errors repeat maybe 50 times, I have edited out most repeats #    for your sake
dpkg: error processing package gconf2 (--configure):
 dependency problems - leaving triggers unprocessed
No apport report written because MaxReports is reached already
                                                              dpkg:

dpkg: error processing package gconf2 (--configure):
 dependency problems - leaving triggers unprocessed
No apport report written because MaxReports is reached already
                                                              dpkg: dependency problems prevent processing triggers for gconf2:
 gconf2 depends on python3:any; however:
  Package python3 is not configured yet.

dpkg: error processing package gconf2 (--configure):
 dependency problems - leaving triggers unprocessed
No apport report written because MaxReports is reached already
                                                              dpkg: too many errors, stopping
Errors were encountered while processing:
 gconf2
 gconf2
#...
 gconf2
 gconf2
Processing was halted because there were too many errors.
E: Sub-process /usr/bin/dpkg returned an error code (1)

#Next I tried (with no success) the solution outlined here: http://askubuntu.com/questions/434742/cannot-install-python3-after-dist-upgrade

robert@X17:~$ sudo nano /usr/lib/python3.3/sre_constants.py

robert@X17:~$ sudo nano /usr/lib/python3.5/sre_constants.py

robert@X17:~$ sudo nano /usr/lib/python3.5/sre_parse.py

robert@X17:~$ sudo nano /usr/lib/python3.5/sre_compile.py

Use "fg" to return to nano.

[1]+  Stopped                 sudo nano /usr/lib/python3.5/sre_compile.py

robert@X17:~$ sudo nano /usr/lib/python3.5/sre_compile.py

robert@X17:~$ sudo apt-get -f install

Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages were automatically installed and are no longer required:
  libasn1-8-heimdal libgssapi3-heimdal libhcrypto4-heimdal
  libheimbase1-heimdal libheimntlm0-heimdal libhx509-5-heimdal
  libkrb5-26-heimdal libroken18-heimdal libwind0-heimdal linux-sound-base
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
  gnupg2
Suggested packages:
  gnupg-doc parcimonie xloadimage
The following packages will be upgraded:
  gnupg2
1 upgraded, 0 newly installed, 0 to remove and 969 not upgraded.
70 not fully installed or removed.
Need to get 0 B/1,389 kB of archives.
After this operation, 3,555 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
dpkg: dependency problems prevent processing triggers for gconf2:
 gconf2 depends on python3:any; however:
  Package python3 is not configured yet.

dpkg: error processing package gconf2 (--configure):
 dependency problems - leaving triggers unprocessed
dpkg: dependency problems prevent processing triggers for gconf2:
 gconf2 depends on python3:any; however:
  Package python3 is not configured yet.

dpkg: error processing package gconf2 (--configure):
 dependency problems - leaving triggers unprocessed
dpkg: dependency problems prevent processing triggers for gconf2:
 gconf2 depends on python3:any; however:
  Package python3 is not configured yet.

dpkg: error processing package gconf2 (--configure):
 dependency problems - leaving triggers unprocessed
dpkg: dependency problems prevent processing triggers for gconf2:
 gconf2 depends on python3:any; however:
  Package python3 is not configured yet.
#^^^ These dpkg errors repeat maybe 50 times, I have editted out most repeats #    for your sake

dpkg: error processing package gconf2 (--configure):
 dependency problems - leaving triggers unprocessed
No apport report written because MaxReports is reached already
                                                              dpkg: too many errors, stopping
Errors were encountered while processing:
 gconf2
#...
 gconf2

Processing was halted because there were too many errors.
E: Sub-process /usr/bin/dpkg returned an error code (1)

robert@X17:~(

What is the problem here and how to fix it?

A: Here's what I've done and it seemed to work.
Re-write sources.list from /etc/apt using the default sources.list file, as specified in the Ubuntu 16.04 documentation.
sudo apt-get update
sudo apt-get -f install
sudo apt-get upgrade

Now I understand that there may be issues when mixing repositories from different Debian distros. I may try to install some Kali default packages one package at a time now, would be harder to mess everything up at once.