问:
Trigger Velocity animation when scrolling over a div
I have a velocity animation that has to be loaded after scrolling down on a div. The div is not a scrollable div like a list, it's just a normal div. So what I want is something like I have the div displayed on screen and when I scroll down further on the website to load a certain animation. How do I do that? This is the div that when it is scrolled it should load the animation.

```<code>  <div id="specialDiv2">
      <div class="ui two column doubling stackable grid container">
          <div class="column ">
              <h1>What</h1>
              <p id="coolParagraph2">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
          </div>
          <div class="column  ">
              <img id="specialImage2" src="meganOMG.png"/>
          </div>
      </div>
      <div class="ui center aligned container">
          <a id="arrow1" href="#">
              <i class="huge red angle double down icon"></i>
          </a>
      </div>
  </div>
</code>```

This is the div where I have to apply the animation.

```<code><div id="specialDiv3">
    <div class="ui three column doubling stackable grid container">
        <div class="column columnFade">
            <h1>Benefits</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            <i class="massive diamond icon"></i>
        </div>
        <div class="column columnFade">
            <h1>Platform</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            <i class="massive diamond icon"></i>
        </div>
        <div class="column columnFade">
            <h1>Vision</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            <i class="massive diamond icon"></i>
        </div>
    </div>
    <br>
    <hr width="40%">
    <br>
</div>
</code>```

答:
You could make a function like this:

```<code>function isScrolledIntoView(elem) {
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();

  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
 }
</code>```

And use it in your javascript with your div (elem)

Here's a good question and answer that will help you, but it is complicated stuff:

Check if element is visible after scroll

Body:
I have a velocity animation that has to be loaded after scrolling down on a div. The div is not a scrollable div like a list, it's just a normal div. So what I want is something like I have the div displayed on screen and when I scroll down further on the website to load a certain animation. How do I do that? This is the div that when it is scrolled it should load the animation.

What

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

This is the div where I have to apply the animation.

Benefits

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Platform

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Vision

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Body:
You could make a function like this:

function isScrolledIntoView(elem) {
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();

  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
 }

And use it in your javascript with your div (elem)

Here's a good question and answer that will help you, but it is complicated stuff:

Check if element is visible after scroll


来源: stackexchange

问:
Pass keyword arguments to target function in Python threading.Thread
I want to pass named arguments to the target function, while creating a Thread object.

Following is the code that I have written:

```<code>import threading

def f(x=None, y=None):
    print x,y

t = threading.Thread(target=f, args=(x=1,y=2,))
t.start()
</code>```

I get a syntax error for "x=1", in Line 6.
I want to know how I can pass keyword arguments to the target function.

答:
You can also just pass a dictionary straight up to kwargs:</p>

```<code>import threading

def f(x=None, y=None):
    print x,y

my_dict = {'x':1, 'y':2}
t = threading.Thread(target=f, kwargs=my_dict)
t.start()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to pass named arguments to the target function, while creating a Thread object.

Following is the code that I have written:

import threading

def f(x=None, y=None):
    print x,y

t = threading.Thread(target=f, args=(x=1,y=2,))
t.start()

I get a syntax error for "x=1", in Line 6.
I want to know how I can pass keyword arguments to the target function.

Body:
You can also just pass a dictionary straight up to kwargs:

import threading

def f(x=None, y=None):
    print x,y

my_dict = {'x':1, 'y':2}
t = threading.Thread(target=f, kwargs=my_dict)
t.start()


问:
remove hover on submenu during media query
Im trying to remove the hover on my submenu when the media query is active.  Right now it works how I want above 979px which displays the submenu on hover.  However, at 979px and below the menu changes.  Im trying to get the submenu to always display and can't seem to figure it out.  there is a link attached to the services button so when its pressed to display the submenu you are re-directed whcih is why I want to display the submenu all the time at media query.

HTML:

```<code><!-- Nav Bar -->
  <div id="navbar">
   <label for="show-menu" class="show-menu">Menu ☰</label>
     <input type="checkbox" id="show-menu" role="button">
      <ul id="menu" class="nav">
        <li class="nav active"><a href="http://adanburlington.com/giotto2/index.html">Home</a></li>
        <li class="nav">
            <a href="http://adanburlington.com/giotto2/services.html">Services</a>
            <ul class="nav hidden">
                <li><a href="#">Fire Alarm Systems</a></li>
                <li><a href="#">Security & Intrusion</a></li>
                <li><a href="#">Closed Circuit TV</a></li>
                <li><a href="#">Access Control</a></li>
                <li><a href="#">Systems Intrigation</a></li>
            </ul>
        </li>
        <li class="nav"><a href="http://adanburlington.com/giotto2/about.html">About Us</a></li>
        <li class="nav"><a href="https://skyfex.com/client/" target="blank">Tech Support</a></li>
        <li class="nav"><a href="#">Photo Gallery</a></li>
        <li class="nav"><a href="#">Testimonials</a></li>
        <li class="nav"><a href="http://adanburlington.com/giotto2/contact.html">Contact Us</a></li>
      </ul>
  </div>
  <!-- Nav Bar End -->
</code>```

CSS:

```<code>ul.nav
{ list-style-type:none;
  margin:0;
  padding:0;
  position: absolute;}

  li.nav
{ display:inline-block;
float: left;
margin-right: 2px;}

li.nav a {
display:block;
min-width:153px;
height: 40px;
text-align: center;
line-height: 40px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #fff;
background: #724e27;
text-decoration: none;
}

li.nav:hover a {
background: #cccccc;
color: #2f3036;
}

li.nav:hover ul a {
background: #f3f3f3; /* Light grey */
color: #2f3036; /* dark Grey */
height: 40px;
line-height: 40px;

}

li.nav:hover ul a:hover {
background: #996633; /* Light Brown */
color: #fff;
}

