text:
Q: Remove digits after decimal notepad++ Basically all over the document I have values like
2014-01-23 15:09:31.879958
I want to remove the last 6 digits and the . using find and replace. I've gotten
(\d{6})

To find the 6 digits but I also need it to find the . so I can replace it with nothing

A: Try: \.\d{6} - the \. escapes the dot.

A: In this case, you should be able to simply add a period to your find/replace.
As a test, I copied your example multiple times in a document. I then attempted to Find the following: \.(\d{6}) and replace with a blank
Give that a try and see if that works for you.
Cheers,
Edited to add the slash that I apparently didn't type. Silly.


text:
Q: jest how to test a function inside of a react component I have been trying to test a function inside of a react component to get 100% coverage but I am been searching for answers but was stuck so coming here for your help. Below is my code. How can I make a jest mock out of the deleteHandler inside Schedule.tsx. My coverage report is asking me to test this code.
Schedule.tsx
const Schedule : FunctionComponent<{id: number, name: string, time: string}> = (props) => {
  const dispatch = useDispatch();
  const { deleteSchedule } = bindActionCreators(actionCreators, dispatch);

  const deleteHandler = () => {
    deleteSchedule(props.id);
  };

  return (
    <ScheduleContainer>
      <ButtonDelete onClick={deleteHandler}>x</ButtonDelete>
      {props.name} - Time: {props.time}
    </ScheduleContainer>
  );
};

export default Schedule;

I tried below method but realized that my test block cannot receive the deleteHandler from my mockComponent function because of block scoping
Schedule.test.js
const renderWithRedux = (
  component,
  { initialState, store = createStore(reducer, initialState) } = {}
) => {
  return {
    ...render(<Provider store={store}>{component}</Provider>),
  };
};

const mockComponent = () => {
  const deleteHandler = jest.fn();

  return <Schedule />;
}

test("handle click", () => {
  renderWithRedux(mockComponent);
  const deleteButton = screen.getByRole("button", { name: "x" });
  fireEvent.click(deleteButton);
  expect(deleteHandler).toHaveBeenCalled();
})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Vim: The way to execute same command in command-line mode multiple times I'm recently working on a project in vim, and I need to execute the same command to different files which are in the same folder in command-line mode multiple times.
like
:%s/V1/V2/g

Is there a easiler way to do this?

A: It's command-line mode, not "command mode".
From within Vim

*