li.active a, li.active a:hover
{ background: #cccccc;
 color: #2f3036;}

li.nav ul {
display: none;
}

li.nav ul li {
display: block;
float: none;
}

li.nav ul li a {
width: auto;
min-width: 100px;
padding: 0 20px;
}

ul.nav li a:hover + .hidden, .hidden:hover {
display: block;
z-index: 999;
}

.show-menu {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
text-decoration: none;
color: #261a0d;
background: #f3f3f3;
text-align: center;
padding: 10px 0;
display: none;
}

input[type=checkbox]{display: none;}

input[type=checkbox]:checked ~ #menu{display: block;}

/* Responsive Styles */

@media screen and (max-width : 979px){

ul.nav
{ position: static;
  display: none;}

li.nav {margin-bottom: 1px;}

ul.nav li, li.nav a {width: 100%;}

.show-menu {display:block;}

}
</code>```

答:
you can use display: block !important inside your media query to display your sub-menu on smaller screen.</p>

```<code>@media screen and (max-width : 979px){
    li.nav > ul.hidden {
        display: block !important;
    }
}
</code>```

Body:
Im trying to remove the hover on my submenu when the media query is active.  Right now it works how I want above 979px which displays the submenu on hover.  However, at 979px and below the menu changes.  Im trying to get the submenu to always display and can't seem to figure it out.  there is a link attached to the services button so when its pressed to display the submenu you are re-directed whcih is why I want to display the submenu all the time at media query.

HTML:

   Menu ☰
     <input type="checkbox" id="show-menu" role="button">

Home

            Services

Fire Alarm Systems

Security & Intrusion

Closed Circuit TV

Access Control

Systems Intrigation

About Us

Tech Support

Photo Gallery

Testimonials

Contact Us

CSS:

ul.nav
{ list-style-type:none;
  margin:0;
  padding:0;
  position: absolute;}

  li.nav
{ display:inline-block;
float: left;
margin-right: 2px;}

li.nav a {
display:block;
min-width:153px;
height: 40px;
text-align: center;
line-height: 40px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #fff;
background: #724e27;
text-decoration: none;
}

li.nav:hover a {
background: #cccccc;
color: #2f3036;
}

li.nav:hover ul a {
background: #f3f3f3; /* Light grey */
color: #2f3036; /* dark Grey */
height: 40px;
line-height: 40px;

}

li.nav:hover ul a:hover {
background: #996633; /* Light Brown */
color: #fff;
}

li.active a, li.active a:hover
{ background: #cccccc;
 color: #2f3036;}

li.nav ul {
display: none;
}

li.nav ul li {
display: block;
float: none;
}

li.nav ul li a {
width: auto;
min-width: 100px;
padding: 0 20px;
}

ul.nav li a:hover + .hidden, .hidden:hover {
display: block;
z-index: 999;
}

.show-menu {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
text-decoration: none;
color: #261a0d;
background: #f3f3f3;
text-align: center;
padding: 10px 0;
display: none;
}

input[type=checkbox]{display: none;}

input[type=checkbox]:checked ~ #menu{display: block;}

/* Responsive Styles */

@media screen and (max-width : 979px){

ul.nav
{ position: static;
  display: none;}

li.nav {margin-bottom: 1px;}

ul.nav li, li.nav a {width: 100%;}

.show-menu {display:block;}

}

Body:
you can use display: block !important inside your media query to display your sub-menu on smaller screen.

@media screen and (max-width : 979px){
    li.nav > ul.hidden {
        display: block !important;
    }
}


问:
What is a good way to get a function to use its default value for an argument when the argument is specified as None in Python?
Let's say I have a function (called function) that takes a boolean argument with default value of True like def function(argument1 = True).

Now let's say I want to use this function, specifying its argument using the output of another function (resolveArg) that checks for arguments in an existing infrastructure. This resolveArg method is used generally and if it can find the argument value destined for a given function (e.g. function), then it sets the function argument to it, otherwise it sets the argument to None.

How can I get function to use the default value of its argument if its argument is set to None by this other function (resolveArg)?

```<code>def resolveArg(argName = None):
    if argName in self.conf._argdict:
        return(self.conf._argdict[argName].value)
    else:
        return(None)

def function(argument1 = True)
    if argument1 is True:
        return(True)
    elif argument1 is False:
        return(False)
    else:
        raise(Exception)

function(argument1 = resolveArg("red"))
</code>```

答:
Probably you want to modify your implementation of function little bit as follow:

```<code>def function(argument1 = None)
    if argument1 is None:
       argument1 = True

    return argument1
</code>```

If you want to understand more about default function argument as None, you may want to refer to my other SO answer

Body:
Let's say I have a function (called function) that takes a boolean argument with default value of True like def function(argument1 = True).

Now let's say I want to use this function, specifying its argument using the output of another function (resolveArg) that checks for arguments in an existing infrastructure. This resolveArg method is used generally and if it can find the argument value destined for a given function (e.g. function), then it sets the function argument to it, otherwise it sets the argument to None.

How can I get function to use the default value of its argument if its argument is set to None by this other function (resolveArg)?

def resolveArg(argName = None):
    if argName in self.conf._argdict:
        return(self.conf._argdict[argName].value)
    else:
        return(None)

def function(argument1 = True)
    if argument1 is True:
        return(True)
    elif argument1 is False:
        return(False)
    else:
        raise(Exception)

function(argument1 = resolveArg("red"))

Body:
Probably you want to modify your implementation of function little bit as follow:

def function(argument1 = None)
    if argument1 is None:
       argument1 = True

    return argument1

If you want to understand more about default function argument as None, you may want to refer to my other SO answer


问:
Transform numpy matrix
I am trying to transform a numpy matrix (say 'Mat') in the following manner:

```<code>Mat[i,j] = Mat[i,j] - numpy.sum(Mat[i,:]) * numpy.sum(Mat[:,j])
</code>```

Given below is the code that I am using (two for loops). I was wondering if there is a faster method to implement this.

```<code>def Normalize(Mat):
    MargR = Mat.sum(axis=0)
    MargC = Mat.sum(axis=1)
    for i in range(len(Mat[:,0])):
        for j in range(len(Mat[0,:])):
            Mat[i,j] = Mat[i,j] - MargC[i]*MargR[j]
    return Mat
</code>```

Any help will be much appreciated.

答:
The second matrix you are multiplying is the outer product of summed rows and the summed columns, so you could write the new matrix as:</p>

```<code>Mat = Mat - np.outer(np.sum(Mat, axis=1), np.sum(Mat, axis=0))
</code>```

Title: Transform numpy matrix

Body:
I am trying to transform a numpy matrix (say 'Mat') in the following manner:

Mat[i,j] = Mat[i,j] - numpy.sum(Mat[i,:]) * numpy.sum(Mat[:,j])

Given below is the code that I am using (two for loops). I was wondering if there is a faster method to implement this.

def Normalize(Mat):
    MargR = Mat.sum(axis=0)
    MargC = Mat.sum(axis=1)
    for i in range(len(Mat[:,0])):
        for j in range(len(Mat[0,:])):
            Mat[i,j] = Mat[i,j] - MargC[i]*MargR[j]
    return Mat

Any help will be much appreciated.

Body:
The second matrix you are multiplying is the outer product of summed rows and the summed columns, so you could write the new matrix as:

Mat = Mat - np.outer(np.sum(Mat, axis=1), np.sum(Mat, axis=0))


问:
Getting lowest values in GROUP BY
```<code>WITH test_data AS (
  SELECT 1 key, 1 a, 2 b FROM dual UNION ALL  --# Lowest a for key=1
  SELECT 1 key, 2 a, 1 b FROM dual UNION ALL
  SELECT 2 key, 3 a, 3 b FROM dual UNION ALL  --# Lowest a for key=2, lowest b
  SELECT 2 key, 3 a, 4 b FROM dual UNION ALL
  SELECT 2 key, 4 a, 5 b FROM dual
)
</code>```

I'm trying to group by key, and retrieve the lowest a and the corresponding b (lowest b in case of ties), plus the SUM of its bs:

```<code>       KEY          A    FIRST_B      SUM_B
---------- ---------- ---------- ----------
         1          1          2          3
         2          3          3         12
</code>```

I can realize this with a sub-select

```<code>SELECT key, MIN(a) AS a, first_b, SUM(b) AS sum_b
FROM (
  SELECT key, a, b,
         FIRST_VALUE(b) OVER (PARTITION BY key ORDER BY a, b) AS first_b
  FROM test_data
)
GROUP BY key, first_b
</code>```

but I wonder if there is a way to avoid the sub-select, something like

```<code>SELECT key, a, SUM(b) AS sum_b,
       MIN( FIRST_VALUE(b) OVER (PARTITION BY key ORDER BY a, b) ) AS first_b
FROM test_data
GROUP BY key, a
</code>```

which raises ORA-30483: window  functions are not allowed here

Thanks in advance, Peter

答:
Are you looking for the first/last aggregate functions? Because of the MIN function, ordering by B on the first_b column should be redundant but that probably depends on how exactly you intend on using it.

```<code>WITH test_data AS (
  SELECT 1 key, 1 a, 2 b FROM dual UNION ALL  --# Lowest a for key=1
  SELECT 1 key, 2 a, 1 b FROM dual UNION ALL
  SELECT 2 key, 3 a, 3 b FROM dual UNION ALL  --# Lowest a for key=2, lowest b
  SELECT 2 key, 3 a, 4 b FROM dual UNION ALL
  SELECT 2 key, 4 a, 5 b FROM dual
)
select
  key,
  min(a) as a,
  min(b) keep (dense_rank first ORDER BY a, b) as first_b,
  SUM(b) AS sum_b
FROM test_data
GROUP BY key
</code>```

ContentLicense: CC BY-SA 2.5

Title: Getting lowest values in GROUP BY

Body:
WITH test_data AS (
  SELECT 1 key, 1 a, 2 b FROM dual UNION ALL  --# Lowest a for key=1
  SELECT 1 key, 2 a, 1 b FROM dual UNION ALL
  SELECT 2 key, 3 a, 3 b FROM dual UNION ALL  --# Lowest a for key=2, lowest b
  SELECT 2 key, 3 a, 4 b FROM dual UNION ALL
  SELECT 2 key, 4 a, 5 b FROM dual
)

I'm trying to group by key, and retrieve the lowest a and the corresponding b (lowest b in case of ties), plus the SUM of its bs:

       KEY          A    FIRST_B      SUM_B
---------- ---------- ---------- ----------
         1          1          2          3
         2          3          3         12

I can realize this with a sub-select

SELECT key, MIN(a) AS a, first_b, SUM(b) AS sum_b
FROM (
  SELECT key, a, b,
         FIRST_VALUE(b) OVER (PARTITION BY key ORDER BY a, b) AS first_b
  FROM test_data
)
GROUP BY key, first_b

but I wonder if there is a way to avoid the sub-select, something like

SELECT key, a, SUM(b) AS sum_b,
       MIN( FIRST_VALUE(b) OVER (PARTITION BY key ORDER BY a, b) ) AS first_b
FROM test_data
GROUP BY key, a

which raises ORA-30483: window  functions are not allowed here

Thanks in advance, Peter

Body:
Are you looking for the first/last aggregate functions? Because of the MIN function, ordering by B on the first_b column should be redundant but that probably depends on how exactly you intend on using it.

WITH test_data AS (
  SELECT 1 key, 1 a, 2 b FROM dual UNION ALL  --# Lowest a for key=1
  SELECT 1 key, 2 a, 1 b FROM dual UNION ALL
  SELECT 2 key, 3 a, 3 b FROM dual UNION ALL  --# Lowest a for key=2, lowest b
  SELECT 2 key, 3 a, 4 b FROM dual UNION ALL
  SELECT 2 key, 4 a, 5 b FROM dual
)
select
  key,
  min(a) as a,
  min(b) keep (dense_rank first ORDER BY a, b) as first_b,
  SUM(b) AS sum_b
FROM test_data
GROUP BY key


问:
Access @Model when @Model is a Task
How am I supposed to use a @Model thats a Task?

Razor:

```<code>@model Task<AreBuraas.Core.v1.Models.Category>

<article class="panel panel-primary">
    <section class="panel-heading">
        <h1>
            @Model.Name
        </h1>
        <h3>
            @Model.Description
        </h3>
    </section>
    <section class="panel-body">
        her kommer content!
    </section>
</article>
</code>```

Controller:

```<code>public IActionResult Display(int id)
{
    return View(_data.GetCategory(id));
}
</code>```

Error:

'Task' does not contain a definition for 'Name' and no
  extension method 'Name' accepting a first argument of type
  'Task' could be found (are you missing a using directive or
  an assembly reference?)

```<code>            @Model.Name
</code>```

'Task' does not contain a definition for 'Description' and
  no extension method 'Description' accepting a first argument of type
  'Task' could be found (are you missing a using directive or
  an assembly reference?)

```<code>                @Model.Description
</code>```

答:
You can't do that.

Instead, you should await the task in your controller and pass its result to the view.

Title: Access @Model when @Model is a Task

Body:
How am I supposed to use a @Model thats a Task?

Razor:

@model Task<AreBuraas.Core.v1.Models.Category>

            @Model.Name

            @Model.Description

        her kommer content!

Controller:

public IActionResult Display(int id)
{
    return View(_data.GetCategory(id));
}

Error:

'Task' does not contain a definition for 'Name' and no
  extension method 'Name' accepting a first argument of type
  'Task' could be found (are you missing a using directive or
  an assembly reference?)

            @Model.Name

'Task' does not contain a definition for 'Description' and
  no extension method 'Description' accepting a first argument of type
  'Task' could be found (are you missing a using directive or
  an assembly reference?)

                @Model.Description


问:
Need assistance moving files from git to git LFS, local is 15 commits ahead of remote
I have been using git & git lfs to keep track of things for a personal project in Unreal Engine. Initially, following a tutorial I set up my git & git LFS in such a way that git LFS didn't handle all my unreal engine files. This is now coming back to haunt me.

Several files that were small initially have now grown to a size close to 600 mb.

Examples:

remote: error: File
  BattleTanks/Content/Static/Landscape/Tiles/project.tmd.session is
  592.00 MB; this exceeds GitHub's file size limit of 100.00 MB

  remote: error: File BattleTanks/Content/_Levels/Battleground.umap is
  590.67 MB; this exceeds GitHub's file size limit of 100.00 MB

  remote: error: File BattleTanks/Content/_Levels/Battleground.umap is
  590.51 MB; this exceeds GitHub's file size limit of 100.00 MB

Recently I started playing around with creating larger levels for my game among other things. Stupidly, I only kept committing locally and since then have made considerable other changes that I am 15 commits ahead of my remote branch.

However, now the file that has been part of my commits since almost the beginning is far too large and I can't push any of my changes to the remote.

I have backed up my main folder and tried the BFG repo cleaner but I only managed to screw up my repo following some of the posted tutorials. I seem to be in a sort of predicament because I am so many commits ahead of my remote on my local machine.

So my questions are as follows:

What other things do I need to add to this question to help clarify? What information am I missing? I would be glad to get it - I'm not certain exactly how to structure my question.

How to fix? Any suggestions are welcome.

Should I just start fresh in a new repo and just redirect in the previous readme to the new repo?

I have pretty much stopped development until I can clean up my repo and get it right, my procrastination previously has put me in such a bind now and it's all my own fault for being lazy. I hope anyone can help me, after BFG didn't work and broke my repo locally (I had a backup) I am worried to just whack away at it now.

答:
I was able to solve the issue with BFG repo cleaner afterall. What I did was use

bfg --delete-files filename

then simply did

git push -f

Before I was doing

$ git reflog expire --expire=now --all && git gc --prune=now
  --aggressive

because the command prompt clearly suggests to do that after. This always caused too many unexpected problems, I'm not sure why.

At any length, I wanted to close this out since I solved the problem I was having.


问:
Can't figure out what's going on with RegExp question mark
I want to match sets of digits preceded by a dot, or nothing at all. I came up with the regular expression (?:\.\d+)?. However, it will match the string . even though the quantifier on \d is a plus. If I get rid of the last question mark, which I believe is making the group optional since there is no preceding quantifier, then it works fine. I am using the RegExp engine in JavaScript, specifically node.js in this case.

Here's what I got from my testing:

.123, without optional: true

., without optional: false

empty, without optional: false

.123, with optional: true

., with optional: true

empty, with optional: true

.123, expected: true

., expected: false

empty, expected: true

Thanks.

答:
Use

```<code>/^<your regex>$/
</code>```

as a general rule to make sure that your entire string is matched. Right now your regex allows the empty string which can be matched at any point.

Note that

```<code>/(?:\.\d+)?/.test('a') === true
</code>```

and the regex will match any nonempty string.

Body:
Use

/^<your regex>$/

as a general rule to make sure that your entire string is matched. Right now your regex allows the empty string which can be matched at any point.

Note that

/(?:\.\d+)?/.test('a') === true

and the regex will match any nonempty string.


答:
You need to add ^ and $ markers to the regex like so

```<code>^(?:\.\d+)?$
</code>```

Otherwise it would match an empty string at any point in the string.

Title: Can't figure out what's going on with RegExp question mark

Body:
I want to match sets of digits preceded by a dot, or nothing at all. I came up with the regular expression (?:\.\d+)?. However, it will match the string . even though the quantifier on \d is a plus. If I get rid of the last question mark, which I believe is making the group optional since there is no preceding quantifier, then it works fine. I am using the RegExp engine in JavaScript, specifically node.js in this case.

Here's what I got from my testing:

.123, without optional: true

., without optional: false

empty, without optional: false

.123, with optional: true

., with optional: true

empty, with optional: true

.123, expected: true

., expected: false

empty, expected: true

Thanks.

Body:
You need to add ^ and $ markers to the regex like so

^(?:\.\d+)?$

Otherwise it would match an empty string at any point in the string.


问:
'Chaincode fingerprint does not match' when querying from other peer
I set up a network on several servers. On one of the servers, the compiled chaincode is consistently different from the chaincode on other servers, resulting in the message:

```<code>Error: Error endorsing query: rpc error: code = Unknown desc = Error executing chaincode: Could not get deployment transaction from LSCC for mycc:1.0 - Get ChaincodeDeploymentSpec for mycc/torchplatformchannel from LSCC error: chaincode fingerprint mismatch data mismatch - <nil>
</code>```

I don't know how chaincode is compiled exactly, but when I run a number of peers on my own laptop, with the same configuration, the hash always matches. I use the normal command to install the chaincode on the peer from the cli (fabric-tools) container (peer chaincode install -n mycc -v 1.0 -p chaincode_example02). The host machines are similar:

```<code>root@fabric:~# uname -a
Linux fabric 4.4.0-81-generic #104-Ubuntu SMP Wed Jun 14 08:17:06 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
</code>```

Other server:

```<code>Linux fabric2 4.4.0-75-generic #96-Ubuntu SMP Thu Apr 20 09:56:33 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
</code>```

Docker versions are the same:

```<code>root@fabric:~# docker version
Client:
 Version:      17.06.0-ce
 API version:  1.30
 Go version:   go1.8.3
 Git commit:   02c1d87
 Built:        Fri Jun 23 21:23:31 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.06.0-ce
 API version:  1.30 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   02c1d87
 Built:        Fri Jun 23 21:19:04 2017
 OS/Arch:      linux/amd64
 Experimental: false
</code>```

Images are the same:

```<code>root@fabric:~# docker images
hyperledger/fabric-tools   x86_64-1.0.0-beta   ae6b0f53cb70        3 weeks ago         1.32GB
hyperledger/fabric-peer    x86_64-1.0.0-beta   e01c2b645f11        3 weeks ago         182MB
hyperledger/fabric-ca      x86_64-1.0.0-beta   e549e8c53c2e        3 weeks ago         238MB
</code>```

But the chaincode actually IS different:

```<code>root@286f0cd4bc82:/var/hyperledger/production/chaincodes# md5sum mycc.1.0
a96076f0cadf7c0e5c8da50ee5195078  mycc.1.0
root@286f0cd4bc82:/var/hyperledger/production/chaincodes# ls -la mycc.1.0
-rw-r--r-- 1 root root 2441 Jul  4 12:55 mycc.1.0
</code>```

And on the other side:

```<code>root@6089fc35a6d9:/var/hyperledger/production/chaincodes# md5sum mycc.1.0
918307de80ef18de378c63e4138ccdf5  mycc.1.0
root@6089fc35a6d9:/var/hyperledger/production/chaincodes# ls -la mycc.1.0
-rw-r--r-- 1 root root 2448 Jul  4 12:53 mycc.1.0
</code>```

What could be the reason for a chaincode not having the same hash on a different peer?

答:
If you pick a machine from which to do the install but pointing to different peers where the chaincode is to be installed, like

```<code> CORE_PEER_ADDRESS=<peer1>:7051 peer chaincode install ....
</code>```

and

```<code> CORE_PEER_ADDRESS=<peer2>:7051 peer chaincode install ....
</code>```

Then you should end up with the same install on both peer1 and peer2.

Alternately, as Artem points above you can package the CC once into "mycc.pak"

```<code> peer chaincode package -n mycc -p <path to mycc> -v 0 mycc.pak
</code>```

and can install it on multiple peers with a slightly different install command

```<code> peer chaincode install mycc.pak
</code>```

Body:
I set up a network on several servers. On one of the servers, the compiled chaincode is consistently different from the chaincode on other servers, resulting in the message:

Error: Error endorsing query: rpc error: code = Unknown desc = Error executing chaincode: Could not get deployment transaction from LSCC for mycc:1.0 - Get ChaincodeDeploymentSpec for mycc/torchplatformchannel from LSCC error: chaincode fingerprint mismatch data mismatch - <nil>

I don't know how chaincode is compiled exactly, but when I run a number of peers on my own laptop, with the same configuration, the hash always matches. I use the normal command to install the chaincode on the peer from the cli (fabric-tools) container (peer chaincode install -n mycc -v 1.0 -p chaincode_example02). The host machines are similar:

root@fabric:~# uname -a
Linux fabric 4.4.0-81-generic #104-Ubuntu SMP Wed Jun 14 08:17:06 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

Other server:

Linux fabric2 4.4.0-75-generic #96-Ubuntu SMP Thu Apr 20 09:56:33 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

Docker versions are the same:

root@fabric:~# docker version
Client:
 Version:      17.06.0-ce
 API version:  1.30
 Go version:   go1.8.3
 Git commit:   02c1d87
 Built:        Fri Jun 23 21:23:31 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.06.0-ce
 API version:  1.30 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   02c1d87
 Built:        Fri Jun 23 21:19:04 2017
 OS/Arch:      linux/amd64
 Experimental: false

Images are the same:

root@fabric:~# docker images
hyperledger/fabric-tools   x86_64-1.0.0-beta   ae6b0f53cb70        3 weeks ago         1.32GB
hyperledger/fabric-peer    x86_64-1.0.0-beta   e01c2b645f11        3 weeks ago         182MB
hyperledger/fabric-ca      x86_64-1.0.0-beta   e549e8c53c2e        3 weeks ago         238MB

But the chaincode actually IS different:

root@286f0cd4bc82:/var/hyperledger/production/chaincodes# md5sum mycc.1.0
a96076f0cadf7c0e5c8da50ee5195078  mycc.1.0
root@286f0cd4bc82:/var/hyperledger/production/chaincodes# ls -la mycc.1.0
-rw-r--r-- 1 root root 2441 Jul  4 12:55 mycc.1.0

And on the other side:

root@6089fc35a6d9:/var/hyperledger/production/chaincodes# md5sum mycc.1.0
918307de80ef18de378c63e4138ccdf5  mycc.1.0
root@6089fc35a6d9:/var/hyperledger/production/chaincodes# ls -la mycc.1.0
-rw-r--r-- 1 root root 2448 Jul  4 12:53 mycc.1.0

What could be the reason for a chaincode not having the same hash on a different peer?

Body:
If you pick a machine from which to do the install but pointing to different peers where the chaincode is to be installed, like

 CORE_PEER_ADDRESS=<peer1>:7051 peer chaincode install ....

and

 CORE_PEER_ADDRESS=<peer2>:7051 peer chaincode install ....

Then you should end up with the same install on both peer1 and peer2.

Alternately, as Artem points above you can package the CC once into "mycc.pak"

 peer chaincode package -n mycc -p <path to mycc> -v 0 mycc.pak

and can install it on multiple peers with a slightly different install command

 peer chaincode install mycc.pak


问:
Changing the hostname on WSL
sudo hostname XYZ does not seems to work in WSL.

I recently reinstalled Windows 10 and my wsl hostname is DESKTOP-XXXXXX. I'm trying to change it to something else. I tried the following:

```<code>sudo hostname wsl
</code>```

I also changed /etc/hostname to "wsl" and changed /etc/hosts to "127.0.1.1 wsl.localdomain wsl".

Every time I restart WSL, it resets the hostname to the windows name. How do I change the wsl hostname permanently?

答: Try to change the host system's name from System --> Change Settings --> Change. In some sense, it makes sense for WSL to update its hostname to match that of the host computer.

ContentLicense: CC BY-SA 4.0

Title: Changing the hostname on WSL

Body:
sudo hostname XYZ does not seems to work in WSL.

I recently reinstalled Windows 10 and my wsl hostname is DESKTOP-XXXXXX. I'm trying to change it to something else. I tried the following:

sudo hostname wsl

I also changed /etc/hostname to "wsl" and changed /etc/hosts to "127.0.1.1 wsl.localdomain wsl".

Every time I restart WSL, it resets the hostname to the windows name. How do I change the wsl hostname permanently?


问:
line chart not working using react-d3-components in create-react-app
I'm new to react and I'm trying to put react-d3-component in the create-react-app boilerplate.

App.js looks like :

```<code>import ReactD3 from 'react-d3-components';
import React from 'react';

var LineChart = ReactD3.LineChart;
var Brush = ReactD3.Brush;
var d3 = ReactD3.d3;

var App = React.createClass({
    getInitialState: function() {
        return {
            data: {label: '', values: [
                {x: new Date(2015, 2, 5), y: 1},
                {x: new Date(2015, 2, 6), y: 2},
                {x: new Date(2015, 2, 7), y: 0},
                {x: new Date(2015, 2, 8), y: 3},
                {x: new Date(2015, 2, 9), y: 2},
                {x: new Date(2015, 2, 10), y: 3},
                {x: new Date(2015, 2, 11), y: 4},
                {x: new Date(2015, 2, 12), y: 4},
                {x: new Date(2015, 2, 13), y: 1},
                {x: new Date(2015, 2, 14), y: 5},
                {x: new Date(2015, 2, 15), y: 0},
                {x: new Date(2015, 2, 16), y: 1},
                {x: new Date(2015, 2, 16), y: 1},
                {x: new Date(2015, 2, 18), y: 4},
                {x: new Date(2015, 2, 19), y: 4},
                {x: new Date(2015, 2, 20), y: 5},
                {x: new Date(2015, 2, 21), y: 5},
                {x: new Date(2015, 2, 22), y: 5},
                {x: new Date(2015, 2, 23), y: 1},
                {x: new Date(2015, 2, 24), y: 0},
                {x: new Date(2015, 2, 25), y: 1},
                {x: new Date(2015, 2, 26), y: 1}
            ]},
            xScale: d3.time.scale().domain([new Date(2015, 2, 5), new Date(2015, 2, 26)]).range([0, 400 - 70]),
            xScaleBrush: d3.time.scale().domain([new Date(2015, 2, 5), new Date(2015, 2, 26)]).range([0, 400 - 70])
        };
    },

    render: function() {
        return (
            <div>
                <LineChart
                    data={this.state.data}
                    width={400}
                    height={400}
                    margin={{top: 10, bottom: 50, left: 50, right: 20}}
                    xScale={this.state.xScale}
                    xAxis={{tickValues: this.state.xScale.ticks(d3.time.day, 2), tickFormat: d3.time.format("%m/%d")}}
                />
                <div className="brush" style={{float: 'none'}}>
                    <Brush
                        width={400}
                        height={50}
                        margin={{top: 0, bottom: 30, left: 50, right: 20}}
                        xScale={this.state.xScaleBrush}
                        extent={[new Date(2015, 2, 10), new Date(2015, 2, 12)]}
                        onChange={this._onChange}
                        xAxis={{tickValues: this.state.xScaleBrush.ticks(d3.time.day, 2), tickFormat: d3.time.format("%m/%d")}}
                    />
                </div>
            </div>
        );
    },

    _onChange: function(extent) {
        this.setState({xScale: d3.time.scale().domain([extent[0], extent[1]]).range([0, 400 - 70])});
    }
});
export default App;
</code>```

index.js looks like :

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));
</code>```

i have already installed react-d3-components also it's there in package.json ; still I get errors like :

TypeError: Cannot read property 'LineChart' of undefined

Also, where ever there is d3.time.day there it says unresolved function. I also tried importing d3 the other way using :

import * as d3 from 'd3'.

But still I get some different errors.

Please suggest what I'm doing wrong, so that I can set up my initial code to work.

Thanks

答:
Try this instead:

```<code>import { LineChart, Brush, d3 } from 'react-d3-components';
</code>```

It seems to me like those are named exports rather than a single default export.

Body:
I'm new to react and I'm trying to put react-d3-component in the create-react-app boilerplate.

App.js looks like :

import ReactD3 from 'react-d3-components';
import React from 'react';

var LineChart = ReactD3.LineChart;
var Brush = ReactD3.Brush;
var d3 = ReactD3.d3;

var App = React.createClass({
    getInitialState: function() {
        return {
            data: {label: '', values: [
                {x: new Date(2015, 2, 5), y: 1},
                {x: new Date(2015, 2, 6), y: 2},
                {x: new Date(2015, 2, 7), y: 0},
                {x: new Date(2015, 2, 8), y: 3},
                {x: new Date(2015, 2, 9), y: 2},
                {x: new Date(2015, 2, 10), y: 3},
                {x: new Date(2015, 2, 11), y: 4},
                {x: new Date(2015, 2, 12), y: 4},
                {x: new Date(2015, 2, 13), y: 1},
                {x: new Date(2015, 2, 14), y: 5},
                {x: new Date(2015, 2, 15), y: 0},
                {x: new Date(2015, 2, 16), y: 1},
                {x: new Date(2015, 2, 16), y: 1},
                {x: new Date(2015, 2, 18), y: 4},
                {x: new Date(2015, 2, 19), y: 4},
                {x: new Date(2015, 2, 20), y: 5},
                {x: new Date(2015, 2, 21), y: 5},
                {x: new Date(2015, 2, 22), y: 5},
                {x: new Date(2015, 2, 23), y: 1},
                {x: new Date(2015, 2, 24), y: 0},
                {x: new Date(2015, 2, 25), y: 1},
                {x: new Date(2015, 2, 26), y: 1}
            ]},
            xScale: d3.time.scale().domain([new Date(2015, 2, 5), new Date(2015, 2, 26)]).range([0, 400 - 70]),
            xScaleBrush: d3.time.scale().domain([new Date(2015, 2, 5), new Date(2015, 2, 26)]).range([0, 400 - 70])
        };
    },

    render: function() {
        return (

                <LineChart
                    data={this.state.data}
                    width={400}
                    height={400}
                    margin={{top: 10, bottom: 50, left: 50, right: 20}}
                    xScale={this.state.xScale}
                    xAxis={{tickValues: this.state.xScale.ticks(d3.time.day, 2), tickFormat: d3.time.format("%m/%d")}}
                />

                    <Brush
                        width={400}
                        height={50}
                        margin={{top: 0, bottom: 30, left: 50, right: 20}}
                        xScale={this.state.xScaleBrush}
                        extent={[new Date(2015, 2, 10), new Date(2015, 2, 12)]}
                        onChange={this._onChange}
                        xAxis={{tickValues: this.state.xScaleBrush.ticks(d3.time.day, 2), tickFormat: d3.time.format("%m/%d")}}
                    />

        );
    },

    _onChange: function(extent) {
        this.setState({xScale: d3.time.scale().domain([extent[0], extent[1]]).range([0, 400 - 70])});
    }
});
export default App;

index.js looks like :

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

i have already installed react-d3-components also it's there in package.json ; still I get errors like :

TypeError: Cannot read property 'LineChart' of undefined

Also, where ever there is d3.time.day there it says unresolved function. I also tried importing d3 the other way using :

import * as d3 from 'd3'.

But still I get some different errors.

Please suggest what I'm doing wrong, so that I can set up my initial code to work.

Thanks

Body:
Try this instead:

import { LineChart, Brush, d3 } from 'react-d3-components';

It seems to me like those are named exports rather than a single default export.


答: This is in fact a thing you should focus on With a controller. The @model in razor syntax cannot be a task. Instead, this is What controller is for, and by convention it should pass the actual result to the view.</p>

Title: Access @Model when @Model is a Task


问:
PHP / Wordpress
I have a piece of php code that creates nice looking pagination, however when the permalinks are set to default (page=?284) rather than something like post name (/post-name) the pagination buttons don't work and just keep loading the first page content.

```<code><?php
global $wp_query;
$total = $wp_query->max_num_pages;
if($total > 1) {
if ( !$current_page = get_query_var('paged') ){$current_page = 1;}
$perm_structure = get_option('permalink_structure');
$format = empty($perm_structure) ? '&page=%#%' : 'page/%#%/';
$paginate_return_data = paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => $format,
'current' => $current_page,
'total' => $total,
'mid_size' => 4,
'type' => 'plain'
));
echo $paginate_return_data;
}
?>
</code>```

Can you tell what is going wrong with this code to only allow for the post name style of permalinks to work?

答:
This might help
I had a look at the paginate_links function
https://codex.wordpress.org/Function_Reference/paginate_links

It has that the default for the total parameter is 1.
However if I pass 1 to the function it returns null.

In the example below I passed 2 and the var_dump shows that 2 links  are returned. So maybe you need to add a check to see if $total is 2 or more.

```<code>$paginate_return_data = paginate_links( array(
// 'base' => '%_%',
'base' => get_pagenum_link(1) . '%_%',
'format' => $format ,
'current' => $current_page,
// 'total' => $total,
'total' => 2
 ) );

var_dump($paginate_return_data);
</code>```

Title: PHP / Wordpress

Body:
I have a piece of php code that creates nice looking pagination, however when the permalinks are set to default (page=?284) rather than something like post name (/post-name) the pagination buttons don't work and just keep loading the first page content.

<?php
global $wp_query;
$total = $wp_query->max_num_pages;
if($total > 1) {
if ( !$current_page = get_query_var('paged') ){$current_page = 1;}
$perm_structure = get_option('permalink_structure');
$format = empty($perm_structure) ? '&page=%#%' : 'page/%#%/';
$paginate_return_data = paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => $format,
'current' => $current_page,
'total' => $total,
'mid_size' => 4,
'type' => 'plain'
));
echo $paginate_return_data;
}
?>