*Set your :help argument-list to the desired list of files:
:arg /path/to/dir/*.xyz

*Perform your substitution on every file in the argument list and write it if there was a change:
:argdo %s/V1/V2/g | update

See :help :arg, :help :argdo, :help :update.
From your shell

*

*Start Vim with each desired file as argument:
$ vim /path/to/dir/*.xyz

*Perform your substitution on every file in the argument list and write it if there was a change:
:argdo %s/V1/V2/g | update


text:
Q: Recording headless chrome I currently have some UI tests running in Jenkins using headless Chrome.
I am able to take screenshots but I was wondering how I could record videos from my testruns.
I read that xvfb is a possibility but since headless chrome is available, I was wondering if it would be possible to do this via devtools itself or some Java library.
Thanks in advance.
Regards


text:
Q: jquery selectmenu variable in php via ajax I want to get a jquery (a selectmenu) variable to php. I try it with Ajax "POST". For testing purpose i just want to echo out the selected number of the selectmenu without any page refresh. So the Change should appear dynamically.
Here is my html_file.php

<select name="number" id="number">
  <option>1</option>
  <option selected="selected">2</option>
  <option>3</option>
  </select>

And here the php_file.php
<?php

$test = $_POST['number'];

// Output of the selcetmenu for testing

echo '
', $test, '
';

?>

I think there is some mistake in the Ajax function.

A: Pass key as number and assign value to number key as
        $.ajax({
                method: "POST",
                url: "php_file.php",
                data: { number : yournumber }
            })

A: You have to give your data property a value.
Try:
$.ajax({
  method: "POST",
  url: "php_file.php",
  data: {
    number: $("#number").val()
  }
})


text:
Q: R: Adding two matrices with different dimensions based on columns I have 22 matrices having equal number of rows (i.e. 691) and different number of columns (i.e. 22-25). I have to add the values corresponding to same row, same column in each of the matrices resulting in one single matrix of the dimension 691*25.
fullanno1 has 691 rows & 25 columns:
>colnames(fullanno1)
[1] "coding-notMod3"                "coding-synonymous"             "coding-synonymous-near-splice"
[4] "intergenic"                    "intron"                        "missense"
[7] "missense-near-splice"          "near-gene-3"                   "near-gene-5"
[10] "splice-3"                      "splice-5"                      "stop-gained"
[13] "stop-gained-near-splice"       "stop-lost"                     "utr-3"
[16] "utr-5"                         "CTCF"                          "E"
[19] "None"                          "PF"                            "R"
[22] "T"                             "TSS"                           "WE"
[25] "coding-notMod3-near-splice"

fullanno2 has 691 rows and 22 columns:
>colnames(fullanno2)

[1] "coding-synonymous"             "coding-synonymous-near-splice" "intergenic"
[4] "intron"                        "missense"                      "missense-near-splice"
[7] "near-gene-3"                   "near-gene-5"                   "splice-3"
[10] "splice-5"                      "stop-gained"                   "stop-lost"
[13] "utr-3"                         "utr-5"                         "CTCF"
[16] "E"                             "None"                          "PF"
[19] "R"                             "T"                             "TSS"
[22] "WE"

Each matrix is a double matrix with numerical values. How can I add these two matrices such that I get a third matrix with dimensions 691*25. Because fullanno2 is three columns short, for those columns the resulting matrix will have values only from the first matrix.
My approach:
Take a setdiff of the colnames to get columns that are not present in the smaller matrix, cbind them to the smaller matrix with 0s as values. Then add the two matrices.
> column.names<-setdiff(colnames(fullanno1),colnames(fullanno2))
[1] "coding-notMod3"             "stop-gained-near-splice"    "coding-notMod3-near-splice"
> column<-0
>cbind(fullanno2,column)
>colnames(fullanno2)[23]<-column.name[1]
>cbind(fullanno2,column)
>colnames(fullanno2)[24]<-column.name[2]
>cbind(fullanno2,column)
>colnames(fullanno2)[25]<-column.name[3]

But this is getting tedious for all the matrices. Any suggestions?

A: You can use match along with colnames.  For example:
> m1<-matrix(1,3,5)
> colnames(m1)<-LETTERS[1:5]
> m2<-matrix(1:9,3,3)
> colnames(m2)<-c("D","A","C")
> m1
     A B C D E
[1,] 1 1 1 1 1
[2,] 1 1 1 1 1
[3,] 1 1 1 1 1
> m2
     D A C
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

> m3<-m1
> mcol<-match(colnames(m2),colnames(m1))
> m3[,mcol]<-m3[,mcol]+m2
> m3
     A B  C D E
[1,] 5 1  8 2 1
[2,] 6 1  9 3 1
[3,] 7 1 10 4 1

A: So you want to sum all of the matrices to end up with one matrix? A simple but perhaps slow (I suspect, but it's probably not a big deal with your matrices) way is to use the plyr and reshape2 libraries. You could start with a list of your matrices:
make.matrix <- function() {
  cols <- sample(month.name, runif(1, 2, 12))
  matrix(rnorm(length(cols)*10), 10, length(cols), dimnames=list(NULL, cols))
}

# Make 10 matrices filled with random numbers, having
# varying numbers of columns named after months
my.matrices <- replicate(10, make.matrix())

Then you can melt all the matrices into one big dataframe
matrix.df <- ldply(my.matrices, melt, varnames=c("row", "col"))
head(matrix.df)
#   row      col      value
# 1   1 February -0.4239145
# 2   2 February  1.1773608
# 3   3 February -2.9565403
# 4   4 February  0.3955096
# 5   5 February -0.3784917
# 6   6 February -0.6234579

and then cast it back into a matrix.
sum.matrix <- acast(matrix.df, row ~ col, sum)


text:
Q: Win2D: Correct usage of CanvasVirtualControl I want to draw the mandelbrot-set taken from the Win2D-Example-Gallery and tweak it a little.
At first I had all my code to generate the mandelbrot inside the CreateResources-Method of CanvasAnimatedControl, but due to performance issues I went on to do it using shaders (HLSL or PixelShaderEffect) and CanvasVirtualControl:
public PixelShaderEffect _effectMandel;
CanvasVirtualImageSource _sdrc;

public async Task CreateResources(CanvasVirtualControl sender)
{
    _sdrc = new CanvasVirtualImageSource(sender, new Size(_width, _height));
    var arr = await FileHelper.ReadAllBytes("Shaders/Mandelbrot.bin");
    if (arr != null)
    {
        _effectMandel = new PixelShaderEffect(arr);

        using (CanvasDrawingSession drawingSession = sender.CreateDrawingSession(new Rect(0,0,_width,_height)))
        {
            drawingSession.DrawImage(_effectMandel);
        }
    }
}

When I run the application, I get a System.Runtime.InteropServices.COMException right in the using section and the 'App.g.i.cs' file opens up telling me:

The shader code I use is this:
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

// This shader has no input textures.
// It generates a mandelbrot fractal.

#define D2D_INPUT_COUNT 0
#define D2D_REQUIRES_SCENE_POSITION

#include "d2d1effecthelpers.hlsli"

float scale;
float2 translate;

static const float4 tapOffsetsX = float4(-0.25,  0.25, -0.25, 0.25);
static const float4 tapOffsetsY = float4(-0.25, -0.25,  0.25, 0.25);

static const int iterations = 100;

D2D_PS_ENTRY(main)
{
    float2 pos = D2DGetScenePosition().xy;

    // Improve visual quality by supersampling inside the pixel shader, evaluating four separate
    // versions of the fractal in parallel, each at a slightly different position offset.
    // The x, y, z, and w components of these float4s contain the four simultaneous computations.
    float4 c_r = (pos.x + tapOffsetsX) * scale + translate.x;
    float4 c_i = (pos.y + tapOffsetsY) * scale + translate.y;

    float4 value_r = 0;
    float4 value_i = 0;

    // Evalulate the Mandelbrot fractal.
    for (int i = 0; i < iterations; i++)
    {
        float4 new_r = value_r * value_r - value_i * value_i + c_r;
        float4 new_i = value_r * value_i * 2 + c_i;

        value_r = new_r;
        value_i = new_i;
    }

    // Adjust our four parallel results to range 0:1.
    float4 distanceSquared = value_r * value_r + value_i * value_i;

    float4 vectorResult = isfinite(distanceSquared) ? saturate(1 - distanceSquared) : 0;

    // Resolve the supersampling to produce a single scalar result.
    float result = dot(vectorResult, 0.25);

    if (result < 1.0 / 256)
        return 0;
    else
        return float4(result, result, result, 1);
}

If you know why this happens, please answer. Thanks!

A: I needed to setup a Timer to regularly invalidate the canvas and get 60fps.
I had another look into the Microsoft Examples and finally worked it out using this code:
DispatcherTimer timer;
internal void Regions_Invalidated(CanvasVirtualControl sender, CanvasRegionsInvalidatedEventArgs args)
{
    // Configure the Mandelbrot effect to position and scale its output.
    float baseScale = 0.005f;
    float scale = (baseScale * 96 / sender.Dpi) / (helper._modifiers[1] / 1000f);
    var controlSize = baseScale * sender.Size.ToVector2() * scale;
    Vector2 translate = (baseScale * sender.Size.ToVector2() * new Vector2(-0.5f,-0f));

    _effectMandel.Properties["scale"] = scale;
    _effectMandel.Properties["translate"] = (Microsoft.Graphics.Canvas.Numerics.Vector2)translate;
#endif

    // Draw the effect to whatever regions of the CanvasVirtualControl have been invalidated.
    foreach (var region in args.InvalidatedRegions)
    {
        using (var drawingSession = sender.CreateDrawingSession(region))
        {
            drawingSession.DrawImage(_effectMandel);
        }
    }

    // start timer for fps
    this.timer = new DispatcherTimer();
    int fps = 60;
    this.timer.Interval = new TimeSpan(0, 0, 0, 0, 100 / fps);
    this.timer.Tick += timer_Tick;
    this.timer.Start();
}

private void timer_Tick(object sender, object e)
{
    this.timer.Stop();
    _canvas.Invalidate();
}

Hope this is helpful to someone.


text:
Q: Creating ranged mapping records from yearly entries I have a table that maps an ID to an Associated ID (AssocID) over time and the database is built having one record per year. I would like to roll up the table have one record for each period of association.
Current Example:
    ID AssocID Start End
    1  a       2000  2001
    1  a       2001  2002
    1  b       2002  2003
    1  b       2003  2004
    1  a       2004  2005
    ...
    1  a       2017  2018
    2  c       2000  2001
    2  c       2001  2002
    2  d       2002  2003
    ...
    2  d       2017  2018

and I am trying to make it look more like this:
    ID AssocID Start End
    1  a       2000  2002
    1  b       2002  2004
    1  a       2004  2018
    2  c       2000  2002
    2  d       2002  2018

My main problem is that ID '1' goes back to AssocID 'a' after time and using DISTINCT (ID, AssocID) and MIN (Start) misses the second time ID '1' maps to AssocID 'a'
Any help appreciated :)

A: You can use this.
 -- Sample Data

 DECLARE @MyTable TABLE (ID INT, AssocID VARCHAR(10),  Start INT, [End] INT)
 INSERT INTO @MyTable VALUES
(1, 'a', 2000, 2001),
(1, 'a', 2001, 2002),
(1, 'b', 2002, 2003),
(1, 'b', 2003, 2004),
(1, 'a', 2004, 2005),
(1, 'a', 2017, 2018),
(2, 'c', 2000, 2001),
(2, 'c', 2001, 2002),
(2, 'd', 2002, 2003),
(2, 'd', 2017, 2018)

-- Query

SELECT ID, AssocID, MIN(Start) [Start], MAX([End]) [End] FROM
    ( SELECT *,
        GRP = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Start) - ROW_NUMBER() OVER(PARTITION BY ID, AssocID ORDER BY Start)
     FROM @MyTable ) T
GROUP BY ID, AssocID, GRP
ORDER BY ID,  [Start]

Result:
ID          AssocID    Start       End
----------- ---------- ----------- -----------
1           a          2000        2002
1           b          2002        2004
1           a          2004        2018
2           c          2000        2002
2           d          2002        2018

A: This is an example of a gaps and islands problem. You need to first identify the start of each group grp_start and then group by each grp to find the min / max
declare @T table (ID int, AssocID varchar(3), Start int, [End] int)
insert into @T (ID, AssocID, Start, [End]) values
(1, 'a', 2000, 2001),(1, 'a', 2001, 2002),(1, 'b', 2002, 2003),(1, 'b', 2003, 2004),(1, 'a', 2004, 2005),(1, 'a', 2005, 2006),(1, 'a', 2006, 2007),(1, 'a', 2007, 2008),(1, 'a', 2008, 2009),(1, 'a', 2009, 2010),(1, 'a', 2010, 2011),(1, 'a', 2011, 2012),(1, 'a', 2012, 2013),(1, 'a', 2013, 2014),(1, 'a', 2014, 2015),(1, 'a', 2015, 2016),(1, 'a', 2016, 2017),(1, 'a', 2017, 2018),(2, 'c', 2000, 2001),(2, 'c', 2001, 2002),(2, 'd', 2002, 2003),(2, 'd', 2017, 2018)

select
    ID,
    AssocID,
    min(Start),
    max([End])
from
(
    select *,
        sum([grp_start]) over (partition by ID, AssocID order by [End]) as grp
    from
    (
        select *,
            case
                when
                    lag([End]) over (partition by ID, AssocID order by [End]) <> [Start]
                then 1 else 0
            end as [grp_start]
        from @T
    ) as T
)as T
group by ID, AssocID, grp
order by ID, min(Start), max([End])


text:
Q: An example of an algebraic loop which has different L and R inverses? Can anyone point me toward a simple example of a non-associative algebraic loop (i.e. a quasigroup with an identity) for which at least one element has a left inverse which is not equal to its right inverse?
That's the end of the question, but here is a little extra detail in case it helps:
I can find plenty of non-associative loops for which the opposite condition is true, i.e. for which the left and right inverses for each element are identical to each other.  The simplest such example I have come across had this Cayley table:
0   1   2   3   4   5   6   7
1   7   5   0   6   2   4   3
2   6   7   5   0   3   1   4
3   0   6   7   5   4   2   1
4   5   0   6   7   1   3   2
5   2   3   4   1   7   0   6
6   4   1   2   3   0   7   5
7   3   4   1   2   6   5   0

which I found here: http://ericmoorhouse.org/pub/bol/htmlfiles8/8_1_4_0.html  This example is clearly a loop as it has (1) the Latin-square property required by quasigroups, and (2) an identity, which in this case is zero. It is also non-associative (which I require) since 3.(4.5)=3.1=0 while (3.4).5=5.5=7. However: all the zeros are spaced symmetrically about the leading diagonal so left and right inverses are identical.  That's not what I want!
A good answer to my question would be a similar Cayley table which has both an identity element and the Latin square property and which is not associative, but which has the identity elements (i.e. the zeros) not distributed symmetrically about the leading diagonal.
Note that an identity (for the purposes of our question, and Loops in general) must be both a left and right identity. Therefore, the following Cayley table is not a valid answer (even though it is a Latin square with non-symmetrically placed zeros) because it demonstrates only a left identity not a right identity (and because it is probably also associative .. though I didn't check this):
0 2 1
1 0 2
2 1 0

The (not necessarily authoritative!) wikipedia page https://en.wikipedia.org/wiki/Quasigroup#Loops suggests that Loops of the form I am looking for do exist.  But if wikipedia is wrong, and there are no non-associative Loops with differing left and right inverses, then a proof of that would also be acceptable as an answer!
P.S.:
My question is almost the opposite of a very old one which wanted to know about loops which had two-sided inverses: Examples of loops which have two-sided inverses.
That question strikes me as strange, in retrospect, because EVERY example of a non-associative loop I have found in the last hour would have answered that question -- almost.

Comment added after this question was successfully answered:
The accepted answer referred to the following Cayley table. I copy it here so that future readers will not have to rely on the stability of a hyperlink in order to be able to read the answer.
∘   0   1   2   3   4
0   0   1   2   3   4
1   1   4   0   2   3
2   2   3   4   1   0
3   3   0   1   4   2
4   4   2   3   0   1

A: Pointer:  https://math.stackexchange.com/a/1444602/123905
The referenced MSE answer exhibits a five element example of a non-associative loop having at least one element with distinct left- and right-inverses.


text:
Q: Two-level grammar with ANTLR 3 I have a grammar which (if you simplify it quite a bit) looks like this:
options
{
    backtrack=true;
}

// parser
text: (TEXT)+;

and_level2_thing: text | '(' and_thing ')';

and_thing: and_level2_thing (OP_AND and_level2_thing)*;

and_expression: and_thing (OP_AND and_thing)*;

parse_starts_here: and_expression EOF;

// lexer
OP_AND : 'AND';
TEXT : ( '"' (~'"')* '"' );

It has two types of groups of expressions top-level (and_thing) and inner-level (and_level2_thing) for which different rules apply but both levels have to support AND e.g. TOP_TYPE_EXPRESSION AND TOP_TYPE_EXPRESSION and
TOP_TYPE_EXPRESSION AND (INNER_TYPE_EXPRESSION AND INNER_TYPE_EXPRESSION).
When I have a value of the form:
(TOP_TYPE_EXPRESSION AND (TOP_TYPE_EXPRESSION AND (TOP_TYPE_EXPRESSION AND (TOP_TYPE_EXPRESSION))))
the time starts to become exponential on the nesting level presumably because the AND is ambiguous. This expression evaluates instantly:
TOP_TYPE_EXPRESSION AND TOP_TYPE_EXPRESSION AND TOP_TYPE_EXPRESSION AND TOP_TYPE_EXPRESSION
If you say this isn't a well designed language - I perfectly agree, but that's what I have right now :). Any ideas how to avoid this problem?

A: Adding memoize "fixes" the problem. But I'm sure there's a better solution or some more interesting discussion around it.
options
{
    backtrack=true;
    memoize=true;
}

A: Your grammar is ambiguous:
"a" AND "b"

can be matched as
parse_starts_here
  and_expression
    and_thing
      and_level2_thing
        text
      OP_AND
      and_level2_thing
        text

or as
parse_starts_here
  and_expression
    and_thing
      and_level2_thing
        text
    OP_AND
    and_thing
      and_level2_thing
        text

Normally, ANTLR would warn you about this ambiguity, but by declaring backtrack = true, you effectively tell ANTLR to try all alternatives and use first that matches.
On unambiguous grammars ANTLR runs in linear time. Use of backtracking leads to potentially exponential time. memoize=true is used to reduce the time back to linear at the cost of more memory used.
I would recommend removing the backtrack=true option. ANTLR will then tell you where the grammar is ambiguous. You can either remove the ambiguity, or if it is not possible, use syntactic predicates only where needed to prefer one possible match to the other. memoize=true would still help if you end up using syntactic predicates.

Edit - As to why there's backtracking even when both alternatives match:
It does not backtrack, but the time will still be exponential.
The problem is that ANTLR doesn't know it can match the first alternative until it actually tries to match it (since you didn't give it any hints). So it will first try to match the rule, and if it succeeds it will actually match it and perform all associated actions (memoize option avoids exactly this by remembering the particular rule succeeded for the given input position and not repeating the whole matching process).
Example:
"a" AND ( "b" AND "c" )

To match this, ANTLR must:

*

*Match "a"

*Decide whether the AND can be matched using the inner rule

*

*To do this, it tries to match the inner rule

*AND matches, ( means go to and_thing

*To match and_thing, it must:

*

*Match ( and "b"

*Decide whether the AND can be matched using the inner rule

*

*To do this, it tries to match the inner rule against AND "c"

*The predicate succeeds - AND "c" matches the inner rule

*Match the inner rule against AND "c"

*Match )

*The predicate succeeds - AND ( "b" AND "c" ) matches the inner rule

*Match the inner rule against AND ( "b" AND "c" )

*

*AND matches, ( means go to and_thing

*To match and_thing, it must:

*

*Match ( and "b"

*Decide whether the AND can be matched using the inner rule

*

*To do this, it tries to match the inner rule against AND "c"

*The predicate succeeds - AND "c" matches the inner rule

*Match the inner rule against AND "c"

*Match )
AS the emphasized parts of the process show, ANTLR needs to match the text AND "c" four times to match the input, while there's one level of nesting. If there was another level, this whole process would repeat twice, so ANTLR would parse the last part eight times.

One related remark - if you use syntactic predicates rather than backtrack option, you can fine-tune what the predicate contains - in some cases it needs not contain the whole rule being predicated. In your example above, you could just tell ANLTR to use the OP_AND and_level2_thing rule whenever it encounters OP_AND, without needing to check whether and_level2_thing matches. Note that you can only do this because you know that either and_level2_thing will match, or the other alternative will fail as well. If you do this wrong you end up with the parser getting lost and refusing an input that would be valid if it chose the right alternative.


text:
Q: mongorestore collections with metoer running on local windows 10 I have a dump folder which was created few year ago using mongodump, and want to use this info with a newly created metor app which is the same as the old meteor app after few packages updates and runs without errors.
I installed the mongodb server on this windows 10, the cmd mongo prints

connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
  MongoDB server version: 4.2.7

what is the "best" way to use the info with the meteor app.
Can some one  please give the overview of how all this things work together and then how to use the old info "including the command mongorestore" with the newly created metoer app?
It has been few years so will need polish my thinking on meteor and mongodb again.
My understanding is mongorestore the backup, then run the mongodb server in a separate cmd window, issue a cmd to connect to the restored database, and somehow tell meteor to use this server. Ok I give up.
Thanks

A: Meteor comes with a bundled MongoDB in development mode, where the mongodb always runs on the app's port + 1 (app: 3000 = mongo: 3001).
You can simply start your Meteor app and when running open a new console and cd into your project folder, then enter:
mongorestore -h localhost:3001 --db meteor /path/to/dump/


text:
Q: Dispatcher.Invoke doesn't change value of Label In the thread I want to change value of Label
I found out that I have to use Dispatcher.Invoke.
Tried this code:
Me.Dispatcher.Invoke(DispatcherPriority.Background, (Function() Me.Label2.Content = "Scanning done."))

but it doesn't change the value.
What am I doing wrong?
@edit: my target framework is 4.0

A: The most glaring issues are you're using a Function where you should be using a Sub since there is no return value.  Also, your parameters are backward.
The following should work for you:
Me.Dispatcher.Invoke(Sub() Me.Label2.Content = "Scanning done.", DispatcherPriority.Background)

A: Try this (.net 4.5, in c#):
Application.Current.Dispatcher.InvokeAsync(() => Label2.Content = "Scanning done.");


text:
Q: Отследить buttonclick Есть некая прога написанная частично на WPF, частично на winforms. Мне необходимо отследить на какую кнопку нажали в этой проге. Те кнопки что на WPF, я отслеживаю с помощью AutomationElement и InvokePattern.InvokedEvent. С ними проблем нет, получаю название кнопки.
Теперь мне нужно получить название кнопки в окне winforms. Я читал, что AutomationElement работает только с WPF. Но должно же быть хоть что-то для winforms. Перебрал все паттерны и ивенты, ничего не подошло. Может кто-то знает библиотечку в nuget? Хоть что-нибудь... помогите, пожалуйста!!


text:
Q: How do I automatically delete all the github generated patch branches from a fork Every time I make typo corrections when reading other people's github repositories, a branch is created in my repository and they pile up because I never return to the pull request to delete them. I currently have 9 branches with the title patch-1, patch-2... etc... and I'm too lazy to delete them one by one. How can I automatically delete them?

A: If you just need a general script that will delete all merged branches (either locally or remotely, I have a utility script to do just that). To delete all local branches that have been merged:
git-delete-merged --doit --local

To delete all remote branches on origin matching the regex "patch-":
git delete-merged --remote origin --match "patch-" --doit

If you don't want to add a script for a one-off need you can find what you need for a specific one-liner in the source.

A: Use this command I wrote:
git push --delete origin `git branch -r --list 'origin/patch*' | sed 's/origin\/\(.*\)/\1/'`


text:
Q: is it possible to recreate for loop in c++ with a function I recently wrote a simple macro because I was so tired of typing the same thing for every vector I needed to loop through:
#define FORVEC(a,b) for(int b=0;b<a.size();b++)

so I could do something like
vector<sometype> stuff

FORVEC(stuff,i)
{
     stuff[i].dosomething();
}

I try to avoid using macros since I was told at one point by a more experienced programmer to avoid them whenever possible.  also, I'm just curious about how it would be done with a function (or whatever it would take), because that's an area I'd like to explore.  Not specifically recreating this macro necessarily, though that would be a good start, but something where after defining it, I could do something like
mylooperfunction(param1,param2,param3)
{
     //and now any code here would be run and looped in a way controlled by and defined in mylooperfunction
}

A: There's a significantly more advanced version in BOOST_FOREACH that you can use in C++03. What you're talking about isn't in C++03 but is in C++0x with the introduction of lambda expressions.
std::for_each(vec.begin(), vec.end(), [&](const T& ref) {
    ref.do_something();
});

Specifically for this use, there's even a new language feature for it, which in my opinion is a horrific mistake, but that's just me. The above code is much more general-case.

A: The STL Algorithms provide the function you are looking for: std::for_each

A: There are two solutions that already do that: BOOST_FOREACH and std::for_each.

A: Here's what will happen:

*

*you forget the name of your macro

*you start typing existing iterator stuff over and over again

*soon typing it is so automatic that it'll be easy and fast to do

*then your macro will no longer be needed

Of course, getting there takes small amount of effort, but everyone will get there at some point...


text:
Q: Timeout on remote query over database link We are trying to verify if a database link is up before inserting data into a remote database.  We have no control over the remote database's behavior and status.  We need to set a timeout on a query which is using a database link before deciding whether we can insert data.
Currently when the link or the remote database goes down in the middle of a transaction, the user has to wait for up to 20 minutes before regaining control on the session.  We want to set the limit to a minute or less.
We're running Oracle 10gR2.
How can we set a timeout for a query like this?


text:
Q: Seaborn lineplot not plotting means correctly I am trying to plot data from a longform pandas dataframe. When I try to plot the data using seaborn lineplot I get a weird result. Instead of plotting the mean for each x (timepoint) value I get a spikey plot.
my code is:
import seaborn as sns

fig,ax1 = plt.subplots(figsize=(25,7))

sn = sns.lineplot(data=data_test,x="Timepoint",y="value",estimator = None,hue = 'Filename')

fig,ax1 = plt.subplots(figsize=(25,7))

sn = sns.lineplot(data=data_test,x="Timepoint",y="value",marker='o',estimator = 'mean')

Below are examples of the plots I get. The upper one is the individual values which are correct. The lower one should show the mean and confidence intervals of these values, but it is wrong.
Example plots from this code

#Here is an example dataset:
https://docs.google.com/spreadsheets/d/18LHD3dKfkXMvlqxp74uXQqVpHsGHIrtJUucxDMPFt4I/edit?usp=sharing


text:
Q: Alternative to Flutter DataTable that has onTap? I have a list of data using a DataTable yet found out it has no onTap/onPressed, and instead only has onSelected which I don't want, I want to open up another page based on the item I have tapped.
Is there anything equivalent to a DataTable that does?
Seems a bit stupid that it doesn't have something so simple.

A: DataCell has onTap you can use,
In demo, tap first name of certain row will print information
code snippet
cells: [
                DataCell(
                  Text(user.firstName),
                  onTap: () {
                    print('Selected ${user.firstName}');
                  },
                ),

full code
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: DataTableDemo(),
    );
  }
}

class User {
  String firstName;
  String lastName;

  User({this.firstName, this.lastName});

  static List<User> getUsers() {
    return <User>[
      User(firstName: "Aaryan", lastName: "Shah"),
      User(firstName: "Ben", lastName: "John"),
      User(firstName: "Carrie", lastName: "Brown"),
      User(firstName: "Deep", lastName: "Sen"),
      User(firstName: "Emily", lastName: "Jane"),
    ];
  }
}

class DataTableDemo extends StatefulWidget {
  DataTableDemo() : super();

  final String title = "Data Table Flutter Demo";

  @override
  DataTableDemoState createState() => DataTableDemoState();
}

class DataTableDemoState extends State<DataTableDemo> {
  List<User> users;
  List<User> selectedUsers;
  bool sort;

  @override
  void initState() {
    sort = false;
    selectedUsers = [];
    users = User.getUsers();
    super.initState();
  }

  onSortColum(int columnIndex, bool ascending) {
    if (columnIndex == 0) {
      if (ascending) {
        users.sort((a, b) => a.firstName.compareTo(b.firstName));
      } else {
        users.sort((a, b) => b.firstName.compareTo(a.firstName));
      }
    }
  }

  onSelectedRow(bool selected, User user) async {
    setState(() {
      if (selected) {
        selectedUsers.add(user);
      } else {
        selectedUsers.remove(user);
      }
    });
  }

  deleteSelected() async {
    setState(() {
      if (selectedUsers.isNotEmpty) {
        List<User> temp = [];
        temp.addAll(selectedUsers);
        for (User user in temp) {
          users.remove(user);
          selectedUsers.remove(user);
        }
      }
    });
  }

  SingleChildScrollView dataBody() {
    return SingleChildScrollView(
      scrollDirection: Axis.vertical,
      child: DataTable(
        sortAscending: sort,
        sortColumnIndex: 0,
        columns: [
          DataColumn(
              label: Text("FIRST NAME"),
              numeric: false,
              tooltip: "This is First Name",
              onSort: (columnIndex, ascending) {
                setState(() {
                  sort = !sort;
                });
                onSortColum(columnIndex, ascending);
              }),
          DataColumn(
            label: Text("LAST NAME"),
            numeric: false,
            tooltip: "This is Last Name",
          ),
        ],
        rows: users
            .map(
              (user) => DataRow(
              selected: selectedUsers.contains(user),
              onSelectChanged: (b) {
                print("Onselect");
                onSelectedRow(b, user);
              },
              cells: [
                DataCell(
                  Text(user.firstName),
                  onTap: () {
                    print('Selected ${user.firstName}');
                  },
                ),
                DataCell(
                  Text(user.lastName),
                ),
              ]),
        )
            .toList(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        verticalDirection: VerticalDirection.down,
        children: <Widget>[
          Expanded(
            child: dataBody(),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.all(20.0),
                child: OutlineButton(
                  child: Text('SELECTED ${selectedUsers.length}'),
                  onPressed: () {},
                ),
              ),
              Padding(
                padding: EdgeInsets.all(20.0),
                child: OutlineButton(
                  child: Text('DELETE SELECTED'),
                  onPressed: selectedUsers.isEmpty
                      ? null
                      : () {
                    deleteSelected();
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}


text:
Q: how to pass max_streak_length from command line I'm using MPI to create C++ console app my problem is I have max_streak_length var  is hard code I need to pass it from command line. my command line mpiexec -n 3 main.exe 6 where 6 is my max_streak_length.can someone help me?
int main(int argc, char* argv[])
{
    //init size of max win streak
    int max_streak_length  = 6;

    //init MPI
    if(MPI_Init(&argc,&argv) == MPI_SUCCESS)
    {
        //init number of process and rank
        int numProc , rank;

        MPI_Comm_size(MPI_COMM_WORLD,&numProc);
        MPI_Comm_rank(MPI_COMM_WORLD,&rank);

        //call the process master
        if(rank == 0)
            procMaster(numProc,max_streak_length);
        //call the process slaves
        else
            procSlave(numProc,rank,max_streak_length);

        MPI_Finalize();
    }

    //playGame(15);

    return 0;

}

A: Simple answer is
int max_streak_length = atoi(argv[1]);

Note that with anything passed from the command line you really should add some error checking, you should check that the argument is actually there (i.e. that argc > 1) and that the value entered really is an integer, and that it's value is in the range you expect etc. etc.


text:
Q: How to wrap 'leaflet-geosearch' in 'react-leaflet' application? I want to warp 'leaflet-geosearch' to work in a react.js application that uses leaflet-geosearch. Is this possible?
Any examples of this would be extremely useful.

A: You'd have to write a custom react-leaflet component to do this.


text:
Q: How to Convert JSON Data into HTML I came across an exercise in freeCodeCamp to convert json data to html. Here, I was asked to copy paste a jquery which I didn't understand.

json.forEach(function(val) {
  var keys = Object.keys(val);
  html += "
";
  keys.forEach(function(key) {
    html += "" + key + ": " + val[key] + "
";
  });
  html += "

";
});

This is my json

[
   {
      "id":0,
      "imageLink":"https://s3.amazonaws.com/freecodecamp/funny-cat.jpg",
      "altText":"A white cat wearing a green helmet shaped melon on it's head. ",
      "codeNames":[
         "Juggernaut",
         "Mrs. Wallace",
         "Buttercup"
      ]
   },
   {
      "id":1,
      "imageLink":"https://s3.amazonaws.com/freecodecamp/grumpy-cat.jpg",
      "altText":"A white cat with blue eys, looking very grumpy. ",
      "codeNames":[
         "Oscar",
         "Scrooge",
         "Tyrion"
      ]
   },
   {
      "id":2,
      "imageLink":"https://s3.amazonaws.com/freecodecamp/mischievous-cat.jpg",
      "altText":"A ginger cat with one eye closed and mouth in a grin-like expression. Looking very mischievous. ",
      "codeNames":[
         "The Doctor",
         "Loki",
         "Joker"
      ]
   }
]

Can anyone help me to break down this code and tell what each line in the code does? For example I don't know what Object.keys does. Is Object an inbuilt instance?

A: The Object.keys() method returns an array of a given object's own enumerable properties.
var keys = Object.keys(val);

Here 'keys' is the array form of your json.
According to the JSON you provided the array has 3 objects.
You can also write
Object.keys(val).forEach(function(key){
  //something
});

instead of
var keys = Object.keys(val);

keys.forEach(function(key) {
     //something
  });

Inside the loop the key returns the the key of your object i.e.
id, imageLink etc
and
val[key] return corresponding values e.g.
0, "https://s3.amazonaws.com/freecodecamp/funny-cat.jpg" to be more specific.

A: From MDN

Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.

The purpose of the code is to generate html by using key and corresponding  value.

var json = [
   {
      "id":0,
      "imageLink":"https://s3.amazonaws.com/freecodecamp/funny-cat.jpg",
      "altText":"A white cat wearing a green helmet shaped melon on it's head. ",
      "codeNames":[
         "Juggernaut",
         "Mrs. Wallace",
         "Buttercup"
      ]
   },
   {
      "id":1,
      "imageLink":"https://s3.amazonaws.com/freecodecamp/grumpy-cat.jpg",
      "altText":"A white cat with blue eys, looking very grumpy. ",
      "codeNames":[
         "Oscar",
         "Scrooge",
         "Tyrion"
      ]
   },
   {
      "id":2,
      "imageLink":"https://s3.amazonaws.com/freecodecamp/mischievous-cat.jpg",
      "altText":"A ginger cat with one eye closed and mouth in a grin-like expression. Looking very mischievous. ",
      "codeNames":[
         "The Doctor",
         "Loki",
         "Joker"
      ]
   }
]
var html = "";
//iterating through all the item one by one.
json.forEach(function(val) {
  //getting all the keys in val (current array item)
  var keys = Object.keys(val);
  //assigning HTML string to the variable html
  html += "
";
  //iterating through all the keys presented in val (current array item)
  keys.forEach(function(key) {
    //appending more HTML string with key and value aginst that key;
    html += "" + key + ": " + val[key] + "
";
  });
  //final HTML sting is appending to close the DIV element.
  html += "

";
});

document.body.innerHTML = html;


text:
Q: How to group days in a week, like a calendar? I have table that has a column of schedule, I would like to pivot on the Day_Name column so that the dates are displayed as columns like Monday, Tuesday etc.
this is my query:
SELECT
     Month_Name,Day_Name, Year, Week_Number, Day_Number
    , isnull((Select (CONVERT(varchar(5), empschedfrom, 108) + '-' + convert(varchar(5), empschedto, 108)) from empdayscheds where empno = '0030' and empday_no = DayNumber_of_Month and empday_month = Month_Number and empday_year = Year), 'OFF') as emp_sched
    from dtRule where DATE between '05/28/2017' and '07/08/2017'

output:
   Month_Name | Day_Name | Year | Week_Number |Day_number| emp_sched
   May        |Sunday    | 2017 | 4           | 28       | 11:45-20:45
   May        | Tuesday  | 2017 | 5           | 29       | 14:15-23:15
   May        | Wednesday| 2017 | 5           | 30       | 13:45-22:45
   June       | Thursday | 2017 | 1           |  1       |10:00-19:00
   June       | Friday   | 2017 | 1           |  2       |10:00-19:00
   June       | Saturday | 2017 | 1           |  3       |10:00-19:00

I would like it to come out like this:
Week_Number | Month_Name | Year | Monday | Tuesday | Wednesday | Thursday  | Friday    | Saturday
1           | June       | 2017 |        |         |           |10:00-19:00|10:00-19:00|10:00-19:00

A:  drop table if exists dbo.Schedule;

create table dbo.Schedule (
Month_Name varchar(100)
, Day_Name varchar(100)
, Year int
, Week_Number int
, Day_Number int
, emp_sched varchar(100)
);

insert into dbo.Schedule (Month_Name, Day_Name, Year, Week_Number, Day_Number, emp_sched)
values ('May', 'Sunday', 2017, 4           ,  28       ,  '11:45-20:45')
 , ('May'        ,  'Tuesday'  ,  2017 ,  5           ,  29       ,  '14:15-23:15')
 , ('May'        ,  'Wednesday',  2017 ,  5           ,  30       ,  '13:45-22:45')
 , ('June'       ,  'Thursday' ,  2017 ,  1           ,   1       , '10:00-19:00')
 , ('June'       ,  'Friday'   ,  2017 ,  1           ,   2       , '10:00-19:00')
 , ('June'       ,  'Saturday' ,  2017 ,  1           ,   3       , '10:00-19:00');

select
s.Week_Number, s.Month_Name, s.Year
, max(case when s.Day_Name = 'Monday' then s.emp_sched else '' end) as Monday
, max(case when s.Day_Name = 'Tuesday' then s.emp_sched else '' end) as Tuesday
, max(case when s.Day_Name = 'Wednesday' then s.emp_sched else '' end) as Wednesday
, max(case when s.Day_Name = 'Thursday' then s.emp_sched else '' end) as Thursday
, max(case when s.Day_Name = 'Friday' then s.emp_sched else '' end) as Friday
, max(case when s.Day_Name = 'Saturday' then s.emp_sched else '' end) as Saturday
from dbo.Schedule s
group by s.Week_Number, s.Month_Name, s.Year;

A: If OBJECT_ID('Tempdb..#Temp') IS NOt NUll
Drop Table #Temp
 ;With cte( Month_Name , Day_Name , Year , Week_Number ,Day_number, emp_sched )
 AS
 (
 SELECT 'May' ,  'Sunday'  , 2017 , 4  , 28, '11:45-20:45' Union all
 SELECT 'May' , 'Tuesday'  , 2017 , 5  , 29, '14:15-23:15' Union all
 SELECT 'May' , 'Wednesday', 2017 , 5  , 30, '13:45-22:45' Union all
 SELECT 'June', 'Thursday' , 2017 , 1  ,  1,'10:00-19:00'  Union all
 SELECT 'June', 'Friday'   , 2017 , 1  ,  2,'10:00-19:00'  Union all
 SELECT 'June', 'Saturday' , 2017 , 1  ,  3,'10:00-19:00'
 )
 SELECT * INTo #Temp from cte

 Declare
         @Sql nvarchar(max),
         @dynamicCol nvarchar(max),@dynamicCol2 nvarchar(max)

Declare @DynamicColumn Table (ID Int IDentity, WeekName varchar(20))
INsert Into @DynamicColumn(WeekName)
SELECT 'Monday'   Union all
SELECT 'Tuesday'  Union all
SELECT 'Wednesday'Union all
SELECT 'Thursday' Union all
SELECT 'Friday'   Union all
SELECT 'Saturday' Union all
SELECT 'Sunday'

SELECT @dynamicCol=STUFF((SELECT ', ' +WeekName FROM  @DynamicColumn
FOR XML PATH('')),1,1,'')

--SELECT @dynamicCol

SELECT @dynamicCol2=STUFF((SELECT ', ' + 'MAX('+ WeekName +')' +' Over(Order by Week_Number Asc ) AS '
+ WeekName  FROM  @DynamicColumn
FOR XML PATH('')),1,1,'')

--SELECT @dynamicCol2

SET @Sql='
SELECT Top 1 Week_Number,Month_Name,[Year], '+ @dynamicCol2 +' From
(
SELECT Month_Name,Day_Name,[Year],Week_Number,Day_number,[emp_sched] From
#temp
)AS Src
PIVOT
(
MAX([emp_sched]) For [Day_Name ] IN ('+@dynamicCol+')
)
AS Pvt
'

PRINT @Sql

EXEC(@Sql)

OutPut
Week_Number Month_Name  Year    Monday  Tuesday Wednesday   Thursday        Friday          Saturday        Sunday
---------------------------------------------------------------------------------------------------------------------
1           June        2017    NULL    NULL    NULL        10:00-19:00     10:00-19:00     10:00-19:00     NULL


text:
Q: Symmetry transformation Let $x'=x+\lambda \cos(\omega t)$, where $\omega = \sqrt{k/m}$, be a symmetry transformation of the harmonic oscillator (with mass $m$ and spring constant $k$). My task is now to find a conserved quantity and show that it is actually conserved.
A Hint says to show that the Lagrange function of the harmonic oscillator is "almost" invariant under the transformation.
So the Lagragian for a harmonic oscillator is: $L_0=\frac{1}{2}m\dot{x}^2 - \frac{1}{2}m\omega^2x^2$.
If I know put in the transformation I get $$L'=\underbrace{\frac{1}{2}m\dot{x}^2-\frac{1}{2}m\omega^2x^2}_{=L_0} +\underbrace{\left(\frac{1}{2}k\lambda^2-\lambda (m\omega\dot{x}\sin(\omega t)+kx\cos(\omega t))\right)}_{=:\frac{\rm{d}}{\rm{d}t}K_{\lambda}(x,t)},$$ where the idea to realize that the part under the second \underbrace is the total time derivative of a function $K_{\lambda}(x,t)$ came from another hint.
Now I need to find $K_{\lambda}(x,t)$. To be honest that's where the real problem starts:
$$\begin{align}K_{\lambda}(x,t)&=\int\frac{{\rm{d}}}{{\rm{d}}t}K_{\lambda}(x,t){\rm{d}}t\\ &=\int \frac{1}{2}k\lambda^2-\lambda (m\omega\dot{x}\sin(\omega t)+kx\cos(\omega t)) {\rm{d}}t\\ &=\frac{1}{2}k\lambda^2t+C_1-\lambda m\omega\int\dot{x}\sin(\omega t){\rm{d}}t -\lambda k\int x\cos(\omega t){\rm{d}}t \end{align}$$
$\dot{x}$ and $x$ depend on $t$, so how am I supposed to evaluate the integrals?
Thanks for the help in advance,
Sito

A: Of course if you don't know $x$ you cannot evaluate those integrals. However it doesn't mean that you cannot find the function $K$, which depends on $x$, whatever $x$ is. My advice is make $k$ explicit in terms of $m$ and $\omega$, and then stare at the derivative of $K$ long enough to realise that it can be written as a derivative in a simple way.


text:
Q: Getting 'com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'ml.combust.mleap.spark'` error I am trying to run the sample MLeap code example provided here: http://mleap-docs.combust.ml/spark/
All of the code works on my Spark cluster. However, whenever I to execute the following code snippet (again from the above link):
for(bundle <- managed(BundleFile("jar:file:/tmp/mleap-examples/simple-json.zip"))) {
  pipeline.writeBundle.format(SerializationFormat.Json).save(bundle)
}

I am getting the following error:
com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'ml.combust.mleap.spark'
  at com.typesafe.config.impl.SimpleConfig.findKeyOrNull(SimpleConfig.java:152)
  at com.typesafe.config.impl.SimpleConfig.findKey(SimpleConfig.java:145)
  at com.typesafe.config.impl.SimpleConfig.findOrNull(SimpleConfig.java:172)
  at com.typesafe.config.impl.SimpleConfig.findOrNull(SimpleConfig.java:176)
  at com.typesafe.config.impl.SimpleConfig.findOrNull(SimpleConfig.java:176)
  at com.typesafe.config.impl.SimpleConfig.findOrNull(SimpleConfig.java:176)
  at com.typesafe.config.impl.SimpleConfig.find(SimpleConfig.java:184)
  at com.typesafe.config.impl.SimpleConfig.find(SimpleConfig.java:189)
  at com.typesafe.config.impl.SimpleConfig.getObject(SimpleConfig.java:258)
  at com.typesafe.config.impl.SimpleConfig.getConfig(SimpleConfig.java:264)
  at com.typesafe.config.impl.SimpleConfig.getConfig(SimpleConfig.java:37)
  at ml.combust.bundle.BundleRegistry$.apply(BundleRegistry.scala:35)
  at ml.combust.bundle.BundleRegistry$.apply(BundleRegistry.scala:28)
  at org.apache.spark.ml.bundle.SparkBundleContext$.apply(SparkBundleContext.scala:21)
  at org.apache.spark.ml.bundle.SparkBundleContext$.defaultContext$lzycompute(SparkBundleContext.scala:15)
  at org.apache.spark.ml.bundle.SparkBundleContext$.defaultContext(SparkBundleContext.scala:15)
  at $anonfun$2.apply(<console>:87)
  at $anonfun$2.apply(<console>:86)
  at resource.AbstractManagedResource$$anonfun$5.apply(AbstractManagedResource.scala:88)
  at scala.util.control.Exception$Catch$$anonfun$either$1.apply(Exception.scala:125)
  at scala.util.control.Exception$Catch$$anonfun$either$1.apply(Exception.scala:125)
  at scala.util.control.Exception$Catch.apply(Exception.scala:103)
  at scala.util.control.Exception$Catch.either(Exception.scala:125)
  at resource.AbstractManagedResource.acquireFor(AbstractManagedResource.scala:88)
  at resource.ManagedResourceOperations$class.apply(ManagedResourceOperations.scala:26)
  at resource.AbstractManagedResource.apply(AbstractManagedResource.scala:50)
  at resource.ManagedResourceOperations$class.acquireAndGet(ManagedResourceOperations.scala:25)
  at resource.AbstractManagedResource.acquireAndGet(AbstractManagedResource.scala:50)
  at resource.ManagedResourceOperations$class.foreach(ManagedResourceOperations.scala:53)
  at resource.AbstractManagedResource.foreach(AbstractManagedResource.scala:50)
  ... 70 elided

I have also followed this similar problem link https://github.com/combust/mleap/issues/252 by adding the following in my maven pom.xml:
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
    <resource>reference.conf</resource>
</transformer>

Unfortunately, I am still getting the same error.


text:
Q: how to share a folder between two projects in Visual studio 2010 If I have a project called 'testing' in project A.
How can I share that folder 'testing' for project B in visual studio 2010?
The reason I would like to achieve about this is because when I change something in the folder testing of project A, I dont want to change the same things in project B.
Thanks in advance.

A: Maybe too late for the person who asked the question, but this is for people with similar problems.  You can share folder contents with an extention  'Project Linker':
This builds upon the concept of linked files where you refer to the same file from two projects. This extention handles the management of that for an entire project. If you add a file to the project, it will be added too to the other project as a linked file. Same for deletes...
Attention: you need to have both projects in the same solution for this to work of coarse...
Extention VS2015
I used it in VS2010 and it's also availible for later versions.

A: You can't share folders in Visual Studio - they are logical constructs that are part of a solution or project.
The closest you can get is to add folders to the projects you need to share on and add all the files that you want to share as links. You will still need to manually synchronize all adds/deletes of files, but updates will come across all projects.
To make things easier, you may want to write a Visual Studio macro that synchronizes these folders for you (you can bind these to keyboard shortcuts and/or menu items).

A: If you put your solution (*.sln) files in the same directory they can share files in sub directories.


text:
Q: Running multiple tasks parrallel and overwriting each line in for I'm pretty new to programming, but I have a question:
How could I show different task output (I should use the tasks) in different lines, in the console?
Also, I want to overwrite the lines each time , so the output should show:
i // overwriting this line everytime.
j // overwriting this line everytime.
I tried using SetCursorPosition, but it makes a collision between the task ouput somewhy.
A mini code sample (hope this makes it clearer):
Task a = Task.Run(() =>
{
    int i;
    for (i = 0; i <= 1000000; i++)
    {
        Console.SetCursorPosition(Console.CursorLeft, 0); // ?
        Console.WriteLine("{0}", i);
    }
});

Task b = Task.Run(() =>
{
    int j;
    for (j = 0; j <= 1000000; j++)
    {
        Console.SetCursorPosition(Console.CursorLeft, 3); // ?
        Console.WriteLine("{0}",j);
    }
});

Console.ReadLine();

Thank You in advance :)

A: You need to synchronize access to Console for different tasks (I am not fixing position part if there is any problem, but an obvious synchronization problem):
var consoleLock = new object();

Task.Run(() =>
{
    for (int i = 0; i <= 1000000; i++)
    {
        Thread.Sleep(1); // to simulate some work
        lock(consoleLock)
        {
            Console.SetCursorPosition(Console.CursorLeft, 0);
            Console.WriteLine(i);
        }
    }
});

Task.Run(() =>
{
    for (int j = 0; j <= 1000000; j++)
    {
        Thread.Sleep(1); // to simulate some work
        lock(consoleLock)
        {
            Console.SetCursorPosition(Console.CursorLeft, 3);
            Console.WriteLine(j);
        }
    }
});

Console.ReadLine();

A: This is a simplified demo of what you are trying. Modify it as per your needs.
The basic idea is, you call a ThreadSafe method to write to console from all threads. And, every time you update the console, you re-write the two lines (notice the use of SetCursorPosition() method).
static object locker = new object();
static int iCommon = 0;
static int jCommon = 0;

static void WriteText()
{
    lock(locker)
    {
        var text = string.Format("i = {0}{1}j = {2}",
                                    iCommon, Environment.NewLine, jCommon);
        Console.SetCursorPosition(0,
                                  Console.CursorTop == 0 ? 0 : Console.CursorTop - 1);
        Console.Write(text);
    }
}

static void Main(string[] args)
{
    Task a = Task.Run(() =>
    {
        for (int i = 0; i <= 15; i++)
        {
            Thread.Sleep(700); //just to demonstrate the display change
            iCommon = i;
            WriteText();
        }
    });

    Task b = Task.Run(() =>
    {
        for (int j = 0; j <= 10; j++)
        {
            Thread.Sleep(1150); //just to demonstrate the display change
            jCommon = j;
            WriteText();
        }
    });
    Console.ReadLine();
}


text:
Q: FuelSDK: Updating Subscriber doesn't work I have to do following things when I create a subscriber

*

*Create a subscriber with status - 'Unsubscribed' in the Business unit

*Update an attribute 'ReferenceId' of the subscriber

*Update the lists of the subscriber

*Send a verification email through TriggerSend

All the above actions have to be performed separately but will be performed in the same sequence.
Now here is the problem that I am facing:
I am able to create the subscriber successfully but then:

*

*If I update the attribute first then trigger doesn't work.

*If I update the lists of the subscriber first then attribute updation doesn't happen.

Note In above problems I am getting success response every time I am sending the API request.
I am using FuelSDK Ruby agent and have been referring the documentation given here


text:
Q: When switching from Apache to Fast CGI, pages of the site are being downloaded instead of displayed in browser I run a site and blog on the same server, blog is located in the /blog/ directory in the root folder and it is a simple wordpress blog.
The problem, I have had to run an update on the blog which is constantly failing. After talking to my hosting provider, I have discovered that I am apparently running php as Apache and not as fast cgi, which is a main reason why I was not able to run all updates on my blog. We have changed it to fast cgi in plesk panel and blog started to work and run all necessary updates as it was supposed to do, but the main site began malfunctioning, basically instead of displaying page in the browser, all pages were firing up a download dialogue.
I have had to change everything back to where I have started, but need to get to the bottom of the problem.
All your suggestions are going to be helpful.
Thanks in advance

A: Sounds like you need to adjust your MIME types in IIS.


text:
Q: sharepoint 2010 context menu event handler i want to hide sharepoint 2010 list/library context menu based on users.
i am using below javascript
  $(document).ready(function(){
        $('.ms-MenuUIPopupBody').live('blur', function() {
           var elm = $("div.ms-MenuUIULItem a:contains('View in Browser')");
           elm.remove();
           $("div.ms-MenuUIULItem a:contains('Edit in Browser')").remove();
         });
  });

It is hiding menu only on focus or blur or mouse-over on the context menu.
the context menu is generating dynamically by core.js file
i need to add the script when the context menu is created.
so i need to find the event for context menu

how to find the click event and add my custom code.
with "Andrew" i found good solution and to handle the context menu event
var _MenuHtc_show;

function OverrideMenuHtc_show()
{
   _MenuHtc_show = window.MenuHtc_show;
   window.MenuHtc_show= function (m,r,fr,ft,yoff) {
      _MenuHtc_show(m,r,fr,ft,yoff);
      var elm = $(".ms-MenuUIULItem[text='Alert Me']");
      elm.remove();
   };
}

ExecuteOrDelayUntilScriptLoaded(OverrideMenuHtc_show, "core.js")

its working fine but its hiding context menu for all webparts.
i need to find the context menu selected webpart id to check is it right webpart to hide context menu.
i am able to find the webpart id after once i select webpart with this code.
 var listId = SP.ListOperation.Selection.getSelectedList();

or
var ctxCur = GetCurrentCtx();
var SPGridViewGuid = ctxCur.listName;

but if i click on "v" symbol with out selecting the webparts its return null.
is there any way to find the context menu selected webpart id.
so its solves my problem.

A: What about that?
 $('.s4-ctx').css('display','none');

It will hide buttons that show context menu.

If you need to hide context menu only from web part with specified id you need to use:
$("div[webpartid='85c13a33-57a3-456b-a19b-c68c97756184'] .s4-ctx").css('display','none');

If you want to remove menu item, for ex. "Alert Me" add this script that overrides standard core.js function "MenuHtc_show" and hides menu item from context menu in specified webpart:
var _MenuHtc_show;

function OverrideMenuHtc_show()
{
   _MenuHtc_show = window.MenuHtc_show;
   window.MenuHtc_show= function (m,r,fr,ft,yoff) {
      _MenuHtc_show(m,r,fr,ft,yoff);
      var items = $("div[webpartid='85c13a33-57a3-456b-a19b-c68c97756184'] .ms-MenuUIULItem[text='Alert Me']");
      $(items).css('display','none');
   };
}

ExecuteOrDelayUntilScriptLoaded(OverrideMenuHtc_show, "core.js")

A: Any reason why you are not using a HideCustomAction?
Here is the MSDN for that.
And here is a resource for finding the correct groups

A: finally this solve my problem
i enhanced "Andrew" script to make full functional.
ExecuteOrDelayUntilScriptLoaded(OverrideMenuHtc_show, "core.js");

var _MenuHtc_show;

function OverrideMenuHtc_show() {

    _MenuHtc_show = window.MenuHtc_show;
    window.MenuHtc_show = function (m, r, fr, ft, yoff) {
        _MenuHtc_show(m, r, fr, ft, yoff);

        var ctxCur = listcontext;
    //list or library GUID
        var listid = ctxCur.listName;

    if(listid =='your list\library GUID')
    {

                var elm = $(".ms-MenuUIULItem[text='Alert Me']");
                elm.remove();

    }

    };
}

A: I wanted to implement the same on SharePoint 2013.
The CSS solution only works for a particular page. If one creates a new view this will not work.
@kavalirakesh and @Andrew answer worked partially for me.
the var ctxCur = listcontext; was throwing exception on listcontext is undefined.
Instead I used GetCurrentCtx() to get ClientContext.
But I was getting the following javascript error when I was clicking on the Setting cog on the top right side of the page.
"An error has occurred with the data fetch. Please refresh the page and retry."
My javascript code added through a Delegate Control on the master page head.
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Control Id="AdditionalPageHead"
           Sequence="90"
           ControlSrc="~/_CONTROLTEMPLATES/15/MyCustomFolder/ECBDelegateControl.ascx" />
</Elements>

The user control "ECBDelegateControl.ascx" had the scrip below
<script type="text/javascript"  src="../../../_layouts/15/MyScripts/Script/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
        ExecuteOrDelayUntilScriptLoaded(OverrideMenuHtc_show, "core.js");
    });

    function OverrideMenuHtc_show() {
        var ctx = GetCurrentCtx();
        var listName = ctx.ListTitle;

        if (listName == 'My First List' ||
            listName == 'My Second List') {
            var _MenuHtc_show;
            _MenuHtc_show = window.MenuHtc_show;
            window.MenuHtc_show = function (m, r, fr, ft, yoff) {
                _MenuHtc_show(m, r, fr, ft, yoff);
                var elm = $("li.ms-core-menu-item[text='Delete Item']");
                elm.remove();
            }
        };
    }
</script>

The ClientContext was null and I had to load the sp.js before I can call GetCurrentCtx().
The javascript error I used to get is also gone.
This is much better solution than changing core.js file.


text:
Q: Unity Assembly references missing when installing Newtonsoft.Json I have the problem, where Unity shows me an error "The type or namespace name 'Newtonsoft' could not be found" but my compiler (Visual Studio) has all the assambly references it need and doesent show an error. I can hardly tell how you should be able to reproduce the error. Maybe it occures when you try to install Newtonsoft.Json to a Unity project.
There might be a hint here. When I installed Newtonsoft.Json to my Unity project. Visual Studio lost every single assambly refrence in "Assembly-CSharp.Player". I had to restart my PC and since then the Error appears.
Would be nice if someone has an idea how to fix this. Thank you very much.


text:
Q: Flutter `FirebaseDynamicLinks.onLink` calls `onSuccess` twice when the app is in background in pubspec.yaml:
firebase_dynamic_links: ^0.5.0+11

The code:
    FirebaseDynamicLinks.instance.onLink(
        onSuccess: (PendingDynamicLinkData dynamicLink) async {
          final Uri deepLink = dynamicLink?.link;
          if (deepLink != null) {
            onLinkReceived(deepLink);
          }
        },
        onError: onError);
  }

*

*The app is launched and in background.

*User clicks the link.

Actual result: onSuccess is being called twice for the link.
Expected result: onSuccess is being called and being called once per link.
What could be wrong?

A: So, seems like it is a known issue.
While we are waiting for the fix on the stable channel I am using as a workaround some sort of double call filter which looks somewhat like this:
class DoubleCallFilter<T> {
  T _lastValue;
  int _lastValueTime = 0;
  final int timeoutMs;
  final Future Function(T) action;

  DoubleCallFilter({@required this.action, this.timeoutMs = 500});

  Future<dynamic> call(T value) async {
    final currentTime = DateTime.now().millisecondsSinceEpoch;
    if (_lastValue == value) {
      if (currentTime - _lastValueTime <= timeoutMs) {
        return;
      }
    }
    _lastValue = value;
    _lastValueTime = currentTime;
    if (action != null) await action(_lastValue);
  }
}

And the usage:
    FirebaseDynamicLinks.instance.onLink(
      onSuccess: DoubleCallFilter<PendingDynamicLinkData>(
        action: (dynamicLink) async {
          final Uri deepLink = dynamicLink?.link;
          if (deepLink != null) {
            await onLinkReceived(deepLink);
          }
        },
      ),
      onError: onError,
    );

One of the downsides this solution is that the latest emitted value is being kept in the memory as long as entire DoubleCallFilter is not destroyed (gc'ed).


text:
Q: MYSQL: Join list of values into a table I have list of predefined values Cash, Bank, Card, Cheque called payment modes (no db table for them).
Each payments will have it's mode.
+-----------+
+ Payments  +
+-----------+
+ id        +
+ amount    +
+ date      +
+ mode      +
+-----------+

The below query will not show mode that are not in the payments table. If for example no payment is made through cheque, then it will not be in the result.
select p.mode, SUM(p.amount) 'total'
from payments p

I also found out about Table Value Constructor but I'm not sure if its supported in MySql as I'm having syntax error.
select p.mode, SUM(p.amount)
from (
    VALUES
      ('Cash'),
      ('Card'),
      ('Cheque'),
      ('Bank')
 ) as m(name)
 left join payments p on m.name = p.mode
group by p.mode

Is there a way to have a query that gets all the mode regardless if they are not present in the payments table? I need a result like:
++++++++++++++++++++
+ mode     | total +
++++++++++++++++++++
+ cash     | 100   +
+ cheque   | 0     +
+ bank     | 0     +
+ card     | 300   +
++++++++++++++++++++

A: In MySQL, you can construct the table using union all:
select m.mode, SUM(p.amount)
from (select 'Cash' as mode union all
      select 'Card' union all
      select 'Cheque' union all
      select 'Bank'
     ) m left join
     payments p
     on m.mode = p.mode
group by m.mode;

Notes:

*

*I changed name to mode so the column with the same information has the same name.

*The group by key needs to be from the first name, not the second (that is m.mode instead of p.mode).

*If you want 0 instead of NULL, then use coalesce(sum(p.amount), 0).

*You might want to consider a reference table that contains the mode values.

A: select
  m.mode,
  SUM(p.amount)
FROM
  (
    SELECT
      m.Cash as mode
    FROM
      (
        VALUES
          ('cash'),
          ('card'),
          ('cheque'),
          ('bank')
      ) as m
  ) as m
  left join payments p on m.mode = p.mode
group by
  m.mode

You need two aliases and you must use the first value of your array (Cash) in nested select as selected column.

A: It's worth checking your version of MySQL if the VALUES approach isn't working. It was only introduced from MySQL 8.0.19 , so anyone on an earlier issue will need to use the UNION ALL approach.


text:
Q: How to get an update thread and render thread working smoothly together (on Linux)? I'm trying to get a simple multi-threaded OpenGL application working. I have an update thread and a render thread. The way I've written them, they should be essentially taking turns running because they are mutex locked. Instead, the update thread will run tens of times, and then the render thread will runs tens of times. Here is the relevant code:
void glRender() {
    printf("glRender()\n");
    glXMakeCurrent(display, window, glXContext);
    glSetup();
    glClear(GL_COLOR_BUFFER_BIT);
    glBegin(GL_TRIANGLES);
        glVertex2f(cosf(fDrawAngle), sinf(fDrawAngle));
        glVertex2f(cosf(fDrawAngle+2.1f), sinf(fDrawAngle+2.1f));
        glVertex2f(cosf(fDrawAngle+4.2f), sinf(fDrawAngle+4.2f));
    glEnd();
    glXSwapBuffers(display, window);
    glXMakeCurrent(display, 0, 0);
}

void * glThread(void * params) {
    while (bRunning) {
        pthread_mutex_lock(&mutex);
        glRender();
        pthread_mutex_unlock(&mutex);
    }
    pthread_exit(0);
}

// Multi threaded version
void gameUpdateMT() {
    while (bRunning) {
        pthread_mutex_lock(&mutex);
        printf("gameUpdate()\n");
        windowUpdate();
        fDrawAngle += 0.01f;
        pthread_mutex_unlock(&mutex);
    }
}

// Single threaded version - Runs fine.
void gameUpdateST() {
    while (bRunning) {
        printf("gameUpdate()\n");
        windowUpdate();
        fDrawAngle += 0.01f;
        glRender();
    }
}

gameUpdateMT() and glThread() are running in parallel. What would be causing one thread to loop so many times before the other one gets a chance to run?

A: A thread doesn't necessarily end its timeslice when it calls pthread_mutex_unlock().   This being the case, it can easily loop around again and re-acquire the mutex (the waiters on a mutex aren't queued).
It's possible to use a condition variable to have the threads take turns - but that's just needlessly overcomplicating things.  If you want glRender() and windowUpdate() called alternately in sequence, then just have a single thread call them alternately, just as in your "singlethreaded" version.
There's no point having multiple threads if they never run concurrently.


text:
Q: docker build starting slow I'm testing docker builds on two different systems. Ubuntu and Arch linux. I'm experiencing significant slow docker build starting  speeds (same Dockerfile) on Arch linux (better/newer machine).
In both systems
Docker version 20.10.12
Storage Driver: overlay2
Further investigations shows that there is no delay between creation of layers. Initial time to start the build is the culprit

A: It was the additional DNS lookup's causing the start delay.
Removing the extra mirrors from  .docker/config.json  did the trick
cat .docker/config.json
{
  "credHelpers": {
    "asia.gcr.io": "gcloud"
  }
}


text:
Q: When change marker position on click, info window not remove When I change the marker position on click the map info window of last position did not remove. My code is following. For example, when I click on google map marker position is changed w-r-t to that lat and long. And info window shows that lat, long. And after that when I change again the position of marker and open the info window it shows the lat, long. And when I click on close window it shows last info window behind it. And then I need to close that window. How can I fix it?
var marker2 = "";
function customMap(ulat,ulong,blat,blong)
{
      //console.log(params);
      var map_div = "map-canvas";
      // var map_div = params.mapDiv;

      var myLatlng = new google.maps.LatLng(ulat, ulong);
      var myLatlng1 = new google.maps.LatLng(blat,blong);
      var loc_latlng = new google.maps.LatLng(23.8212783,90.4278342);
      var mapOptions = {
        zoom: 17,
        center: myLatlng1
      }
      var map = new google.maps.Map(document.getElementById( map_div ), mapOptions);

      var content_data = "User";
      var content_data3 = "Location";
      var content_data2 = "
Location
Lat: "+blat+"
Long: "+blong+"
Click on Map to change location
Delete Location
";
     // show full map button
     map.controls[google.maps.ControlPosition.TOP_RIGHT].push(
     FullScreenControl(map));

      var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        icon: this_domain_cp+"/mvc/images/user_map_icon.png",
        //title: 'User'
      });
      attachMessage(marker, content_data);

      marker2 = new google.maps.Marker({
        position: myLatlng1,
        map: map,
        //title: 'building'
      });
      attachMessage(marker2, content_data2);

      marker3 = new google.maps.Marker({
        position: loc_latlng,
        map: map,
        icon: this_domain_cp+"/mvc/images/loc_icon.png",
        title: 'Location'
      });
      attachMessage(marker3, content_data3);

    //update lat long of building (red marker)
    google.maps.event.addListener(map, "click", function (event) {

        var blat = event.latLng.lat();
        var blong = event.latLng.lng();

        var myLatlng1 = new google.maps.LatLng(blat, blong);
        var newloc = marker2.setPosition(myLatlng1);

        var content_data2 = "
Location
Lat: "+blat+"
Long: "+blong+"
Click on Map to change location
Delete Location
";
        attachMessage(marker2, content_data2);
        infowindow.close();

        $('#building_latitude').val(blat);
        $('#building_longitude').val(blong);

    });

}

    function attachMessage(marker, content_data) {
        //    var message = 'This is my';
        var infowindow = new google.maps.InfoWindow({
            content: content_data
        });

        google.maps.event.addListener(marker, 'mouseover', function() {
            infowindow.open(marker.get('map'), marker);
        });

    }

    function DeleteMarker(id) {
        marker2.setMap(null);
        $('#building_latitude').val(0);
        $('#building_latitude').attr("disabled","disabled");
        $('#building_longitude').attr("disabled","disabled");
        $('#building_longitude').val(0);
    }

A: One option would be to keep a reference to the infowindow and close it if you run your attachMessage function again on the same infowindow:
function attachMessage(marker, content_data) {
    //    var message = 'This is my';
    if (marker.infowindow) {
       marker.infowwindow.close();
    }
    var infowindow = new google.maps.InfoWindow({
        content: content_data
    });
    marker.infowindow = infowindow;
    google.maps.event.addListener(marker, 'mouseover', function() {
        infowindow.open(marker.get('map'), marker);
    });

}

proof of concept fiddle
If you only ever want one infowindow open, create one in the global context and reuse that for any marker that is clicked.


text:
Q: SwiftUI - AppStorage doesn't work with GeometryReader Here is a simple example. You can create new SwiftUI iOS project and copy it to ContentView file.
import SwiftUI

struct Settings {
    static let onOff = "onOff"
}

struct ContentView: View {
    @AppStorage(wrappedValue: false, Settings.onOff) var onOff

    var body: some View {
        NavigationView {
            GeometryReader { reader in // < Comment out this line
                List {
                    Section (header:
                                VStack {
                                    HStack {
                                        Spacer()
                                        VStack {
                                            Text("THIS SHOULD BE FULL-WIDTH")
                                            Text("It is thanks to GeometryReader")
                                        }
                                        Spacer()
                                    }
                                    .padding()
                                    .background(Color.yellow)

                                    HStack {
                                        Text("This should update from AppStorage: ")
                                        Spacer()
                                        Text(onOff == true ? "ON" : "OFF")
                                    }
                                    .padding()
                                }
                                .frame(width: reader.size.width) // < Comment out this line
                                .textCase(nil)
                                .font(.body)
                    ) {
                        Toggle(isOn: $onOff) {
                            Text("ON / OFF")
                        }
                    }

                }
                .listStyle(GroupedListStyle())
            } // < Comment out this line

        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I have 3 elements:

*

*Text with yellow background - I need it full-width and I use GeometryReader to do it.

*Text. Last word should switch ON/OFF based on toggle value. This is just for testing purposes to check if AppStorage works correctly.

*Toggle - switches onOff variable and saves it to AppStorage (UserDefaults).

AppStorage works perfectly only without GeometryReader. Please comment out 3 tagged lines to check it out.
Is it a bug? Or something is wrong with my AppStorage code? Or maybe GeometryReader part is wrong? If I could set yellow part full-width, I could drop GeometryReader completely.

A: Yes, this is definitely a bug. Looks like AppStorage doesn't behave completely same as State for some reason, and change doesn't trigger updates inside GeometryReader. Example can be reduced to this:
struct ContentView: View {
    @AppStorage("onOff") var onOff = false

    var body: some View {
        VStack {
            Text("Text updating: " + (onOff == true ? "ON" : "OFF"))
            GeometryReader { reader in
                Toggle(isOn: $onOff) {
                    Text("Text not updating: " + (onOff == true ? "ON" : "OFF"))
                }
            }
        }
    }
}

This is not even fixed in the latest iOS 15 beta. You can try to hack with some duplicate state variable, but instead I suggest you switching to custom AppStorage, it works fine in this circumstances.

A: One solution that works in my testing is to factor out the GeometryReader's content, including the @AppStorage:
struct ContentView: View {
    var body: some View {
        NavigationView {
            GeometryReader { proxy in
                _ContentView(width: proxy.size.width)
            }
        }
    }
}

struct _ContentView: View {
    var width: CGFloat
    @AppStorage(wrappedValue: false, Settings.onOff) var onOff

    var body: some View {
        List {
            Section(header: header) {
                Toggle(isOn: $onOff) {
                    Text("ON / OFF")
                }
            }

        }
        .listStyle(GroupedListStyle())
    }

    var header: some View {
        VStack {
            VStack {
                Text("THIS SHOULD BE FULL-WIDTH")
                Text("It is thanks to GeometryReader")
            }
            .padding()
            .frame(width: width)
            .background(Color.yellow)

            HStack {
                Text("This should update from AppStorage: ")
                Spacer()
                Text(onOff == true ? "ON" : "OFF")
            }
            .padding()
        }
        .textCase(nil)
        .font(.body)
    }
}


text:
Q: Optional React Router Param Flagging GET request Error? EDIT: Posted answer to how I went around this instead of using react-router optional params.
For some reason, I'm having a GET error when I go to the optional react-router route/url with the optional param attached to the URL. I'm trying to track where a user came from by including the optional param SRC to the url. I've tried everything from /ref=testing, /src=testing, /testing as the :referrer? and they'll save probably in localStorage, but still raise the console GET request.
Here is what my App.js looks like:
<Route exact path="/profile/user/:user/:referrer?" component={ ProfileById } />

:user is the user ID in the mongoose structure. :referrer? is the src=(whatever it is)
Here is my axios request for the route:
export const getProfileByUserId = (user) => dispatch => {
dispatch(setProfileLoading());
axios.get(`/profile/user/${user}`)
    .then(res =>
        dispatch({
            type: GET_PROFILE,
            payload: res.data
        })
    )
    .catch(err =>
        dispatch({
            type: GET_PROFILE,
            payload: null
        })
    );
}

Here is what's inside my componentDidMount() where I run the axios GET request, and then also check for the optional param and store it in localStorage.
componentDidMount() {
    if (this.props.match.params.user) {
        this.props.getProfileByUserId(this.props.match.params.user);
    }

    if (this.props.match.params.referrer) {
        let referrerString = this.props.match.params.referrer.split('=');
        localStorage.setItem('referrer', referrerString[1])
    }
}

When I load the route, let's say its: /profile/user/20385h1058h385/ref=testing  the GET error comes up as: 404 Not found, and then says the error is /ref=testing   Well if it's an optional param and I'm not actually requesting a GET on this optional param, why is it coming up?
Any help is appreciated, thanks!

A: Please append, only testing instead of  ref=testing in the URL. In that case, your URL will be /profile/user/20385h1058h385/testing
We put : for the required parameter and :parameter_name? for the optional parameter.
For example :
<Route path="/login/:p1/:p2?" component={Login} />

Here p1 is the required parameter and p2 is an optional parameter.
And we get these in the componentDidMount method as you are doing.
this.props.match.params.p1

A: I couldn't get it working with a react optional param route, so I just went ahead and did a new URLSearchParams(), made it into a string and then split that string to identify the actual search query. Works on a slash path like: /?src=testing and when it's appended to an existing path.
Here's what I came up with:
if (this.props.location.search) {
        // Check to see if the search address has a location and search query param, if so save in localStorage for referrer source
        //console.log(this.props.location.search);
        let srcParams = new URLSearchParams(this.props.location.search);
        let srcString = srcParams.toString();
        let referrerString = srcString.split('=');
        localStorage.setItem('referrer', referrerString[1]);
    }


text:
Q: Are transitions between stationary orbits part of the Bohr model? The first assumption of the Bohr atomic model states that the electrons can only orbit stably, without radiating, in certain orbits (called by Bohr the "stationary orbits") at a certain discrete set of distances from the nucleus.
Electrons can only gain and lose energy by jumping from one allowed orbit to another. source
Someone pointed out a conceptual problem with this assumption: "If an electron is in a stationary state, it would not collapse." By calling it a "stationary orbit", does Bohr mean the electron orbital will never increase or decrease in energy or radius?
In other words, does the Bohr model say that the electrons will forever stay in the same stationary orbits? Is this the reason why the Bohr model was determined to be incorrect?
Or, does the Bohr model say that an electron can jump from one orbit to another, and thereby gain and lose energy? If so, under what conditions?
This question differs from this related question because it asks about the Bohr model, not about the planetary model.

A: Bohr's atomic model is an approach to describe the hydrogen atom effectively. The model holds neither in classical nor in quantum physics completely. It is an effective model that describes the emission spectrum lines as transitions between the electron shells. It describes the electron shells of a hydrogen atom reasonably well, but fails completely when going to heavier (higher Z) atoms.
I found this formulation of the first two postulates of Bohr:

*

*Electrons in an atom exist in STATIONARY STATES.

*

*Bohr stated that electrons orbit the nucleus WITHOUT emitting EM radiation.

*Any permanent change in their motion must be accompanied by a complete transition from one stationary state to another.

*Note that Bohr could NOT explain this.

*Transmission between stationary states produces/absorbs EM Radiation.

*

*When an electron moves between stationary states, it is accompanied by the emission or absorption of a photon.

*This photon's energy is given by ΔE=hf

*Thus, EM radiation is produced by the movement of electrons between energy states which account for Planck's "atomic oscillators."

Source: http://nsb.wikidot.com/pl-9-8-1-3 -160814 12:04
The transition between orbits is an integral part of Bohr's model. But I would not try to explain the physics of the transition mechanism in this model. It is only an effective description of the hydrogen atom - not a physically correct one.


text:
Q: sparklyr formula creation error I am testing this tutorial
Predicting food preferences with sparklyr (machine learning)
but in the Modeling section I am getting the following error
Input code:
library(lazyeval)
for (response in countries) {

  features <- colnames(partitions$training)[-grep(response, colnames(partitions$training))]
  features <- features[grep("_trans|_idx", features)]

  fit <- partitions$training %>%
    filter_(interp(~ var > 0, var = as.name(response))) %>%
    ml_random_forest(intercept = FALSE, response = response, features = features, type = "classification")

...
}

Output:
Error in ml_formula_transformation(): only one of 'formula' or 'response'-'features' should be specified
Traceback:

1. partitions$training %>% filter_(interp(~var > 0, var = as.name(response))) %>%
 .     ml_random_forest(intercept = FALSE, response = response,
 .         features = features, type = "classification")
2. withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
3. eval(quote(`_fseq`(`_lhs`)), env, env)
4. eval(quote(`_fseq`(`_lhs`)), env, env)
5. `_fseq`(`_lhs`)
6. freduce(value, `_function_list`)
7. withVisible(function_list[[k]](value))
8. function_list[[k]](value)
9. ml_random_forest(., intercept = FALSE, response = response, features = features, type = "classification")

I tried with formula creation, however response is a variable and it should be lazy evaluated, because it feature is the content of response variable (example algeria country)
IN
ml_formula <- formula(response ~ features)

  fit <- partitions$training %>%
    filter_(interp(~ var > 0, var = as.name(response))) %>%
  ml_random_forest(ml_formula, type = "classification")

out
Error in ml_random_forest(., ml_formula, type = "classification"): response is not a column in the input dataset

thanks in advance


text:
Q: Java - how to encode URL path for non Latin characters Currently there is final URL url = new URL(urlString); but I run into server not supporting non-ASCII in path.
Using Java (Android) I need to encode URL from
http://acmeserver.com/download/agc/fcms/儿子去哪儿/儿子去哪儿.png

to
http://acmeserver.com/download/agc/fcms/%E5%84%BF%E5%AD%90%E5%8E%BB%E5%93%AA%E5%84%BF/%E5%84%BF%E5%AD%90%E5%8E%BB%E5%93%AA%E5%84%BF.png

just like browsers do.
I checked URLEncoder.encode(s, "UTF-8"); but it also encodes / slashes
http%3A%2F%2acmeserver.com%2Fdownload%2Fagc%2Ffcms%2F%E5%84%BF%E5%AD%90%E5%8E%BB%E5%93%AA%E5%84%BF%2F%E5%84%BF%E5%AD%90%E5%8E%BB%E5%93%AA%E5%84%BF.png

Is there way to do it simply without parsing string that the method gets?
from http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars

B.2.1 Non-ASCII characters in URI attribute values Although URIs do
  not contain non-ASCII values (see [URI], section 2.1) authors
  sometimes specify them in attribute values expecting URIs (i.e.,
  defined with %URI; in the DTD). For instance, the following href value
  is illegal:
...
We recommend that user agents adopt the following convention for
  handling non-ASCII characters in such cases:

*

*Represent each character in UTF-8 (see [RFC2279]) as one or more
  bytes.

*Escape these bytes with the URI escaping mechanism (i.e., by
  converting each byte to %HH, where HH is the hexadecimal notation of
  the byte value).

A: You should just encode the special characters and the parse them together. If you tried to encode the entire URI then you'd run into problems.
Stick with:
String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;

Check out this great guide on URL encoding.
That being said, a little bit of searching suggests that there may be other ways to do what you want:
Give this a try:
String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();

(You will need to have those spaces encoded so you can use it for a request.)

This takes advantage of a couple features available to you in Android
  classes.  First, the URL class can break a url into its proper
  components so there is no need for you to do any string search/replace
  work.  Secondly, this approach takes advantage of the URI class
  feature of properly escaping components when you construct a URI via
  components rather than from a single string.
The beauty of this approach is that you can take any valid url string
  and have it work without needing any special knowledge of it yourself.

A: final URL url = new URL( new URI(urlString).toASCIIString() );

worked for me.

A: I did it as below, which is cumbersome
        //was: final URL url = new URL(urlString);
        String asciiString;
        try {
            asciiString = new URL(urlString).toURI().toASCIIString();
        } catch (URISyntaxException e1) {
            Log.e(TAG, "Error new URL(urlString).toURI().toASCIIString() " + urlString + " : " + e1);
            return null;
        }
        Log.v(TAG, urlString+" -> "+ asciiString );
        final URL url = new URL(asciiString);

url is later used in
        connection = (HttpURLConnection) url.openConnection();


text:
Q: 2 Ajax forms in a page but only one is working I have two forms in a page. But only one works.
This is the website link - http://baysquare-dubai.com/businessbay/real-estate.html
I have two scripts for each form.
Script 1:
 <script>
 $(document).ready(function() {
    $("#submit-form-button").click(function() { submitForm(); });
});
function submitForm() {

        $.ajax({
      type: "POST",
      url: "http://famproperties.com/real_estate/property/contact/lead/",
      data: {
      NAME:   $("#NAME").val(),
      EMAIL:  $("#EMAIL").val(),
      MOBILE: $("#MOBILE").val(),
      NOTE:   $("#NOTE").val(),
      SOURCE: 'BAY.SQUARE',
      CITY: 'ADD CITY',
      },

      success: function() {

         alert ("we will contact you soon ..");

      },
      dataType: 'html'
   });
$("#NAME").val('');
 $("#EMAIL").val('');
 $("#MOBILE").val('');
 $("#NOTE").val('');

};
</script>

In the 2nd script, it is the same but with different IDs.
Need help!

A: You can't make two different functions with the same name. For your second form add the function "submitForm2" instead of "submitForm". Call the right functions like this:

$(document).ready(function() {
    $("#submit-form-button").click(function() { submitForm(); });
});

$(document).ready(function() {
    $("#submit-form-button_v2").click(function() { submitForm2(); });
});


text:
Q: Java Regex not working multiline I got some kind help last night figuring out a regex to capture the smallest group possible. I need to take a string of lyrics and find a search phrase in it. The problem I am having is I can't get it to look multi line.
I have a text file with lyrics that I read in, this is just part of the song. (brackets aren't in text file I am just using them to show the group I am trying to capture.
 The first [time we fall in love.
 Love can be exciting, it can be a bloody bore.
 Love can be a pleasure or nothing but a chore.
 Love can be like a dull routine,
 It can run you around until you're out of steam.
 It can treat you well, it can treat you mean,
 Love can mess you around,
 Love can pick you up, it can bring you down].
 But they'll never know The feelings we show

The phrase I am using a regex for is
 time can bring you down

I use a stringbuilder to create the string of lyrics, the lyrics then contain the \n character. I tried doing a replaceAll to strip them but it still didn't work. If I go into the text file and just write one line saying time can bring you down, it works but if I write that into two lines it doesn't.
I tried using \n in my regex but it ended up capturing most of the song because time is the second  word. This is the regex that I currently am trying to use:
(?is)(\bTime\b)(?:(?!\n\b(?:time|can|bring|you|down)\b\n).)*(\bcan\b)(?:(?!\b(?:time|can|bring|you|down)\b).)*(\bbring\b)(?:(?!\b(?:time|can|bring|you|down)\b).)*(\byou\b)(?:(?!\b(?:time|can|bring|you|down)\b).)*(\bdown\b)

I am trying to capture what is in the brackets above in the lyrics. Here is my method that I am using it takes in the lyrics and searchPhrase and returns the length of the string it found.
    static int rankPhrase(String lyrics, String lyricsPhrase){
    //This takes in song lyrics and the phrase we are searching for

    //Split the phrase up into separate words
    String[] phrase = lyricsPhrase.split("[^a-zA-Z]+");

    //Helper string for regex so we can get smallest grouping
    String regexHelper = lyricsPhrase.replaceAll(" ","|").toLowerCase();

    //Start to build the regex
    StringBuilder regex = new StringBuilder("(?im)"+"(\\" + "b" + phrase[0] + "\\b)");

    //loop through each word in the phrase
    for(int i = 1; i < phrase.length; i++){

            //add this to the regex we will search for
            regex.append("(?:(?!\\b(?:" + regexHelper + ")\\b).)*(\\b" + phrase[i] + "\\b)");

    }

    //Create the pattern
    Pattern p = Pattern.compile(regex.toString(), Pattern.DOTALL);
    Matcher m = p.matcher(lyrics);

    //string for regex match found
    String regexMatch = "";
        while(m.find()){

            regexMatch = m.group();
            System.out.println(regexMatch);
    }

    return regexMatch.length();

}

I will continue to try and trying to figure it out, I think it's a matter of working \n into the regex but not 100% sure. Thank you!

A: You are trying to search a combination of words within a string. That can be easily achieved by using word1.*?word2 as a Regex. Here there can be n characters between word one and word two. ? denotes Lazy matching. As few as possible.
But Here the problem is you are trying to search a pattern in multiple lines. When you use the . meta character it works in a single line. . is all the meta characters except a new line character.
You can easily overcome this by using (.|\n)* rather than using .*
  I have updated your code below.
public class Regexa2 {
 static int rankPhrase(String lyrics, String lyricsPhrase){
    //This takes in song lyrics and the phrase we are searching for

    //Start to build the regex
    String regex = lyricsPhrase.replaceAll(" ","(.|\\n)*?").toLowerCase();

    System.out.println(regex);
    //Create the pattern
    Pattern p = Pattern.compile(regex.toString(), Pattern.DOTALL);
    Matcher m = p.matcher(lyrics);

    //string for regex match found
    String regexMatch = "";
        while(m.find()){

            regexMatch = m.group();
            System.out.println(regexMatch);
    }

    return regexMatch.length();

}

public static void main(String[] args) {
    String lyrics = "The first time we fall in love. \n" +
            "Love can be exciting, it can be a bloody bore. \n" +
            "Love can be a pleasure or nothing but a chore.\n" +
            "Love can be like a dull routine, \n" +
            "It can run you around until you're out of steam. \n" +
            "It can treat you well, it can treat you mean, \n" +
            "Love can mess you around, \n" +
            "Love can pick you up, it can bring you down. \n" +
            "But they'll never know The feelings we show ";
    String phrase = "time can bring you down";
    Regexa2.rankPhrase(lyrics, phrase);
 }
}


text:
Q: Can GTA V Online work between Xbox 360 and Xbox One Can someone on an Xbox 360 play GTA online with people on Xbox One and vice versa? Some guys in a lobby said he was on the 360 playing with me (I have an Xbox one) but I have a feeling he wasn't in the right state of mind. Is it possible?

A: No. Cross platform play is currently not possible between Xbox 360 and Xbox One in any game, let alone GTA V.


text:
Q: Vim syntax javaid.vim dotfile didn't work Recently I use Vim to write java program. However, the bad thing is that vim default java syntax is not satisfying.
I checked the help doc, type :help java.vim, and found this one http://www.fleiner.com/vim/syntax/javaid.vim. This dotfile can highlight most java standard classes. And it almost saved my day.
Then I followed the guide carefully, yet surprisingly got the error message
like this:
Error detected while processing /Applications/MacVim.app/Contents/Resources/vim/runtime/syntax/javaid.vim

E492: Not an editor command:   JavaHiLink javaR_Java javaR_
E492: Not an editor command:   JavaHiLink javaC_JavaApplet javaC_Java
E492: Not an editor command:   JavaHiLink javaR_JavaAwt javaR_Java
E492: Not an editor command:   JavaHiLink javaR_JavaAwtColor javaR_JavaAwt

And lot of similar error messages. I have read the doc and found the update day is 2005, so is something too old to compile correctly?
So, kind Stack Overflowers, can offer better ideas?

A: For compatibility with very old Vim versions, old syntax scripts defined a custom {filetype}HiLink command. I guess the javaid.vim syntax was written to reuse that definition from $VIMRUNTIME/syntax/java.vim, but that script has been cleaned up (some time ago).
As the syntax script seems to be unmaintained, I'd simply replace JavaHiLink with hi def link. This should fix the errors, and work in all Vim versions you'd encounter today.