Can you tell what is going wrong with this code to only allow for the post name style of permalinks to work?

Body:
This might help
I had a look at the paginate_links function
https://codex.wordpress.org/Function_Reference/paginate_links

It has that the default for the total parameter is 1.
However if I pass 1 to the function it returns null.

In the example below I passed 2 and the var_dump shows that 2 links  are returned. So maybe you need to add a check to see if $total is 2 or more.

$paginate_return_data = paginate_links( array(
// 'base' => '%_%',
'base' => get_pagenum_link(1) . '%_%',
'format' => $format ,
'current' => $current_page,
// 'total' => $total,
'total' => 2
 ) );

var_dump($paginate_return_data);


问:
Angular 2 Router: Navigating to other components
Given the root routing module

```<code>const appRoutes: Routes = [
    {
        path: '',
        component: HomeComponent,
        children: [
            {
                path: 'users',
                loadChildren: './pages/users/users.module#UsersModule'
            }
        ]
    },
    {path: '', redirectTo: '', pathMatch: 'full'},
    {path: '**', redirectTo: '/login'}
];

export const appRouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);
</code>```

and the users routing module

```<code>const usersRoutes: Routes = [
    {
        path: '', component: UsersComponent,
        children: [
            {path: 'admittances', component: AdmittancesComponent},
            {path: 'admittance/:id', component: AdmittanceDetailComponent}
        ]
    }
];

export const usersRouting: ModuleWithProviders = RouterModule.forChild(usersRoutes);
</code>```

i want to navigate from the AdmittancesComponent to the AdmittanceDetailComponent.

But, instead of using

```<code>this._router.navigate(['admittance', id]); // ERROR
</code>```

i rather have to use

```<code>this._router.navigate(['users/admittance', id]); // WORKS
</code>```

Can somebody explain why the first example is not working and why the second one fixes it?

答:
The following link is from the Angular documentation: https://angular.io/guide/router#relative-navigation

For relative routing using the .navigate, you need syntax like this:

```<code>this.router.navigate([crisis.id], { relativeTo: this.route });
</code>```

Body:
Given the root routing module

const appRoutes: Routes = [
    {
        path: '',
        component: HomeComponent,
        children: [
            {
                path: 'users',
                loadChildren: './pages/users/users.module#UsersModule'
            }
        ]
    },
    {path: '', redirectTo: '', pathMatch: 'full'},
    {path: '**', redirectTo: '/login'}
];

export const appRouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);

and the users routing module

const usersRoutes: Routes = [
    {
        path: '', component: UsersComponent,
        children: [
            {path: 'admittances', component: AdmittancesComponent},
            {path: 'admittance/:id', component: AdmittanceDetailComponent}
        ]
    }
];

export const usersRouting: ModuleWithProviders = RouterModule.forChild(usersRoutes);

i want to navigate from the AdmittancesComponent to the AdmittanceDetailComponent.

But, instead of using

this._router.navigate(['admittance', id]); // ERROR

i rather have to use

this._router.navigate(['users/admittance', id]); // WORKS

Can somebody explain why the first example is not working and why the second one fixes it?

Body:
The following link is from the Angular documentation: https://angular.io/guide/router#relative-navigation

For relative routing using the .navigate, you need syntax like this:

this.router.navigate([crisis.id], { relativeTo: this.route });


问:
How to implement Vlookup formula drag down in vba
Why was the range (Rg) not called in vlookup function of my vba code below,  is there any correction needed to make it work right?  </p>

```<code>Sub Vlkuprangcall()
  Dim strColum As String
  Dim Rg As Range
  Set Rg = ActiveWorkbook.Sheets(1).Range("F4:H9")

  With ActiveSheet
   a = ActiveCell.Column
   lastrow = 9
   strColumn = Split(ActiveCell.Address, "$")(1)

   ActiveCell.FormulaR1C1 = "=vlookup(RC[-2],Rg,3,0)"
   ActiveCell.AutoFill Destination:=Range(ActiveCell, Range(strColumn & lastrow))

End Sub
</code>```

答:
Not sure why in your setup isn't working for Naming that Range and use it to set FormulaR1C1. Did a mock up and below code works.

Consider this in Sheet1:

And this in Sheet2:

Running the Sub yields:

Code:

```<code>Sub VlkupRangCall()
    Dim strColumn As String, lastrow As Long

    With ActiveSheet
        lastrow = 9
        strColumn = Split(ActiveCell.Address, "$")(1)

        .Range(ActiveCell, Range(strColumn & lastrow)).FormulaR1C1 = "=vlookup(RC[-2],MyRange,3,FALSE)"
    End With
End Sub
</code>```

Things you can improve:

Use a Table instead of fixed Range

Rename this Table to something more meaningful say "MyRange" (just to match the code above)

Avoid fixing the lastrow

Use module level Private Const for these FormulaR1C1 if you have a lot of them to auto fill formula

Body:
Why was the range (Rg) not called in vlookup function of my vba code below,  is there any correction needed to make it work right?

Sub Vlkuprangcall()
  Dim strColum As String
  Dim Rg As Range
  Set Rg = ActiveWorkbook.Sheets(1).Range("F4:H9")

  With ActiveSheet
   a = ActiveCell.Column
   lastrow = 9
   strColumn = Split(ActiveCell.Address, "$")(1)

   ActiveCell.FormulaR1C1 = "=vlookup(RC[-2],Rg,3,0)"
   ActiveCell.AutoFill Destination:=Range(ActiveCell, Range(strColumn & lastrow))

End Sub

Body:
Not sure why in your setup isn't working for Naming that Range and use it to set FormulaR1C1. Did a mock up and below code works.

Consider this in Sheet1:

And this in Sheet2:

Running the Sub yields:

Code:

Sub VlkupRangCall()
    Dim strColumn As String, lastrow As Long

    With ActiveSheet
        lastrow = 9
        strColumn = Split(ActiveCell.Address, "$")(1)

        .Range(ActiveCell, Range(strColumn & lastrow)).FormulaR1C1 = "=vlookup(RC[-2],MyRange,3,FALSE)"
    End With
End Sub

Things you can improve:

Use a Table instead of fixed Range

Rename this Table to something more meaningful say "MyRange" (just to match the code above)

Avoid fixing the lastrow

Use module level Private Const for these FormulaR1C1 if you have a lot of them to auto fill formula


问:
Get the first element of pointer array in C?
I've been searching for a while now on how to do this. The methods I have found have not yielded success so far.

GNU Readline Info

Within that page, there is an example program called fileman.c, in particular this function:

```<code>/* Execute a command line. */
int
execute_line (line)
     char *line;
{
  register int i;
  COMMAND *command;
  char *word;

  /* Isolate the command word. */
  i = 0;
  while (line[i] && whitespace (line[i]))
    i++;
  word = line + i;

  while (line[i] && !whitespace (line[i]))
    i++;

  if (line[i])
    line[i++] = '\0';

  command = find_command (word);

  if (!command)
    {
      fprintf (stderr, "%s: No such command for FileMan.\n", word);
      return (-1);
    }

  /* Get argument to command, if any. */
  while (whitespace (line[i]))
    i++;

  word = line + i;

  /* Call the function. */
  return ((*(command->func)) (word));
}
</code>```

I am trying to understand how to access the char *word in such a way to be able to inspect it's elements? For example - if I wanted to check that the first element of the char *word is '#' and based on that do certain logic as opposed to when the word starts with anything else? I'm new to C and find that I have become accustomed to a lot of things in other languages; cough Python; that are inherently more difficult in C.

Thanks!

答:
I was able to solve this with a tokenizer.

```<code>/*Tokenizer, splits the arguments and detects presence of i/o or piping.*/
void Tokenize(char *sentence, char** StorageArray, char * delimiter)
{
    char *token;
    char *next_token;
    int counter = 1, position = 0;
    token = strtok(sentence, delimiter);
    next_token = token;
    while (next_token != NULL){
        TokenCount++;
        StorageArray[position] = token;

        /*Check for input / output markers*/
        if(strcmp(StorageArray[position], "<") == 0){ flagInput = 1;}
        if(strcmp(StorageArray[position], ">") == 0){ flagOutput = 1;}
        /*Check for pipeline instructions.*/
        if(strcmp(StorageArray[position], "|") == 0){ flagPipeInst = 1;}

        position++;
        if((next_token = strtok(NULL, delimiter))){
            token = next_token;
        }
        counter++;
    }
    counter--;
}
</code>```

I got all the tokens prior to passing things into the execute command.

Body:
I've been searching for a while now on how to do this. The methods I have found have not yielded success so far.

GNU Readline Info

Within that page, there is an example program called fileman.c, in particular this function:

/* Execute a command line. */
int
execute_line (line)
     char *line;
{
  register int i;
  COMMAND *command;
  char *word;

  /* Isolate the command word. */
  i = 0;
  while (line[i] && whitespace (line[i]))
    i++;
  word = line + i;

  while (line[i] && !whitespace (line[i]))
    i++;

  if (line[i])
    line[i++] = '\0';

  command = find_command (word);

  if (!command)
    {
      fprintf (stderr, "%s: No such command for FileMan.\n", word);
      return (-1);
    }

  /* Get argument to command, if any. */
  while (whitespace (line[i]))
    i++;

  word = line + i;

  /* Call the function. */
  return ((*(command->func)) (word));
}

I am trying to understand how to access the char *word in such a way to be able to inspect it's elements? For example - if I wanted to check that the first element of the char *word is '#' and based on that do certain logic as opposed to when the word starts with anything else? I'm new to C and find that I have become accustomed to a lot of things in other languages; cough Python; that are inherently more difficult in C.

Thanks!

Body:
I was able to solve this with a tokenizer.

/*Tokenizer, splits the arguments and detects presence of i/o or piping.*/
void Tokenize(char *sentence, char** StorageArray, char * delimiter)
{
    char *token;
    char *next_token;
    int counter = 1, position = 0;
    token = strtok(sentence, delimiter);
    next_token = token;
    while (next_token != NULL){
        TokenCount++;
        StorageArray[position] = token;

        /*Check for input / output markers*/
        if(strcmp(StorageArray[position], "<") == 0){ flagInput = 1;}
        if(strcmp(StorageArray[position], ">") == 0){ flagOutput = 1;}
        /*Check for pipeline instructions.*/
        if(strcmp(StorageArray[position], "|") == 0){ flagPipeInst = 1;}

        position++;
        if((next_token = strtok(NULL, delimiter))){
            token = next_token;
        }
        counter++;
    }
    counter--;
}

I got all the tokens prior to passing things into the execute command.


问:
Return type in demangled member function name
What is the reason for the g++ abi::__cxa_demangle function to not return the return value for member functions?

Here's a working example of this behavior

```<code>#include <execinfo.h>
#include <cxxabi.h>
#include <iostream>

struct Foo {
    void operator()() const
    {
        constexpr int buf_size = 100;
        static void *buffer[buf_size];
        int nptrs = backtrace(buffer, buf_size);
        char **strings = backtrace_symbols(buffer, nptrs);
        for(int i = 0; i < nptrs; ++i) {

            auto str = std::string(strings[i]);
            auto first = str.find_last_of('(') + 1;
            auto last = str.find_last_of(')');
            auto mas = str.find_last_of('+');

            int status;
            char* result = abi::__cxa_demangle(str.substr(first, mas-first).c_str(), nullptr, nullptr, &status);
            if (status == 0) std::cout << result << std::endl;
        }
    }
};

int main () {
    Foo f;
    f();
}
</code>```

and after compiling with
g++ foo.cpp -std=c++11 -rdynamic
the output is
Foo::operator()() const

Is there a way to get a consistent behavior, this is, getting also the return value for the member functions?

答:
Mangling/demangling of function names is beyond the scope of the C++ Standard. It's purely compiler's responsibility and necessity to mangle functions in such way that two different functions will have different mangled representations (symbols).

In the same time, as declaring two functions that only differ by their return type is prohibited by the Standard, there's no need for the compiler to mangle the return type, as there will be no benefit.

What you are seeing is just a consequence of the compiler being reasonably lazy.

Also, here's a rextester with a more complete example (including a global function in the backtrace).

Body:
What is the reason for the g++ abi::__cxa_demangle function to not return the return value for member functions?

Here's a working example of this behavior

#include <execinfo.h>
#include <cxxabi.h>
#include <iostream>

struct Foo {
    void operator()() const
    {
        constexpr int buf_size = 100;
        static void *buffer[buf_size];
        int nptrs = backtrace(buffer, buf_size);
        char **strings = backtrace_symbols(buffer, nptrs);
        for(int i = 0; i < nptrs; ++i) {

            auto str = std::string(strings[i]);
            auto first = str.find_last_of('(') + 1;
            auto last = str.find_last_of(')');
            auto mas = str.find_last_of('+');

            int status;
            char* result = abi::__cxa_demangle(str.substr(first, mas-first).c_str(), nullptr, nullptr, &status);
            if (status == 0) std::cout << result << std::endl;
        }
    }
};

int main () {
    Foo f;
    f();
}

and after compiling with
g++ foo.cpp -std=c++11 -rdynamic
the output is
Foo::operator()() const

Is there a way to get a consistent behavior, this is, getting also the return value for the member functions?


问:
Speed up BOW/LINEAR animation in Here map sdk
I am working with Here map sdk in android. I have applied Bow animation for centering markers and for all other things. When i compare it to ios code it is slower than ios.
How can i make this inbuild animations of here map faster?

Thanks

答: Unfortunately, the SDK APIs do not allow you to control the speed of the pre-defined animations.</p>


问:
Local database vs Server database in Android Development
What are the differences between a local database and a server database?</p>

答:
I think you know the basic answer:

-Local Database: the database is located on the User's Android Device.

-Server Database: the User's Android Device must connect to an external server to access the database.

Here is my real world example of my usages of both:

I was tasked to develop an app for "Secret Shoppers" employed by Sam's Club. Basically they had to go to different grocery stores, and report prices using the app, and that data must be saved in Sam's Clubs Databases (On THEIR Servers). Here was 'the catch', not every Secret Shopper had a tablet with a 4g network, thus could only transfer the data while they were on WiFi.

So what I did was create an exact clone of their databases using SQLite, every time they 'submitted' a report of products and prices:

First I checked that the User's Android Device had internet access.

If they DID HAVE internet at the time of submitting, the report would be sent to Sam's Club servers as normal.

If they DID NOT HAVE internet at the time of submitting, the report would ONLY save on the LOCAL Database on the Android Device with a FLAG indicating it has not been sent to Sam's Club Servers.

When the app is run with internet, it will then send the those flagged reports to Sam's Club Servers.

So basically, I used a LOCAL Database that SYNCS with a SERVER Database each time the app is run. Hope this helps with the 'picture' you are looking for in terms of Local vs Server in Android Development specifically.


问:
Can the compiler optimize out the empty base if the class contains a member of base class type as first element, followed by other members?
Consider:

```<code>struct empty {};
struct child : empty {
    empty a[sizeof(int) / sizeof(empty)];
    int b;
};
// Assume sizeof(int) >= sizeof(empty)
</code>```

Does the standard mandate that sizeof(child) is more than 2 * sizeof(int)?

The way I see it, nothing prohibits the baseclass-subobject from sharing its address with member b.

If not, are there any common ABIs exploiting that at all?

答:
Let us first check the rule that allows empty base class optimization to acquaint ourselves with the terminology:

N4659 standard draft [intro.object]

7 Unless it is a bit-field (12.2.4), a most derived object shall have a nonzero size and shall occupy one or more
bytes of storage. Base class subobjects may have zero size. [snip]

Then a requirement about distinct addresses:

8 Unless an object is a bit-field or a base class subobject of zero size, the address of that object is the address
of the first byte it occupies. Two objects a and b with overlapping lifetimes that are not bit-fields may have
the same address if one is nested within the other, or if at least one is a base class subobject of zero size and
they are of different types; otherwise, they have distinct addresses.

The empty base subobject and the first element of the member array may not have the same address because they are of same type.

Therefore, if we assume that the base subobject must be ordered before the members and that the members must be in declaration order, padding is required to achieve distinct addresses. However, I cannot find a rule in the standard that would require such order.

The portable Itanium C++ ABI (used by Clang and GCC) does specify the order, and under that specification, padding is indeed required:

2.4 Non-POD Class Types

II. Allocation of Members Other Than Virtual Bases

For each data component D (first the primary base of C, if any, then the non-primary, non-virtual direct base classes in declaration order, then the non-static data members and unnamed bitfields in declaration order), allocate as follows:

A different ABI might be able to exploit EBCO here, if it allows non-declaration order sub-objects or member subobjects before bases in the memory layout. At least as a special case with empty bases. I don't know if such ABI exist.

Body:
Consider:

struct empty {};
struct child : empty {
    empty a[sizeof(int) / sizeof(empty)];
    int b;
};
// Assume sizeof(int) >= sizeof(empty)

Does the standard mandate that sizeof(child) is more than 2 * sizeof(int)?

The way I see it, nothing prohibits the baseclass-subobject from sharing its address with member b.

If not, are there any common ABIs exploiting that at all?


问:
Match and replace a specific underscore to tab in shell
I want to replace a specific underscore from a file and replace it with a tab. The problem is that I have a lot of underscores and when I try with tr all the underscores are replaced by tabs. Here's an example of the format of the file:

```<code>Arabidopsis_thaliana_TRANSCRIPT_NM1000_c5_g4_i1
Arabidopsis_thaliana_TRANSCRIPT_NM2530_c1_g1_i1
Arabidopsis_lyrata_TRANSCRIPT_NM10000_c2_g2_i2
Oriza_sativa_TRANSCRIPT_NM43000_c1_g2_i4
Oriza_sativa_TRANSCRIPT_NM31000_c2_g1_i1
</code>```

The output that I want is the following:

```<code>Arabidopsis_thaliana    TRANSCRIPT_NM1000_c5_g4_i1
Arabidopsis_thaliana    TRANSCRIPT_NM2530_c1_g1_i1
Arabidopsis_lyrata     TRANSCRIPT_NM10000_c2_g2_i2
Oriza_sativa     TRANSCRIPT_NM43000_c1_g2_i4
Oriza_sativa     TRANSCRIPT_NM31000_c2_g1_i1
</code>```

Any help will be appreciated,

Best.

答:
You can use sed. If your text is in test.txt, then try this:

```<code>$ sed -i.bak "s/_TRANSCRIPT/$(echo '\t')TRANSCRIPT/g" test.txt
</code>```

Body:
I want to replace a specific underscore from a file and replace it with a tab. The problem is that I have a lot of underscores and when I try with tr all the underscores are replaced by tabs. Here's an example of the format of the file:

Arabidopsis_thaliana_TRANSCRIPT_NM1000_c5_g4_i1
Arabidopsis_thaliana_TRANSCRIPT_NM2530_c1_g1_i1
Arabidopsis_lyrata_TRANSCRIPT_NM10000_c2_g2_i2
Oriza_sativa_TRANSCRIPT_NM43000_c1_g2_i4
Oriza_sativa_TRANSCRIPT_NM31000_c2_g1_i1

The output that I want is the following:

Arabidopsis_thaliana    TRANSCRIPT_NM1000_c5_g4_i1
Arabidopsis_thaliana    TRANSCRIPT_NM2530_c1_g1_i1
Arabidopsis_lyrata     TRANSCRIPT_NM10000_c2_g2_i2
Oriza_sativa     TRANSCRIPT_NM43000_c1_g2_i4
Oriza_sativa     TRANSCRIPT_NM31000_c2_g1_i1

Any help will be appreciated,

Best.

Body:
You can use sed. If your text is in test.txt, then try this:

$ sed -i.bak "s/_TRANSCRIPT/$(echo '\t')TRANSCRIPT/g" test.txt


问:
rails escape_javascript in .net
For rails developer please check my last paragraph.

Is there an equivalent of escape_javascript in rails for .net specifically .net mvc2?
I am going to return some JavaScript which needs to be escaped since I am getting the code from another view using RenderPartialViewToString http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/

You can see what escape_javascript does here Why escape_javascript before rendering a partial? if your not familiar with its functionality.

Rails developers:
It feels like this function should be easy to implement or port for rails so can someone explain what it does more than just escaping qoutes?

答:
ASP.NET MVC provides 9 ActionResults, one of them is the JavascriptResult.

In your Action method:

return JavaScript("javascript code");

Title: rails escape_javascript in .net


问:
EMGU QueryFrame returns "streaky" Image over RTSP
I have a HD network camera that I am trying to grab frames over rtsp and using the following code:

```<code>//in Form_Load
Application.Idle += getNextFrame;
</code>```

And the Event Handler:

```<code>private void getNextFrame(object sender, EventArgs ags)
{
        //where _imgCount is the total image Grabs
        lbl_Count.Text = _imgCount++.ToString();
        // and ibLive is a Emgu ImageBox
        ibLive.Image = capAxis.QueryFrame().Resize(640, 480, INTER.CV_INTER_AREA);
}
</code>```

When I start the program, it'll grab 20-40 frames before the "streakiness" appears at the bottom of the screen. It's always on the bottom of the image, but some times it takes up half the screen.

The stream resolution is 1920x1080 and it's using mjpeg. I tried switching to h.264 but had the same results.

I am using Emgu version x86-2.4.0.1717

Any Ideas?
Thanks.

答:
At the end of Capture  string add this "?tcp"

```<code>Capture cap = new Capture(@"rtsp://10.0.0.1/axis-media/media.amp?videocodec=h264&streamprofile=rtspstream?tcp");
</code>```

EDIT

This is my code, and yes, it works, I'am using an IP cam DAHUA.

```<code>Capture cap = Capture(@"rtsp://admin:12345@10.0.0.01:554/cam/realmonitor?channel=1&subtype=01?tcp");
</code>```

Body:
I have a HD network camera that I am trying to grab frames over rtsp and using the following code:

//in Form_Load
Application.Idle += getNextFrame;

And the Event Handler:

private void getNextFrame(object sender, EventArgs ags)
{
        //where _imgCount is the total image Grabs
        lbl_Count.Text = _imgCount++.ToString();
        // and ibLive is a Emgu ImageBox
        ibLive.Image = capAxis.QueryFrame().Resize(640, 480, INTER.CV_INTER_AREA);
}

When I start the program, it'll grab 20-40 frames before the "streakiness" appears at the bottom of the screen. It's always on the bottom of the image, but some times it takes up half the screen.

The stream resolution is 1920x1080 and it's using mjpeg. I tried switching to h.264 but had the same results.

I am using Emgu version x86-2.4.0.1717

Any Ideas?
Thanks.

Body:
At the end of Capture  string add this "?tcp"

Capture cap = new Capture(@"rtsp://10.0.0.1/axis-media/media.amp?videocodec=h264&streamprofile=rtspstream?tcp");

EDIT

This is my code, and yes, it works, I'am using an IP cam DAHUA.

Capture cap = Capture(@"rtsp://admin:12345@10.0.0.01:554/cam/realmonitor?channel=1&subtype=01?tcp");


问:
Type error when trying to execute little game code
I'm trying to code a little game here to show someone, but I'm having trouble with it. When I try a sum of two values, it just says TypeError: must be str, not int. I am newbie, so I wasn't able to find a fix.
I programmed it in another language (not another programming language, I mean I programmed it in portuguese but translated it to english so it is easier to understand).
Here you have the code:

```<code>import random
import time

print ('Welcome to the Even or Odd game!')
print ('Type the letter \'o\' if you want odd and \'e\' if you want even.')

userChoice = input('Your choice: ').lower()
time.sleep(1)
userNumber = input('Now, type in a number from 1 to 5: ')

randomNumber = random.randint(1,5)
time.sleep(2)

print ('Your number: ' + str(int(userNumber)))
time.sleep(2)
print ('Computer\'s number: ' + str(int(randomNumber)))
time.sleep(2)

result = userNumber + randomNumber
print ('Adding these two numbers together, you have ' + str(result))
if result % 2 == 0:
    if userChoice == 'e' or 'even':
        print ('You won!')
    else:
        print ('You lost!')
else:
    if userChoice == 'o' or 'odd':
        print ('You won!')
    else:
        print ('You lost!')
</code>```

I get the TypeError if I run this program. It happens when it tries to execute result = userNumber + computerNumber.
Any ideas? Thank you so much!

答:
When you take the user's input, it is being stored as a string. You're getting the error because you're trying to add a string and an integer.

You can use the int() function to turn a string to an integer. So you can do for example:

```<code>result = int(userNumber) + int(randomNumber)
</code>```

Body:
I'm trying to code a little game here to show someone, but I'm having trouble with it. When I try a sum of two values, it just says TypeError: must be str, not int. I am newbie, so I wasn't able to find a fix.
I programmed it in another language (not another programming language, I mean I programmed it in portuguese but translated it to english so it is easier to understand).
Here you have the code:

import random
import time

print ('Welcome to the Even or Odd game!')
print ('Type the letter \'o\' if you want odd and \'e\' if you want even.')

userChoice = input('Your choice: ').lower()
time.sleep(1)
userNumber = input('Now, type in a number from 1 to 5: ')

randomNumber = random.randint(1,5)
time.sleep(2)

print ('Your number: ' + str(int(userNumber)))
time.sleep(2)
print ('Computer\'s number: ' + str(int(randomNumber)))
time.sleep(2)

result = userNumber + randomNumber
print ('Adding these two numbers together, you have ' + str(result))
if result % 2 == 0:
    if userChoice == 'e' or 'even':
        print ('You won!')
    else:
        print ('You lost!')
else:
    if userChoice == 'o' or 'odd':
        print ('You won!')
    else:
        print ('You lost!')

I get the TypeError if I run this program. It happens when it tries to execute result = userNumber + computerNumber.
Any ideas? Thank you so much!

Body:
When you take the user's input, it is being stored as a string. You're getting the error because you're trying to add a string and an integer.

You can use the int() function to turn a string to an integer. So you can do for example:

result = int(userNumber) + int(randomNumber)


问:
Jackson Java generic parameter
I want to provide a DTO to use in a Jackson REST endpoint which has a generic parameter.

But I get this error when building.

```<code>[ERROR] Failed to execute goal org.bsc.maven:maven-processor-plugin:1.3.6:process (default) on project metrics-server: java.lang.UnsupportedOperationException: Unknown parameterized type: T. Available types in this context: {V=null, K=java.lang.String}. -> [Help 1]

public class ValidationRequest<T> {

    private final Map<String, T> columnValues;

    @JsonCreator
    public ValidationRequest @JsonProperty("columnValues") Map<String, T> columnValues) {

    this.columnValues = columnValues;
    }
}
</code>```

My usage looks like this:

```<code>    Map<String, Double> testColumnValue = new HashMap<>();
    testColumnValue.put("sum", 1.0);

    ValidationRequest validationRequest = new ValidationRequest(columnValues);
    user.validate(validationRequest);  // this is a REST request

Can anyone help me figure out if this is possible?

Here is the stack trace:
[ERROR] execute error
java.lang.RuntimeException: java.lang.UnsupportedOperationException: Unknown parameterized type: T. Available types in this context: {V=null, K=java.lang.String}.
    at com.sun.tools.javac.main.Main.compile(Main.java:553)
    at com.sun.tools.javac.api.JavacTaskImpl.doCall(JavacTaskImpl.java:129)
    at com.sun.tools.javac.api.JavacTaskImpl.call(JavacTaskImpl.java:138)
    at org.bsc.maven.plugin.processor.AbstractAnnotationProcessorMojo.executeWithExceptionsHandled(AbstractAnnotationProcessorMojo.java:248)
    at org.bsc.maven.plugin.processor.AbstractAnnotationProcessorMojo.execute(AbstractAnnotationProcessorMojo.java:129)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: java.lang.UnsupportedOperationException: Unknown parameterized type: T. Available types in this context: {V=null, K=java.lang.String}.
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.getDeclaredTypeForTypeVariable(AnnotationProcessor.java:711)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.visitTypeVariable(AnnotationProcessor.java:694)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.visitTypeVariable(AnnotationProcessor.java:461)
    at com.sun.tools.javac.code.Type$TypeVar.accept(Type.java:1337)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.acceptOrRecurse(AnnotationProcessor.java:566)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.visitDeclared(AnnotationProcessor.java:543)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.visitDeclared(AnnotationProcessor.java:461)
    at com.sun.tools.javac.code.Type$ClassType.accept(Type.java:944)
    at org.versly.rest.wsdoc.AnnotationProcessor.jsonTypeForDeclaredType(AnnotationProcessor.java:418)
    at org.versly.rest.wsdoc.AnnotationProcessor.access$300(AnnotationProcessor.java:63)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.recurseForJsonType(AnnotationProcessor.java:667)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.addFieldFromBeanMethod(AnnotationProcessor.java:646)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.buildTypeContents(AnnotationProcessor.java:616)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.buildType(AnnotationProcessor.java:575)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.visitDeclared(AnnotationProcessor.java:560)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.visitDeclared(AnnotationProcessor.java:461)
    at com.sun.tools.javac.code.Type$ClassType.accept(Type.java:944)
    at org.versly.rest.wsdoc.AnnotationProcessor.jsonTypeForDeclaredType(AnnotationProcessor.java:418)
    at org.versly.rest.wsdoc.AnnotationProcessor.jsonTypeFromTypeMirror(AnnotationProcessor.java:391)
    at org.versly.rest.wsdoc.AnnotationProcessor.buildRequestBody(AnnotationProcessor.java:288)
    at org.versly.rest.wsdoc.AnnotationProcessor.buildRequestBodies(AnnotationProcessor.java:284)
    at org.versly.rest.wsdoc.AnnotationProcessor.buildParameterData(AnnotationProcessor.java:254)
    at org.versly.rest.wsdoc.AnnotationProcessor.processRequestMappingMethod(AnnotationProcessor.java:233)
    at org.versly.rest.wsdoc.AnnotationProcessor.processElements(AnnotationProcessor.java:126)
    at org.versly.rest.wsdoc.AnnotationProcessor.process(AnnotationProcessor.java:87)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:794)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:705)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$1800(JavacProcessingEnvironment.java:91)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1035)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1176)
    at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1170)
    at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:856)
    at com.sun.tools.javac.main.Main.compile(Main.java:523)
    ... 26 more
</code>```

I have changed the name of the constructor in the original post, I hope this is a clearer example.

答:
Please post a Minimal, Complete, and Verifiable example with unit test that shows you made some effort. Your code makes no sense to me, due to several reasons:

Your code WILL NOT compile - You've some unknown type InfluxValidationRequest inside the class ValidationRequest which looks like a constructor but isn't.

There's a thing called type erasure, so a Map<String, Double> is just a raw Map at runtime.

Why not have different instances of the validator that knows how to validate a Double value, an Integer value, and so on? Where is the so-called validation code?

Title: Jackson Java generic parameter

Body:
I want to provide a DTO to use in a Jackson REST endpoint which has a generic parameter.

But I get this error when building.

[ERROR] Failed to execute goal org.bsc.maven:maven-processor-plugin:1.3.6:process (default) on project metrics-server: java.lang.UnsupportedOperationException: Unknown parameterized type: T. Available types in this context: {V=null, K=java.lang.String}. -> [Help 1]

public class ValidationRequest<T> {

    private final Map<String, T> columnValues;

    @JsonCreator
    public ValidationRequest @JsonProperty("columnValues") Map<String, T> columnValues) {

    this.columnValues = columnValues;
    }
}

My usage looks like this:

    Map<String, Double> testColumnValue = new HashMap<>();
    testColumnValue.put("sum", 1.0);

    ValidationRequest validationRequest = new ValidationRequest(columnValues);
    user.validate(validationRequest);  // this is a REST request

Can anyone help me figure out if this is possible?

Here is the stack trace:
[ERROR] execute error
java.lang.RuntimeException: java.lang.UnsupportedOperationException: Unknown parameterized type: T. Available types in this context: {V=null, K=java.lang.String}.
    at com.sun.tools.javac.main.Main.compile(Main.java:553)
    at com.sun.tools.javac.api.JavacTaskImpl.doCall(JavacTaskImpl.java:129)
    at com.sun.tools.javac.api.JavacTaskImpl.call(JavacTaskImpl.java:138)
    at org.bsc.maven.plugin.processor.AbstractAnnotationProcessorMojo.executeWithExceptionsHandled(AbstractAnnotationProcessorMojo.java:248)
    at org.bsc.maven.plugin.processor.AbstractAnnotationProcessorMojo.execute(AbstractAnnotationProcessorMojo.java:129)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: java.lang.UnsupportedOperationException: Unknown parameterized type: T. Available types in this context: {V=null, K=java.lang.String}.
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.getDeclaredTypeForTypeVariable(AnnotationProcessor.java:711)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.visitTypeVariable(AnnotationProcessor.java:694)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.visitTypeVariable(AnnotationProcessor.java:461)
    at com.sun.tools.javac.code.Type$TypeVar.accept(Type.java:1337)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.acceptOrRecurse(AnnotationProcessor.java:566)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.visitDeclared(AnnotationProcessor.java:543)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.visitDeclared(AnnotationProcessor.java:461)
    at com.sun.tools.javac.code.Type$ClassType.accept(Type.java:944)
    at org.versly.rest.wsdoc.AnnotationProcessor.jsonTypeForDeclaredType(AnnotationProcessor.java:418)
    at org.versly.rest.wsdoc.AnnotationProcessor.access$300(AnnotationProcessor.java:63)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.recurseForJsonType(AnnotationProcessor.java:667)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.addFieldFromBeanMethod(AnnotationProcessor.java:646)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.buildTypeContents(AnnotationProcessor.java:616)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.buildType(AnnotationProcessor.java:575)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.visitDeclared(AnnotationProcessor.java:560)
    at org.versly.rest.wsdoc.AnnotationProcessor$TypeVisitorImpl.visitDeclared(AnnotationProcessor.java:461)
    at com.sun.tools.javac.code.Type$ClassType.accept(Type.java:944)
    at org.versly.rest.wsdoc.AnnotationProcessor.jsonTypeForDeclaredType(AnnotationProcessor.java:418)
    at org.versly.rest.wsdoc.AnnotationProcessor.jsonTypeFromTypeMirror(AnnotationProcessor.java:391)
    at org.versly.rest.wsdoc.AnnotationProcessor.buildRequestBody(AnnotationProcessor.java:288)
    at org.versly.rest.wsdoc.AnnotationProcessor.buildRequestBodies(AnnotationProcessor.java:284)
    at org.versly.rest.wsdoc.AnnotationProcessor.buildParameterData(AnnotationProcessor.java:254)
    at org.versly.rest.wsdoc.AnnotationProcessor.processRequestMappingMethod(AnnotationProcessor.java:233)
    at org.versly.rest.wsdoc.AnnotationProcessor.processElements(AnnotationProcessor.java:126)
    at org.versly.rest.wsdoc.AnnotationProcessor.process(AnnotationProcessor.java:87)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:794)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:705)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$1800(JavacProcessingEnvironment.java:91)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1035)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1176)
    at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1170)
    at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:856)
    at com.sun.tools.javac.main.Main.compile(Main.java:523)
    ... 26 more

I have changed the name of the constructor in the original post, I hope this is a clearer example.