text:
Q: vector space of all smooth functions has infinite dimension Now, I am working through a particular case in the book on smooth manifolds by John.M.Lee used in my graduate math class, let's say we have a smooth manifold X which has positive dimension. He then claims that the vector space $C^\infty$ of all smooth functions from $X \rightarrow \mathbb{R} $ will have infinite dimension over $\mathbb{R}$. While I do have a fair idea of the  claim, I'm a little bit lost to show that the vector space has infinite dimension.

A: I originally posted the following as a comment but I think it is a particularly simple argument, so worth upgrading to a answer.
Choose any $\theta\in C^\infty(M)$ which is not constant on a connected component of $M$. Then its image is an infinite subset of $\mathbb{R}$ (it includes a nontrivial interval). As the space $\mathbb{R}[X]$ of real polynomials is infinite dimensional, and a polynomial is fully determined by its values on an infinite set, you can conclude that
$$
\left\{f\circ\theta\colon f\in\mathbb{R}[X]\right\}
$$
is an infinite dimensional subspace of $C^\infty(M)$.
Note that this argument is applicable much more generally. E.g., if a Riemann surface has at least one non-constant meromorphic function then the space of meromorphic functions is infinite dimensional.
If you like, you can modify this method to show that the dimension of $C^\infty(M)$ is (at least) the cardinality of the continuum, by proving the same is true for smooth functions on any nontrivial interval in $\mathbb{R}$. (Hint: the exponentials $x\mapsto e^{ax}$ are linearly independent).

A: This follows from the existence of bump functions.  Take an open set $U$ in your manifold with a chart $\phi:U\to \mathbb{R}^n$.  Let $k$ be a positive integer, and let $x_1,x_2,\ldots,x_k$ be distinct points in $\phi(U)$.  For each $j$ from $1$ to $k$, let $f_j:\mathbb{R}^n\to\mathbb{R}$ be a smooth function whose support is a compact subset of $\phi(U)$ such that $f_j(x_j)=1$ and $f_j(x_m)=0$ if $m\neq j$.  Define $g_j:X\to\mathbb{R}$ by $g_j(x)=0$ if $x$ is in $X\setminus U$, and $g_j(x)=f_j(\phi(x))$ if $x$ is in $U$.  Then $\{g_1,\ldots,g_k\}$ is a linearly independent set of smooth functions on $X$.  Since $k$ was arbitrary, the space of smooth functions is infinite dimensional.

A: I'm not sure of the details for smooth manifolds, but certainly the polynomials have infinite dimension and are contained in $C^\infty$.


text:
Q: RESTEasy with Guice InstantiationError at deployment (App Engine local) I am trying to get Guice to work with RESTEasy by following the instructions here: https://docs.jboss.org/resteasy/docs/3.0.21.Final/userguide/html/Guice1.html
However, there is an error InstantiationError on org.jboss.resteasy.spi.ResteasyDeployment during deployment on App Engine (local deployment):
2019-11-12 21:01:15.419:WARN:oejw.WebAppContext:main: Failed startup of context c.g.a.t.d.j.DevAppEngineWebAppContext@557a1e2d{APP,/,file:///PATH/target/APP-1.0-SNAPSHOT/,UNAVAILABLE}{PATH\target\APP-1.0-SNAPSHOT}
java.lang.InstantiationError: org.jboss.resteasy.spi.ResteasyDeployment
    at org.jboss.resteasy.plugins.server.servlet.ConfigurationBootstrap.<init>(ConfigurationBootstrap.java:21)
    at org.jboss.resteasy.plugins.server.servlet.ListenerBootstrap.<init>(ListenerBootstrap.java:25)
    at org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap.contextInitialized(ResteasyBootstrap.java:23)
    at org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener.contextInitialized(GuiceResteasyBootstrapServletContextListener.java:37)
    at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:957)
    at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:553)
    at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:922)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:365)
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1497)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1459)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:852)
    at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:278)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:545)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:167)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:110)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:167)
    at org.eclipse.jetty.server.Server.start(Server.java:418)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:110)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
    at org.eclipse.jetty.server.Server.doStart(Server.java:382)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at com.google.appengine.tools.development.jetty9.JettyContainerService.startContainer(JettyContainerService.java:343)
    at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:283)
    at com.google.appengine.tools.development.AutomaticInstanceHolder.startUp(AutomaticInstanceHolder.java:26)
    at com.google.appengine.tools.development.AbstractModule.startup(AbstractModule.java:87)
    at com.google.appengine.tools.development.Modules.startup(Modules.java:105)
    at com.google.appengine.tools.development.DevAppServerImpl.doStart(DevAppServerImpl.java:282)
    at com.google.appengine.tools.development.DevAppServerImpl.access$000(DevAppServerImpl.java:47)
    at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:223)
    at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:221)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:221)
    at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:404)
    at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:45)
    at com.google.appengine.tools.development.DevAppServerMain.run(DevAppServerMain.java:257)
    at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:248)

I reversed my changes and found that merely adding the following dependency in my pom.xml causes the deployment error.
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-guice</artifactId>
        <version>4.4.0.Final</version>
    </dependency>

If I remove it, the deployment has no errors. Any idea why this happens? The other RESTEasy- and Guice-related dependencies are declared:
    <!--RESTEasy Dependencies-->
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxrs</artifactId>
        <version>3.9.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <version>3.9.0.Final</version>
    </dependency>

    <!-- Guice -->
    <dependency>
        <groupId>com.google.inject</groupId>
        <artifactId>guice</artifactId>
        <version>4.2.2</version>
    </dependency>
    <dependency>
        <groupId>com.google.inject.extensions</groupId>
        <artifactId>guice-servlet</artifactId>
        <version>4.2.2</version>
    </dependency>

A: Got past the error by setting resteasy-guice dependency version to 3.9.0.Final as well

redpajama_set_name: RedPajamaStackExchange


text:
Q: Json deserialize string with 2 arrays I have to Serialize a string with two list collections as JSON string.
 public class Product {
   public string  Name {get;set;}
 };

 public class Product2 {
   public string Age { get; set; }
 };

 private void Form1_Load(object sender, EventArgs e) {
   List<Product> mitems = new List<Product>();
   List<Product2> mitems2 = new List<Product2>();
   mitems.Add(new Product { Name = "John" });
   mitems2.Add(new Product2 {Age = "28" } );
   var objects = new { mitems, mitems2 };

   string json = JsonConvert.SerializeObject(objects);
   var Items = JsonConvert.DeserializeObject<List<Product>>(json);
 }

In the last line, I am getting an exception Cannot deserialize the current JSON object

A: Instead of an anonymous object probably you would want to create a model to hold this like
public class MyModel
{
  public List<Product> products { get; set; }
  public List<Product2> products2 { get; set; }
}

In Form_Load
MyModel model = new MyModel
{
  Products = mitems,
  Products2 = mitems2,
}

var Items = JsonConvert.DeserializeObject<MyModel>(json);

per your comment, if you want to iterate through Products then
foreach(var data in Item.products)
{
  MessageBox.Show(data.Name);
}

A: You can't deserialise objects to a List<Product> because it isn't a List<Product> it's a new anonymous type with two properties
Change
 var objects = new { mitems, mitems2 };

To
 var objects = new List<Product>(mitems);
 objects.AddRange(mitems2);

Also Product2 is not a product
You also need to change
 public class Product2

To
 public class Product2 : Product

in order to add it to a list of Product

A: You have several options, one is you can deserialize as dynamic or you can define a root object for your final json.
var Items = JsonConvert.DeserializeObject<dynamic>(json);

and casting to your object lists:
List<Product> products = new List<Product>();
List<Product2> products2 = new List<Product2>();

foreach (var item in Items.mitems)
{
    Console.WriteLine(item.Name);
    products.Add(((JObject)item).ToObject<Product>());
}

foreach (var item2 in Items.mitems2)
{
    Console.WriteLine(item2.Age);
    products2.Add(((JObject)item2).ToObject<Product2>());
}

output :
John
28

or
class RootObj
{
    public List<Product> mitems { get; set; }
    public List<Product2> mitems2 { get; set; }
}

var Items = JsonConvert.DeserializeObject<RootObj>(json);

foreach (var item in Items.mitems)
{
    Console.WriteLine(item.Name);
}

foreach (var item2 in Items.mitems2)
{
    Console.WriteLine(item2.Age);
}

output:
John
28

Outputs for both deserialization methods:

A: you can also do this:
using Newtonsoft.Json.Linq;

var item = JsonConvert.DeserializeObject<IDictionary<string, object>>(json)["mitems"];
Console.WriteLine(((JArray)item).ToObject<IList<Product>>());

Edit: I rephrased my answer
Fiddler Example : https://dotnetfiddle.net/ItMClb


text:
Q: Xubuntu - command/shortcut to hide all notifications Is there a command/shortcut avaiable to hide all popped-up notifications? Some of my scripts produce notifications which dont auto-hide, you have to click them.
I'd like to have a keyboard shortcut instead of having to click each and every one.

A: There is no such shortcut. Even then, the notification interface does not expose a DBus call to revoke all open notifications.
However, you can speedily dispose all by killing the notification process:
Quick and dirty:
Assign the shortcut of your liking to:
pkill xfce4-notifyd

Sophisticated and nerdy:
Ask it to terminate gracefully:

dbus-send --session --type=method_call --dest=org.freedesktop.Notifications \
                   /org/freedesktop/Notifications \
                   org.xfce.Notifyd.Quit

Or maybe put the above in your scripts.
Note: Ending the xfce4-notifyd process is not an issue because the next invocation of a notification will start the process. It will even self-terminate when there is nothing to display for some time.


text:
Q: Remove string from a string jquery I am trying to replace within a string using jquery
var myString ="qwerty"

var avoid ="t"

I want to do someting like
myString.replace(avoid,'');

I was able to remove like myString.replace('t',''); But i want it to be like myString.replace(avoid,'');
How to do it?
JsFiddle : http://jsfiddle.net/nKSZT/

A: replace does not modify the string, it returns a modified string. So do:
 var avoided = myString.replace(avoid,'');

Fiddle:
http://jsfiddle.net/MBjy3/1/

A: Try this
 var myString = "qwerty";
 alert(myString);
 var avoid = "t";
 var abc=myString.replace(avoid, '');
 alert(abc);

Demo

A: var str = "send_more_id4";
alert(str);
var res = str.replace("send_more_id", "");
alert(res);

A: Your problem is that replace does not replace the characters in your original string but returns a new string with the replacement.
myString = myString.replace(avoid,'');

A: Also, there is another approach:
var myString ="qwerty",
    avoid = "t";

var result = myString.split(avoid).join('');

console.log(result);


text:
Q: Appendix with own toc I want to have two table of contents in my document. The first (main) shall only contains "Appendix A: ...", "Appendix B: ..." and so on with page numbers.
In the appendix I want another table of contents which tells me, what sections are available and on which page.
I have searched in the internet, but I couldn't find any thing matching.
I think I am not the first person trying that with LaTeX.
What is the best way to start?
EDIT:
I used now the solution from lockstep with the additional \phantomsection (Link).
Now I am searching for

... a possibility to put Heading on Level 1 under Appendix?

I think there must be a separation between the toc and the bookmarks.

A: You can work with bookmarksdepth
\documentclass[toc=flat,numbers=noenddot]{scrartcl}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage{hyperref}
\makeatletter
\newcommand*{\maintoc}{%
  \begingroup
    \@fileswfalse
    \renewcommand*{\appendixattoc}{%
      \value{tocdepth}=-10000%
    }%
    \tableofcontents%
  \endgroup
}
\newcommand*{\appendixtoc}{
  \begingroup
    \edef\@alltocdepth{\the\value{tocdepth}}%
    \setcounter{tocdepth}{-10000}%
    \renewcommand*{\contentsname}{%
      List of Appendices}%
    \renewcommand*{\appendixattoc}{%
      \setcounter{tocdepth}{\@alltocdepth}%
    }%
    \tableofcontents%
    \setcounter{tocdepth}{\@alltocdepth}%
  \endgroup
}
\newcommand*{\appendixattoc}{}%
\g@addto@macro\appendix{%
  \clearpage%
  \phantomsection%
  \addcontentsline{toc}{section}{\appendixname}%
  \addtocontents{toc}{\protect\appendixattoc}%
  \renewcommand*{\thesection}{Appendix~\Alph{section}}%
}
\makeatother

\begin{document}

\maintoc
\blinddocument

\hypersetup{bookmarksdepth=-1}
\appendix
\pdfbookmark[-1]{Appendix}{appendixentry}
\appendixtoc
\hypersetup{bookmarksdepth=4}
\blinddocument
\end{document}

EDIT:
You can also modify the interna of the level -- here I changed them in the following way:
\g@addto@macro\appendix{%
  \clearpage%
  \phantomsection%
  \addcontentsline{toc}{section}{\appendixname}%
  \addtocontents{toc}{\protect\appendixattoc}%
  \renewcommand*{\thesection}{Appendix~\Alph{section}}%
  \def\toclevel@chapter{1}%0
  \def\toclevel@section{2}%1
  \def\toclevel@subsection{3}%2
  \def\toclevel@subsubsection{4}%
  \def\toclevel@paragraph{5}%
  \def\toclevel@subparagraph{6}%
  \def\toclevel@figure{7}%
  \def\toclevel@table{8}%
}

The result is the same:
\documentclass[toc=flat,numbers=noenddot]{scrartcl}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage{hyperref}
\usepackage{bookmark}
\makeatletter
\newcommand*{\maintoc}{%
  \begingroup
    \@fileswfalse
    \renewcommand*{\appendixattoc}{%
      \value{tocdepth}=-10000%
    }%
    \tableofcontents%
  \endgroup
}
\newcommand*{\appendixtoc}{
  \begingroup
    \edef\@alltocdepth{\the\value{tocdepth}}%
    \setcounter{tocdepth}{-10000}%
    \renewcommand*{\contentsname}{%
      List of Appendices}%
    \renewcommand*{\appendixattoc}{%
      \setcounter{tocdepth}{\@alltocdepth}%
    }%
    \tableofcontents%
    \setcounter{tocdepth}{\@alltocdepth}%
  \endgroup
}
\newcommand*{\appendixattoc}{}%
\g@addto@macro\appendix{%
  \clearpage%
  \phantomsection%
  \addcontentsline{toc}{section}{\appendixname}%
  \addtocontents{toc}{\protect\appendixattoc}%
  \renewcommand*{\thesection}{Appendix~\Alph{section}}%
  \def\toclevel@chapter{1}
  \def\toclevel@section{2}
  \def\toclevel@subsection{3}
  \def\toclevel@subsubsection{4}
  \def\toclevel@paragraph{5}
  \def\toclevel@subparagraph{6}
  \def\toclevel@figure{7}
  \def\toclevel@table{8}
}
\makeatother

\begin{document}

\maintoc
\blinddocument

\appendix
\appendixtoc

\blinddocument
\end{document}

EDIT: Changed the order of \appendix and \pdfbookmark

A: Here's an option using the titletoc package (to build the partial ToCs), the tocvsec2 package (to control the tocdepth for the main Table of Contents), and the appendix package (to modify the way appendices appear in the main ToC):
\documentclass{scrbook}
\usepackage{titletoc}
\usepackage{tocvsec2}
\usepackage[title,titletoc]{appendix}
\usepackage{hyperref}

\begin{document}

\hypersetup{bookmarksdepth=4}
\tableofcontents
\chapter{First regular chapter}
\section{Section one one}
\subsection{Subsection one one one}
\chapter{Second regular chapter}
\section{Section two one}
\subsection{Subsection two one one}

\begin{appendices}
\settocdepth{chapter}
\addtocontents{ptc}{\setcounter{tocdepth}{3}}
\chapter{First Appendix}
\startcontents[sections]
\printcontents[sections]{}{1}{}
\section{First section in appendix one}
\subsection{First subsection in appendix one one}
\subsubsection{First subsubsection in appendix one one one}
\section{Second section in appendix one}
\subsection{First subsection in appendix one two}
\stopcontents[sections]
\chapter{Second Appendix}
\startcontents[sections]
\printcontents[sections]{}{1}{}
\section{First section in appendix two}
\section{Second section in appendix two}
\stopcontents[sections]
\end{appendices}

\end{document}


text:
Q: Why was my question closed as off-topic without any comment feedback?
Possible Duplicate:
Should a user have to add a comment when they vote to close

So, I had a question, and it was closed by five people as "off-topic". Now, I still think it's on-topic, but some people seem to disagree. However, the question was closed without providing any kind of feedback on how to improve the question, and that I have a problem with.
Wouldn't it be better if it was required to put a comment when voting a question to be closed? Especially off-topic is in my opinion very vague, and pointing how to make the question on-topic, or a place where the question is on-topic can motivate users (especially newbies as myself) to ask better questions.
I know there are several other questions similar to this one, but they all end up as a discussion on why the poster's specific question was closed, and end up being subsequently closed. This time I would like to ask, in general, whether or not it would be best to require a comment, even a small one when voting to close a question. The newbies will appreciate it.

A:
So, I had a question, and it was closed by five people as "off-topic". Now, I still think it's on-topic, but some people seem to disagree.

Let's play my favorite favorite game: Ask the FAQ:

*

*a specific programming problem -> Nope

*a software algorithm -> Not really

*software tools commonly used by programmers -> No

*practical, answerable problems that are unique to the programming profession -> Uhh...well, no
That's 0 out of 4. I did not award a half point for the first point because you actually don't ask about anything programming related at all, but only about generic information on the topic. I also did not award a point for the last point because it is hardly answerable...and there is no real question there.

However, the question was closed without providing any kind of feedback on how to improve the question, and that I have a problem with.
Wouldn't it be better if it was required to put a comment when voting a question to be closed? Especially off-topic is in my opinion very vague, and pointing how to make the question on-topic, or a place where the question is on-topic can motivate users (especially newbies as myself) to ask better questions.

I know there are several other questions similar to this one, but they all end up as a discussion on why the poster's specific question was closed, and end up being subsequently closed.

Yes.

This time I would like to ask, in general, whether or not it would be best to require a comment, even a small one when voting to close a question. The newbies will appreciate it.

Then you failed at representing your question accordingly. We had a lot of discussions about forced comments here, and the consensus is as following:

Forced comments are leading to one of the following behaviors:

*

*Appropriate and useful comments are left.

*Bulk/Generic comments (spawned from templates, f.e. via a userscript) are left.

*Nonsense comments are given, which are subsequently deleted.

*People stop moderating (closing, downvoting etc.)

From all these possibilities, the last one is the most likely one. For everyone who hasn't been around SE for a longer period of time: SE does not work without users which are moderating questions.


text:
Q: The clock in rostest does not appear to be running in simple test I have built a very simple test, something like:
#include <ros/node_handle.h>
#include <gtest/gtest.h>

struct SimpleTicker {

    SimpleTicker(ros::NodeHandle &nh) : _nh(nh) {
       _stateTickTimer = _nh.createTimer(ros::Duration(0.25f),
      &SimpleTicker::incrementVal, this, false, true);
    }

    void incrementVal(const ros::TimerEvent&) {
        val++;
    }

    int val = 0;
    ros::Timer _stateTickTimer;
    ros::NodeHandle _nh;

};

TEST(SlamManagerTest, run_simple_tick) {
    ros::NodeHandle nh(~);
    SimpleTicker s(nh);
    ros::Duration{1}.sleep();
    ASSERT_GT(s.val, 0);
}

int main(int argc, char **argv)
{
    testing::InitGoogleTest(&argc, argv);
    ros::init(argc, argv, "simple_timer_test");
    ros::NodeHandle nh;
    if (ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME,
                                       ros::console::levels::Debug))
    {
        ros::console::notifyLoggerLevelsChanged(); // show debug output in tests
    }
    return RUN_ALL_TESTS();
}

This extremely simple test, starts a class with a timer that should call back to increment a value every 0.25 seconds. I launch this with the test file:
<launch>
  <test test-name="simple_timer_test" pkg="manager" type="simple_timer_test">
  </test>
</launch>

Launched simply with
rostest src/manager/test/simple_timer.test

But the test fails and the value is never incremented. I suspect something is wrong with how I setup rostest to use the clock. Any ideas about this?

A: So it looks like the system is not spinning. I guess because of this specific way of running rostest the node, never calls to ros::spin() because it is busy running the tests. So wherever a sleep needs to occur, we need to spin instead, something like this:
template <typename F>
void spin_sleep(ros::Duration duration, F break_condition) {
    auto end = ros::Time::now() + duration;
    while (end > ros::Time::now() && !break_condition()) {
        ros::spinOnce();
    }
}

void spin_sleep(ros::Duration duration) {
    spin_sleep(duration, []() { return false;});
}

Then instead of sleeping do something like this:
ros::NodeHandle nh(~);
SimpleTicker s(nh);
spin_sleep(ros::Duration{1});
ASSERT_GT(s.val, 0);


text:
Q: Constructive treatment of Jacobson rings Which result is closest to the classical
General Hilbert's Nullstellensatz: Finite type algebras over Jacobson rings are Jacobson.
and constructively true at the same time? And where can I find a proof of it?
I skimmed through the books by Lombardi/Quitté and Mines/Richman/Ruitenberg but there seems to be no discussion of Jacobson ring-related methods.
The usual definition of Jacobson rings relies heavily on prime ideals so perhaps one should find a suitable constructive version of the definition of a Jacobson ring first. I'm curious for your ideas.


text:
Q: Add an application to windows startup visual forum applcation I have a problem. I want to add an application to windows startup. I am making visual express 2010 forum application.
I want to add an application in the path "C:\app\trial.exe" to my windows startup.
    const char path[]="C:\\app\\trial.exe";
    HKEY hkey;
    long regOpenResult;

    regOpenResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,(LPCWSTR)"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0L,KEY_WRITE, &hkey);

         if (ERROR_SUCCESS == regOpenResult){
         RegSetValueEx(hkey,(LPCWSTR)"startup sample",0,REG_SZ,(BYTE*) path, strlen(path));
             if( ERROR_SUCCESS == regOpenResult )

                MessageBox::Show("successfully added to start up");
             else
                MessageBox::Show("1. Failed to set at startup");
             }
         else
            MessageBox::Show("2. Failed to set at startup");
         RegCloseKey(hkey);

I used the following code by adding 'Windows.h' and 'advapi32.lib'.
But i always shows the message    "2. Failed to set at startup"
What is the wrong with this code.
Can i use any other form of code in forum application.
Thanks in advance.


text:
Q: Reverse an array containing random numbers. How? My assignment is to create an array with random numbers and then reverse the order in C#.
I managed to generate the random array, but how do i reverse it?
For example the output should look like this
15334
43351
int[] TalArray = new int[5];
var arr = new int[TalArray.Length];
for (int i = 0; i < TalArray.Length; i++)

{
    Random random = new Random();
    int num = random.Next(TalArray.Length);

    Console.WriteLine(num);
}

Thanks in advance! :)

A: Here is a solution with Array.Reverse:
var arr = new int[5];
for (int i = 0; i < arr.Length; i++)
  {
     arr[i] = new Random().Next(0, arr.Length);
  }
var revArr = arr.Reverse();
Console.WriteLine(String.Join("", arr ) + string.Join("", revArr));

A: Have you tried
Documentation
public static void Main()
    {
        int[] TalArray = new int[5];
        var arr = new int[TalArray.Length];
        for (int i = 0; i < TalArray.Length; i++)
        {
            Random random = new Random();
            int num = random.Next(TalArray.Length);
            arr[i] = num;
            Console.WriteLine(num);
        }

        Array.Reverse(arr);
        for (int i = 0; i < arr.Length; i++)
        {
            Console.WriteLine(arr[i]);
        }
    }

Working example dotnet fiddle


text:
Q: What's the relationship between the regularization parameter lambda and the constrain parameter K In regularized regression, for example the ridge regression, we have the Lagrange method, which adds lambda times the 2-norm of parameters to the loss function and minimizes this. On the other hand, this is equivalent to minimizing the loss function subject to the constraint that the 2-norm of the parameters is less than K.
My question is, is there a explicit formula between lambda and K?

A: Let $x^{\ast}$ be the solution of minimizing $f(x)+\lambda R(x)$, where $R(x)$ is the regularization term and $\lambda > 0$.
Now consider the minimization problem, where you want to minimize $f(x)$ given $R(x)\le k$ with $k > 0$. Set $k=k^{\ast}:=R(x^{\ast})$. Let $x^{\prime}$ be the solution of this particular minimization problem. This means of course that $f(x^{\prime})\le f(x^{\ast})$, and also that it holds $R(x^{\prime})\le k^{\ast}=R(x^{\ast})$ or equivalently $\lambda R(x^{\prime})\le \lambda R(x^{\ast})$.
But if one of the two inequalities $f(x^{\prime})\le f(x^{\ast})$ and $\lambda R(x^{\prime}) \le \lambda R(x^{\ast})$ where strict, than this would be a contradiction to $x^{\ast}$ being a minimizer of $f(x)+\lambda R(x)$. Thus, $f(x^{\prime}) = f(x^{\ast})$ and $x^{\ast}$ is also a solution for the second minimization problem, and $x^{\prime}$ is also a solution for the first minimization problem.
This shows, that solving the minimization problem of the first kind solves also a particular minimization problem of the second kind, and vice versa.
The relationship is $k=R(x^{\ast})$.


text:
Q: Massive number of "SET autocommit=0/1" queries in MySQL I'm running some load tests on our system and I notice a massive number of "SET autocommit=0" and "SET autocommit=1" queries being executed. Something around 25,000 within 1 minute. I'm trying to figure out what is causing this and how to get rid of it.
We use the following technologies:

*

*MySQL

*Hibernate

*Hikari

*Spring

*Tomcat
I have tried the following but it did not seem to help:

*

*"SET autocommit = 0" in MySQL

*Added the elideSetAutoCommits property in the db connection URL. "jdbc:mysql://localhost/db_name?useUniCode=true&characterEncoding=UTF-8&pinGlobalTxToPhysicalConnection=true&elideSetAutoCommits=true"
Could someone point me towards what might be causing these queries?

A:
Could someone point me towards what might be causing these queries?

Your queries are the consequence of Connection#setAutoCommit(boolean) which is used to switch from the default mode that is auto-commit mode to transactional mode in order to insert/update/delete/read data within a transaction.
The common code is :
// Switch to transactional mode which actually triggers a SET autocommit = 0
con.setAutoCommit(false);
try {
    // Some operations on the db
    con.commit();
} finally {
    // Switch back to auto-commit mode which actually triggers a SET autocommit = 1
    con.setAutoCommit(true);
}

Here is a good link that explains how transactions work in JDBC.

If you know that your pool of connections will always be used to get connections in transactional mode, you can set the default mode in the configuration of Hikari thanks to the parameter autoCommit to set to false this way the connections will be already in transactional mode such that it won't be needed anymore to modify the mode.

This property controls the default auto-commit behavior of connections
  returned from the pool. It is a boolean value. Default: true

More details about the configuration of Hikari here.


text:
Q: Watching a QImage during single-stepping I'm debugging a huge Qt app with hundreds of classes, messy code, etc.  While tracking down a bug, I want to single-step in gdb (kdbg, ddd, whatever) while watching what gets drawn into a QImage using a QPainter that's carried about from method to method.  Somewhere, it's doing being given bad information.  Normally all I can get is the final QImage written to a .png file.
Is there some way to see what the image is in a QImage when stopped in a debugger?
BTW, this is using Qt4.3, which is kinda old but we're stuck with for now.  If a newer Qt offers some advantage, I have ways to hack with it (as well as others seeing this question may have the latest).

A: That's one of the examples in the Peek and Poke, Vol. 3 article on Qt Labs blog.


text:
Q: Google removed cross compilers for Android Kernel. Where are they now? I've used UBERTC prebuilt cross compilers so far, but I get errors when compiling an android kernel, and they haven't updated their stuff since 2016, so I just would like to find an alternative.
Google should have them, obviosly. But I'm unable to find them. They should be here, but the repo is empty and the last commit says:

Remove aarch64-linux-android gcc-4.9 libs and includes
Android has moved to LLVM.
The bins were already removed. Remove everything else except for OWNERS.

So, I suppose they've moved them elsewhere. But where?
I wouldn't like to hear that you need to compile the whole AOSP tree to get to the compilers. I really hope there is another way.

A: I've found the old toolchain. The funny thing is: the latest commit before the repository was cleaned out does not contain gcc for some reason. So I had to "climb" up the git tree to find one which contains it. Here is 32-bit ARM toochain and 64-bit ARM toolchan. It's gcc 4.9 from back in 2019.
What they meant by

Android has moved to LLVM.

is that you should be able to cross-compile kernels with clang and llvm and should not use their stand-alone solution anymore. But they didn't provide any info on how to do it. So yeah, nice job.
Downloading looks like this:
# clone the repo, it will be empty
git clone https://android.googlesource.com/platform/prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.9 toolchain
# go to the repo folder
cd toolchain
# use the hash of the commit to restore the commit which actually contains the toolchain
git checkout e9b2ab0932573a0ca90cad11ab75d9619f19c458

There are also alternative toolchains for those like myself, who haven't wrapped their heads around llvm and clang just yet. Here is one from arm.com based on gcc 11.2. There are also Linaro ones.
Anyways, you should sometimes use the old toolchains to build older kernels, since new compilers tend to throw more warnings, which are treated by Makefile as errors by default. For example, I'm not able to compile my kernel with the arm.com ones, because they are too smart and spot too many warnings, which I haven't found a way to disable. Modifying the Makefile doesn't seem like a valid option, as it's ~2k lines long.
If someone knows, how to disable those, I'd really love to know that too. But for now I'm gonna try to stick with the google toolchain for the older kernels.
GLHF, lol.


text:
Q: How to declare a c++ function that returns std::list or takes std::list as a parameter type? I've been trying to make a function in c++ that takes a list, performs some operation on it, and returns it. but the function won't accept std::list as a valid return type or as a parameter type.
#include <iostream>
#include <list>

std::list list_function(int n, std::list progress) {

}

int main() {
    /* std::list<int> test_list = {1, 2, 3, 4, 4854};

    test_list.push_back(10); // some unrelated testing

    for (int x : test_list) {
        std::cout << x << '\n';
    } */
}

I can't find any answers online, what do I need to do?

A: std::list is a template library, so you need a template argument to use that as a type.
For example:
#include <list>

std::list<int> list_function(int n, std::list<int> progress) {
    return std::list<int>();
}

int main(void) {
    std::list<int> a = list_function(10, std::list<int>());
    return 0;
}

If you want to create a generic function, you can also make your function templated like this:
#include <list>

template<typename T>
std::list<T> list_function(int n, std::list<T> progress) {
    return std::list<T>();
}

int main(void) {
    std::list<int> a = list_function(10, std::list<int>());
    std::list<double> b = list_function(10, std::list<double>());
    return 0;
}

A: either template it,
template <typename T>
std::list<T> list_function(int n, std::list<T> progress) {
    // ...
}

or provide fixed type
std::list<int> list_function(int n, std::list<int> progress) {
    // ...
}


text:
Q: Where is the GNOME Extensions error log? I have installed gnome-shell-extension-move-clock on 18.04 and it does not work.  In gnome-tweaks it displays a warning icon with the title "Error loading extension".
Where can I find more details about the exact error?  Is there a log file for the GNOME Extensions?


text:
Q: How do you open Chrome extension options page from a web page? My Chrome extension has a content script that uses the following to inject HTML into the page:
var optionsUrl = chrome.extension.getURL("src/options/options.html");
var content = 'Options';

This produces:
 Options

When I click the link, it opens a new browser tab and nothing more.
If I paste the href attribute chrome-extension://gdocgfhmbfbbbmhnhmmejncjdcbjkhfc/src/options/options.html into the address bar, I see the options page for my Chrome extension displayed correctly.

*

*Why doesn't the link work?

*Is there some extra permission that I'm missing?

A: In the manifest file insert:
"web_accessible_resources": ["src/options/options.html"],

more info see documentation.

A: Updating for Manifest v3. The following worked for me:
  "web_accessible_resources": [
    {
      "resources": [ "options.html" ],
      "matches": ["<all_urls>"]
    }
  ]

Further. I trigger the options page in a content script via:
  `chrome-extension://${chrome.runtime.id}/options.html`


text:
Q: Regex pattern for getting part of a string Hi I have strings like:
** Dealing Flop ** [ As, 4s, 8h ]
** Dealing Turn ** [ 4h ]
** Dealing River ** [ 3s ]

I need know is it flop turn or river and what cards has been dealt.
for now I have
new Regex(@"^\*\* Dealing (?<flop>F)|(?<turn>T)|(?<river>R)");

and what i need should be something like
new Regex(@"^\*\* Dealing (?<flop>F)|(?<turn>T)|(?<river>R)*[(?<cards>)]$");

but it does not work.
Please help.Thank you.

A: Surely this would be a lot more readable by using .Contains()?
enum Situation {
 Flop,
 Turn,
 River
}

Situation GetSituation(string input){
 if(input.Contains("Flop"){ return Situation.Flop;}
 if(input.Contains("Turn"){ return Situation.Turn;}
 if(input.Contains("River"){ return Situation.River;}
 throw new ArgumentException("Invalid situation");
}

You can get the played hands like this:
var start = myString.IndexOf("[");
var end = myString.IndexOf("]");
var hands = myString.SubString(start, (end - start)).Split(",");

A: If you want check if in the string there is Dealing Flop/River or Turn you can use this regex
(.*Dealing Flop| Dealing Turn| Dealing River.*)

And then you can extract from string all data that you need.
But sincerely I prefer @JeroenVannevel method because it's more clear and simply to understand

A: You can use this pattern to know the situation and the cards:
\b(?<ftr>Flop|Turn|River) \*\* \[ (?<c1>[^], ]+)(?>, (?<c2>[^], ]+))?(?>, (?<c3>[^] ]+))? ]


text:
Q: camel + netty: send only if remote server is available <route>
        <from uri="file://inbox?move=.txt"/>
        <to uri="netty:tcp://localhost:5150?encoders=#encoders&sync=false"/>
 </route>

I need to send files to a remote legacy tcp server via a socket (IP  and port ). this server is sometimes unavailable   so :
1- I need to check if the remote tcp server(socket ) is  available.
2- if not , i need wait 5 minutes.
I tried several options but none is working.
thanks

A: I made it worked with the following config :
        <route id="step1" trace="false">
        <from uri="file:/dev/tmp/datain/?sortBy=file:name;&delete=true&maxMessagesPerPoll=1" />
        <convertBodyTo type="java.lang.String" />
    <to uri="direct-vm:toTcp?block=true&timeout=10000" />
    </route>

    <route id="step2" trace="false">
    <from uri="direct-vm:toTcp?block=true&timeout=10000" />
    <to uri="netty4:tcp://localhost:7000?sync=true&textline=true&requestTimeout=50000&synchronous=true" />
    </route>


text:
Q: Inflating only a specific action bar menu I have an action bar menu defined in my main activity. Now, one of the fragments I am using in that activity has its own action bar menu but when I click on the menu option, I get both the fragment's as well as the activity's menu items. How to ensure that only that fragment's menu item is displayed?
My java code for that fragment is:
public class ProfileD extends Fragment {

TextView tv_named, tv_genderd, tv_cfd, tv_aged, tv_biod, tv_statusd;
ImageView imageView_dp;

public ProfileD() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_profile_d, container, false);

    tv_named = (TextView)rootView.findViewById(R.id.tv_named);
    tv_genderd = (TextView)rootView.findViewById(R.id.tv_genderd);
    tv_cfd= (TextView)rootView.findViewById(R.id.tv_cfd);
    tv_aged = (TextView)rootView.findViewById(R.id.tv_aged);
    tv_biod = (TextView)rootView.findViewById(R.id.tv_biod);

    tv_statusd = (TextView) rootView.findViewById(R.id.tv_statusd);

    imageView_dp = (ImageView)rootView.findViewById(R.id.imageView_dp);
    setHasOptionsMenu(true);

    return rootView;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu, inflater);

    getActivity().getMenuInflater().inflate(R.menu.profile_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.edit_profile) {

        Intent intent = new Intent(getContext(),PersonalDetails.class);
        intent.putExtra("Edit",1);
        startActivity(intent);

        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onResume() {
    super.onResume();

    AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
    ActionBar actionBar = appCompatActivity.getSupportActionBar();
    actionBar.setTitle("Profile");
}
}

The xml file for the menu is:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/edit_profile"
    android:orderInCategory="100"
    android:title="Edit"
    app:showAsAction="never" />

</menu>

A: I found a solution to my problem. I am posting it here so if anyone else is facing the same issue, they can benefit from this:
I created a static menu object and stored the activity's action bar menu in that object. I then called that object from my fragment and cleared it thereby clearing the activity's menu and leaving me with the fragment's menu
Here is the updated java code for the fragment
public class ProfileD extends Fragment {

TextView tv_named, tv_genderd, tv_cfd, tv_aged, tv_biod, tv_statusd;
ImageView imageView_dp;

public ProfileD() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_profile_d, container, false);

    tv_named = (TextView)rootView.findViewById(R.id.tv_named);
    tv_genderd = (TextView)rootView.findViewById(R.id.tv_genderd);
    tv_cfd= (TextView)rootView.findViewById(R.id.tv_cfd);
    tv_aged = (TextView)rootView.findViewById(R.id.tv_aged);
    tv_biod = (TextView)rootView.findViewById(R.id.tv_biod);

    tv_statusd = (TextView) rootView.findViewById(R.id.tv_statusd);

    imageView_dp = (ImageView)rootView.findViewById(R.id.imageView_dp);
    setHasOptionsMenu(true);

    return rootView;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu, inflater);

    HomePage.menu_home.clear();

    getActivity().getMenuInflater().inflate(R.menu.profile_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.edit_profile) {

        Intent intent = new Intent(getContext(),PersonalDetails.class);
        intent.putExtra("Edit",1);
        startActivity(intent);

        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onResume() {
    super.onResume();

    AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
    ActionBar actionBar = appCompatActivity.getSupportActionBar();
    actionBar.setTitle("Profile");
}
}


text:
Q: Efficient try / catch block usage? Should catch blocks be used for writing logic i.e. handle flow control etc? Or just for throwing exceptions? Does it effect efficiency or maintainability of code?
What are the side effects (if there are any) of writing logic in catch block?
EDIT:
I have seen a Java SDK class in which they have written logic inside the catch block. For example (snippet taken from java.lang.Integer class):
        try {
            result = Integer.valueOf(nm.substring(index), radix);
            result = negative ? new Integer(-result.intValue()) : result;
        } catch (NumberFormatException e) {
            String constant = negative ? new String("-" + nm.substring(index))
                                       : nm.substring(index);
            result = Integer.valueOf(constant, radix);
        }

EDIT2:
I was going through a tutorial where they count it as an advantage of writing logic of exceptional cases inside the exceptions:

Exceptions enable you to write the main flow of your code and to deal
  with the exceptional cases elsewhere.

Any specific guidelines when to write logic in catch block and when not to?

A: This is something that tends to be dependent on language and paradigm.
Most of my work is done in Java (and sometimes C++). The tendency is to use exceptions for exceptional conditions only. There are some questions on Stack Overflow about the performance overhead of exceptions in Java, and as you can see, it's not exactly negligible. There are also other concerns, such as the readability and maintainability of the code. When used properly, exceptions can delegate error handling to the appropriate components.
However, in Python, the idea that it is easier to ask forgiveness than permission reigns. In the Python community, this is known as EAFP, which is contrasted with the "look before you leap" (LBYL) approach in C-style languages.

A: That is not the best way of thinking about try/catch blocks.  The way to think about try/catch blocks is this: a failure has happened, where is the best place to deal with THIS specific failure.  That may be the very next line of code, it may be twenty levels up the call chain.  Wherever it is, that is where it should be.
What the catch block does depends upon the error and what you can do about it.  Sometimes it can simply be ignored (failure to delete a scratch file with no imortant data in it), sometimes it will be used to set a functions return value to true or false (java's int parse method), sometimes you'll exit the program.  All of that depends upon the error.
The important part to understand is: catch block == I know how to deal with this.

A: Catch blocks should only be used for handling exceptions, nothing else and never ever for control flow. In any situation where you want to use exceptions to manage flow you would be better off checking pre-conditions.
Handling flow with exceptions is slow and semantically incorrect.

A:
Should catch blocks be used for writing logic i.e. handle flow control etc? Or just for throwing exceptions? Does it effect efficiency or maintainability of code?

First, forget the notion that "exceptions should be used for exceptional conditions".  Also stop worrying about efficiency, until you have code that performs unacceptably and you have measured to know where the problem lies.
Code is easiest to understand when actions follow in a simple sequence, without conditionals.  Exceptions improve maintainability by removing error checking from the normal flow.  It doesn't matter if execution follows the normal flow 99.9% of the time or 50% of the time or 20% of the time.
Throw an exception when a function is unable to return a value, when a procedure is unable to complete the expected action, or when a constructor is unable to produce a usable object.  This allows programmers to assume that a function always returns a usable result, a procedure always completes the requested action, a constructed object is always in a usable state.
The biggest problem I see with exception handling code is that programmers write try/catch blocks when they should not.  For example, in most web applications, if a database request throws an exception, there is nothing that can be done in the controller.  One generic catch clause at the highest level is enough.  Then the controller code can blissfully ignore the possibility that the disk has crashed or the database is offline or whatever.

A: The example you cite is due to poor API design (there is no clean way to check whether a String is a valid integer except trying to parse it and catching the exception).
At the technical level, throw and try/catch are control flow constructs that allow you to jump up the call stack, nothing more and nothing less. Jumping the up the call stack implicitly connects code that is not close together in the source, which is bad for maintainability. So it should only be used when you need to do that and the alternatives are even worse. The widely accepted case where the alternatives are worse is error handling (special return codes that need to be checked and passed up each level of the call stack manually).
If you have a case where the alternatives are worse (and you really have considered all of them carefully), then I'd say using throw and try/catch for control flow is fine. Dogma is not a good substitute for judgement.

A: Catch blocks should not be used for writing code logic. They should be used only for handling errors. An example is (1) cleanup any allocated resources, (2) print a useful message, and (3) exit gracefully.
It's true that exceptions can be abused and cause undesired goto effects. But that doesn't make them useless. When properly used, they can improve many aspects of your code.


text:
Q: Show that a triangle delimited by parallel lines to the sides of another triangle is similar to said triangle. I was looking at geometric constructions of similar triangles, and at one point I came across the statement in the question.

A triangle delimited by vertices which are intersections of lines parallel to the sides of some other triangle is similar to said triangle.

I drew an example of the statement as follows:

Where the small green triangle's vertices are given by the intersections of some lines which are parallel to the sides of the blue triangle. The statement seems intuitively obvious, but I can't seem to find a way to justify it. I tried using the intercept theorem which is what I normally see is used to prove statements about similar triangles, but since I'm not sharing a side in both triangles I didn't think I could use it. Does anyone know a simple argument to justify this? Thank you!

A: The angle between two lines is the same as the one between two lines parallel to the original ones. Therefore the 3 angles of the deduced triangle are the same than the ones of the original triangle and the triangles are similar.

A: An easy way to make the connection:
Given triangle $ABC$, and through external points $D$, $E$, $F$ parallels drawn to $AB$, $BC$, $CA$, respectively, forming triangle $GHJ$.
For explicit proof that $\triangle ABC\sim\triangle GHJ$, extend $AB$ to meet the parallels to $CA$ and $BC$ at $K$ and $L$. Since by parallels$$\angle CAB=\angle JKL$$and$$\angle JKL=\angle JGH$$therefore$$\angle CAB=\angle JGH$$For the same reason$$\angle CBA=\angle JLK=\angle JHG$$Therefore remaining angles$$\angle ACB=\angle GJH$$ and$$\triangle ABC\sim\triangle GHJ$$


text:
Q: What should I do with an Id property in a View Model with HttpPost when database Id is an identity column? In my ASP.NET MVC program, I have a Model that looks like this:
public class PaycheckTypeViewModel
{
    public int Id { get; set; }
    public string Type { get; set; }
    public int CustomSortOrder { get; set; }
}

In my database, Id is an identity column.  In my controller I am creating a new record like this:
[HttpPost]
public async Task<ActionResult> Create(PaycheckTypeViewModel paycheckType)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost/api/");

        var responseMessage = await client.PostAsJsonAsync<PaycheckTypeViewModel>("paycheck-type", paycheckType);

        if (responseMessage.IsSuccessStatusCode)
        {
            return RedirectToAction("Index");
        }
    }

        ModelState.AddModelError(string.Empty, "Error calling API to Create New Paycheck Type.");

        return View();
}

The paycheckType parameter contains data like this:
CustomSortOrder   5
Id                0
Type              New Paycheck

The API that handles this Post Request knows to ignore the Id because its an identity column. But my question is what is usually done in this case? I thought of using [JsonIgnore] in the Model, but I want the Id to be serialized for displaying on the screen. It doesn't break anything by having the Id in the paycheckType parameter, but I thought this might not be the best practice.

A: well, best practice for design api is to separate the actions and what they need.
for example for creating you don't need to pass id so create a dto without id.
but when you want to update you need id so create a dto that contains id.
just remember that a method responsible just for one action. SOLID principle


text:
Q: get specific value of a TD tag How can I hide a specific TD in my Table ?
Rendered page:

    Codigo
    Tipo
    (L/V)
    Endereco
    Propostas Ativas
    Cons

    373054
    Apartamento
    V
    Rua DO FURQUIM
    1
    0

ASP page:
<asp:GridView ID="grdImoveis" Width="100%" runat="server" AutoGenerateColumns="false" DataSourceID="dsGrid" OnRowDataBound="grdImoveis_DataBound">
    <Columns>
        <asp:BoundField HeaderText="Código" DataField="Imovel_Id" />
        <asp:BoundField HeaderText="Tipo" DataField="TipoDsc1" />
        <asp:BoundField HeaderText="(L/V)" DataField="TransacaoSigla" />
        <asp:TemplateField HeaderText="Endereco">
            <ItemTemplate>
                <%# Eval("Descricao") %> <%# Eval("Logradouro") %>, <%# Eval("Numero") %> - <%# Eval("Expr1") %> <%# Eval("Complemento") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField HeaderText="Propostas Ativas" DataField="NumeroProposta" />
        <asp:BoundField HeaderText="Cons" DataField="FoundInSanNegocio" />
    </Columns>
</asp:GridView>

Drawing (Example):
Código      Tipo          (L/V)      Endereço         Propostas Ativas        Cons
373054      Apartamento    V         Rua Do Furquim   1                       0

I want to get via JQuery the value of the last column (Cons), but the user can't see this column. How can I hide and get the value of this column in each line ?

A: Assuming your Cons column is always the last one of your table, this should do it:
var myVar = '';
var myArray = new Array();

$('tr').each(function() {
    //this fetches the text content of the last cell of the current row:
    myVar = $(this).children("td:last").text();
    //this puts that value at the end of the myArray array
    myArray.push(myVar);
    //this hides that td
    $(this).children("td:last").hide();
});

I made a jsfiddle for it, seems to work.
http://jsfiddle.net/qnvHM/

A: Easiest way is:
  $(document).ready(function(){
  $('#<%=grdImoveis.ClientID %>').find('tr').each(function(){
      $(this).find('td:last').hide();
    });
  });

To get the value on click or some other event you can use:
 var value= $(this).find('td:last').text();

A: Check what the ID of you table is. Assuming it's grdImoveis, then:
// Hide last column and and get its value (text)
var comp = $("#grdImoveis TD:last").hide().text();


text:
Q: AWS Lambda and loading of reference data I'm building a Lambda function in AWS that need to load reference data from a mysql database. There is no real issue right now as it very limited amount of data. But what is best practice here? Is there away to keep this data within Lambda (or some other similar functionality) so that I don't need to request it for every invocation of the function? I'm using Node js though I don't think that affects this question.
Many thanks,
Marcus

A: There is no build-in persistent storage for lambda. Any data that you would like to keep reliably (not counting temporary persistence due to lambda execution context) between invocations is to store data outside of lambda itself.
You already store it in MySQL, but other popular choices are:

*

*SSM Parameter Store

*S3

*EFS

*DynamoDB

*ElastiCache if you really need fast access to the data.

Since you already get the data from MySQL the only advantage of using SSM or DynamoDB would be that you can use AWS API to access and update them, or inspect/modify in AWS Console. You don't need to bundle any MySQL client with your function nor establish any connections to the database.


text:
Q: Javascript: Fetch data while executing code I am building an app that relies on some data I need to fetch from my server. Right now my app starts with fetching the data and then passing down the data through several steps which are separated by classes. I simplify the code in the following.
Class1:

export default class Class1 {

    constructor(props) {
        this.props = props
    }

    async init() {
        const data = await this.fetchData()
        new Screen({ data }).init()
    }

    async fetchData() {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest()
            xhr.open("POST", 'http://localhost:8888/getData', true)
            xhr.setRequestHeader('Content-Type', 'application/json')
            xhr.onload = () => resolve(JSON.parse(xhr.responseText))
            xhr.onerror = reject
            xhr.send(JSON.stringify({}))
        })
    }

}

Class2:

export default class Screen {

    constructor(props) {
        this.props = props
    }

    async init() {
        let ScreenType
        if (this.offscreenIsSupported()) ScreenType = Offscreen
        else ScreenType = Onscreen

        new ScreenType(this.props).init()
    }

    offscreenIsSupported() {
        return "OffscreenCanvas" in window && "transferControlToOffscreen" in this.props.canvas
    }

}

OnscreenClass:

export default class Onscreen {

    constructor(props) {
        this.props = props
    }

    async init() {
        new Handler(this.props}).init()
    }

}

OffscreenClass:

export default class Offscreen {

    constructor(props) {
        this.props = props
    }

    async init() {
        this.worker = new Worker(new URL('./offscreen.worker.js', import.meta.url))
        const offscreen = this.props.canvas.transferControlToOffscreen()
        this.worker.postMessage({
            type: "init",
            canvas: offscreen
        }, [offscreen])
    }
}

offscreen.worker.js

self.onmessage = msg => {
    switch (msg.data.type) {
      case 'init':
        init(msg.data)
        break
    }
}

async function init(data) {
  self.vgHandler = new Handler({ data })
  await self.vgHandler.init()
}

Class3:

export default class Handler {

    constructor(props) {
        this.props = props
    }

    async init() {
        this.setup(this.props.data)
    }

}

As you can see the main code called in Class3 will be the same. This Class needs the fetched data. Class2 is just necessary to determine if the browser should use offscreen or onscreen canvas. Since checking the ability of using offscreen canvas as well as creating the web worker is not dependent to the fetched data it is not very smart to await the fetching process.
How am I able to fetch the data in background, run my code of Class2 simultaneously and use the fetched data in Class3?
I want to make this process as fast as possible.
Best


text:
Q: ReactJS: Problem accessing this.context in a class based consumer component I have a problem to access this.context in a class based consumer component. I have the following situation:
AppContext.js:
import React from "react";
const ContactContext = React.createContext();  // Create our context
export default ContactContext;

DataProvider.js:
import React, { Fragment } from "react";
import AppContext from "./AppContext";

export default class DataProvider extends React.Component {
    state = {
        contacts: {
            contact1: {
                id: 1,
                firstName: 'Test User FN',
                lastName: 'Test User LN'
            }
        }
    };
    render() {
        return (
            <>
            <AppContext.Provider value={{contacts: this.state.contacts}}>
                {this.props.children}
            </AppContext.Provider>
            </>
        );
    }
}

App.js:
import React from 'react';

import DataProvider from "./DataProvider";
import Contact from './components/contact/contact.component';

export default class App extends React.Component {
  render() {
    return (

          <DataProvider>
            <Contact contactIndex={0}/>
          </DataProvider>

    );
  }
}

The consumer Contact.js:
import React, { Component } from "react";
import AppContext from '../context/AppContext'

export default class Contact extends Component {
    static contextType = AppContext;

    componentDidMount () {
        console.log('My context is: ' + this.context);
    }

    render() {
        return (

        );
    }
}

The console output is:
My context is: undefined
Thanks for any help
Regards
Dakir

A: Your code seems right to me, I tried to replicate it in a Sandbox to find out the error and somehow works like a charm.
https://codesandbox.io/s/interesting-https-emgoz?file=/src/App.js
Tried to spot the difference but I couldn't honestly.

A: Only difference I see in the other answer's CodeSandbox is the import path is different.
import AppContext from "./AppContext";
vs:
import AppContext from '../context/AppContext'
Maybe OP has a filepath/import error?
p.s. If this is the error, TypeScript is a lifesaver for avoiding these kind of things in JS.


text:
Q: "Fuzzy Lookup" add in results Using Excel 2010, and the Microsoft "Fuzzy Lookup" add in to compare a column out of 2 worksheets. First worksheet has around 48,000 rows (x 3 columns), second worksheet has around 23,000 rows (x 5 columns). The "Fuzzy Lookup" is comparing one column from each & returning a similarity between the two.
The fuzzy lookup appears to run without a problem, and the results - in most cases - appear to be correct. For example:
W2-NK22/16 in one worksheet shows to have a 0.97 similarity to W2NK2216.
But not in all cases. Some that I expected to have some degree of similarity, instead have 0.000 returned by the Add-In. For example:
761689700000

should have some degree of similarity to:
761689700000EN4239

but the Fuzzy Lookup add in returns 0.000 for it. Both fields are formatted as text.  Neither have spaces before or after them, and the first 12 characters are identical.
I have uninstalled & reinstalled the add-in, and have used the default settings.  The only other Fuzzy Lookup settings I have changed were in Configure --> Global -- UseApproximateIndexing. I have set it to both False and True which have had no impact.
I have hundreds of examples like the one above that show 0.000 similarity, but upon inspection appear to be very similar.  Rows before & after them show various degrees of similarity.
Any thoughts or ideas as to why this doesn't appear to function correctly, or a better way to do this approximate match would be appreciated.

A: Trying to add content even though this case is 2 years old. Hopefully someone else can use it.
For Transformations, Tokenization, etc - look in the same folder where Fuzzy Lookup is installed. There is an example file there called Portfolio.xlsx and a corresponding Readme.docx file. Those are very helpful. Frankly the documentation on the Fuzzy Lookup add-in is terrible (but it is free). The Readme file talks about an entitlement called "EditTransformationProvider" that might help this kind of problem.
I've implemented Fuzzy on a couple processes at my work and we have saved hundreds of man-hours when working in Excel. It's no joke.


text:
Q: Netlogo: Create/ iterate multiple lists simultaneously I have a simple Astar search model that finds the optimal path to a given destination. It operates on all turtles- however, it does so one at a time.  I would like to speed up my simulation when having multiple turtles (ships) by having all turtles create/iterate through the search space (find-a-path) at the same time.
Below I have attached a portion of code where i call this.  Is there a way I can modify my current code to support this? Any help would be greatly appreciated, thanks.
to find-shortest-path-to-destination
      place-turtles
      label-destination
      ask ships
      [
        set path find-a-path current-waypoint target-waypoint
        set optimal-path path
        set current-path path
        output-show (word  "Shortest Path Length: " length optimal-path " (" "LP: " land-prox "," " LPW: " land-prox-weight ")")
      ]

    end

    to-report find-a-path [ source-patch destination-patch]

      ; initialize all variables to default values
      let search-done? false
      let search-path []
      let current-patch 0
      set open []
      set closed []

      ; add source patch in the open list
      set open lput source-patch open

      ; loop until we reach the destination or the open list becomes empty
      while [ search-done? != true]
      [
        ifelse length open != 0
        [
          ; sort the patches in open list in increasing order of their f() values
          set open sort-by [[f] of ?1 < [f] of ?2] open

          ; take the first patch in the open list
          ; as the current patch (which is currently being explored (n))
          ; and remove it from the open list
          set current-patch item 0 open
          set open remove-item 0 open

          ; add the current patch to the closed list
          set closed lput current-patch closed

          ; explore the neighbours of the current patch
          ask current-patch
          [
            ; if any of the neighbours is the destination stop the search process
            ifelse any? neighbors with [ (pxcor = [ pxcor ] of destination-patch) and (pycor = [pycor] of destination-patch)]
            [
              set search-done? true
            ]
            [
              ; the neighbors should not be obstacles or already explored patches (part of the closed list)
              ask neighbors with [ elev <= min-depth and (not member? self closed) and (self != parent-patch)  ]
              [
                ; the neighbors to be explored should also not be the source or
                ; destination patches or already a part of the open list (unexplored patches list)
                if not member? self open and self != source-patch and self != destination-patch
                [
                  set pcolor gray + 1

                  ; add the eligible patch to the open list
                  set open lput self open

                  ; update the path finding variables of the eligible patch
                  set parent-patch current-patch
                  set g [g] of parent-patch  + 1
                  set h distance destination-patch
                  set f (g + h)
                ]

              ]
            ]
            if self != source-patch
            [

            ]
          ]
        ]
        [
          ; if a path is not found (search is incomplete) and the open list is exhausted
          ; display a user message and report an empty search path list.
          user-message( "A path from the source to the destination does not exist." )
          report []
        ]
      ]

      ; if a path is found (search completed) add the current patch
      ; (node adjacent to the destination) to the search path.
      set search-path lput current-patch search-path

      ; trace the search path from the current patch
      ; all the way to the source patch using the parent patch
      ; variable which was set during the search for every patch that was explored
      let temp first search-path
      while [ temp != source-patch ]
      [
        ask temp
        [
          set pcolor white
        ]
        set search-path lput [parent-patch] of temp search-path
        set temp [parent-patch] of temp
      ]

      ; add the destination patch to the front of the search path
      set search-path fput destination-patch search-path

      ; reverse the search path so that it starts from a patch adjacent to the
      ; source patch and ends at the destination patch
      set search-path reverse search-path

      ; report the search path
      report search-path
    end


text:
Q: Drawing to canvas so i am dabbling in making a game and i am a fairly messy worker and then i go back and tidy it up. So please ignore any stupid naming conventions or methods or anything. As I go back later and tidy up.
So basically I am trying to make a main menu, i just want to draw something to the screen and have it stay there. I am writing the graphics to a image ATM and displaying the image as i tried just drawing to the canvas and it just flickered up onto the screen and then it went blank. I changed it to a runnable so i could put in sleep() to try and error hunt. I've removed all my error hunting code now. It turns out when i have a sleep() before or after the image is put on the screen for longer than 50ms the rectangle stays on screen and doesn't flicker away like 1ms after it was drawn.
I'm not sure what's going on. I am probably not that clear and I apologies.
    import java.awt.Canvas;
import java.awt.Graphics;

import javax.swing.JFrame;

public class test extends Thread{

    public static void main(String[] args){

        test t = new test();
        t.start();
    }

    @Override
    public void run() {
        JFrame f = new JFrame("Test");
        Canvas c = new Canvas();
        Graphics g;

        c.setSize(400, 400);
        f.add(c);
        f.pack();

        f.setVisible(true);
        c.setVisible(true);

        try {
            sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        g = c.getGraphics();

        g.drawRect(10, 10, 40, 68);

    }
}

A: Basically, this is not how painting in AWT works.  Painting should be done within the context of a component's paint method.  In AWT Canvas seems to be the preferred base component to use.
You should never use getGraphics, apart from been able to return null, it will only represent the Graphics context from the last paint cycle, anything added to it could be wiped about by newer paint events...which is probably happening to you.
Take a look at Painting in AWT and Swing for details about how painting works.
Having said all that, I would discourage you from using AWT based API as it was replaced by Swing some 15 years ago.
Take a look at Performing Custom Painting for more details about painting in Swing

A: You're kind of getting the idea, but there are a few standard design patterns of creating a game, for starters check out this code.
Basically, you'll need something called a game loop which will update and render to the display a certain amount of times every second (framerate or fps). When it renders, it will clear and redraw the image in a new location at a certain interval, if your fps was 60 you would be rendering (clearing, and redrawing) 60 times a second. We can also introduce more advanced concepts such as buffer strategies (shown in the example above) to reduce tearing and flickering.
To sum it up, you're kind of there, you just need to constantly do that g = c.getGraphics() so...
while (true) {
     g = c.getGraphics();

     // set color
     // draw a rectangle

     g.dispose();
}

Note how I added the dispose, this will just free up any unused memory. Just to clarify, this is by no means good code, but it will give you a place to start :)
The flickering is due to only having 1 screen, to stop this flickering you need a buffer strategy. Basically having two buffers is like having two screens, whilst you render on one 'screen' you can clear and draw the next step on the second screen and switch between the two buffers; this reduces the flickering.


text:
Q: regex trailing letters+numbers+symbols I have the following set of texts:
msg_type_add=ADD
table_name_card=cardholder
bin_card=7771800
member_card=123
card_status_active=123
card_status_cancelled=123

I would like to match the trailing letters ,numbers and symbol after the '=' symbol.
How would i match it with a regex expression.
any help would be appreciated.

A: You could match on:
[^=]+$

This would match the trailing portion after the equals sign.


text:
Q: How do we effectively prevent concurrent use of a web-application in one session? We have built a Spring MVC web application that is heavily relying on the user to do things in a certain order, and while it prevents users from circumventing this (without trying very hard) in the usual case (by not offering options to "go to places" you're not supposed to at the given moment), we're having some problems when people open another instance of the application in a new tab or browser window.
Since the application stores the domain model in the user's session, using the program in another window can potentially mess up the model's data, we've already implemented a page-ID mechanism that validates the user using the program in the correct order and not using the browser navigation, but we're still facing problems when things like resetting the program (this is a feature, redirecting the user to the home screen and clearing the domain model) happen in one window and the user then tries to do something relying on the domain model to be filled with valid data in another window (leading to a NullPointerException quite quickly).

A: Storing some user details (like id, name, email) in a session might be ok, but storing the user's state (or any data that changes often and/or significantly affects other things in your app) doesn't sound like a good idea.
Hopefully one of the following approaches will fit you:

*

*Don't save state in the session - load it from the database whenever you need it (in your case, whenever the user tries to access one of the steps that should be done in order). If you use caching, this shouldn't have major performance consequences.

*Don't save state in the database, only in the session - works for limited cases (for instance, ordering airline tickets) where you can postpone committing your domain object until the process has finished.

*Use Ajax for multi-step processes and don't save state at all (except implicitly in the browser). This requires putting all the steps into one page and ajaxifying some of your code.

Regardless, if someone logs in and tries to go to step 3, they shouldn't get an exception thrown at them, but that's a different story.

A: If I were you, I'd let user to wander around other parts of the website - the parts that don't interfere with your wizard process. However, once they try to restart it - check if there's PageID in session, and remind them they have not finished what they started, and ask if they would like to cancel/restart or continue on from where they left it.

A: In case anyone ever reads this question again:
Instead of the HttpSession keeping exactly one copy of the domain model it now holds a collection and we transport a reference to a single one of the models through the requests/responses so we can get the right model to work on in our controllers and views.


text:
Q: jQuery does not send form even when file is uploaded I created a function to validate if an file is uploaded or not.
When the file is not uploaded the form should not submit, but when a file is uploaded it should submit.
But when I upload a file I still get the error that I have to upload a file.
Here is the jQuery code I am using:
$("#btnSave").click(function () {
    var vidFileLength = $("#videoUploadFile")[0].files.length;
    if(vidFileLength === 0){
        $("#formType").submit(function(e){
        alert('Selecteer een afbeelding!');
        e.preventDefault();
        });
    }
});

And here is the form:
<form action="php/edit.php?id=type" method="post" id="formType">

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Website bewerken

            Type ID
            <input type="text" id="typeId" name="typeid" class="form-control" readonly="readonly">

            Type Naam
            <input type="text" id="typeNaam" name="typenaam" class="form-control" >

            Type Waarde
            <input type="text" id="typeWaarde" name="typewaarde" class="form-control" >

            Type Afbeelding
            <input class="input-group" type="file" id="videoUploadFile" name="user_image" accept="image/*" />

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" id="btnSave" name="submit" class="btn btn-primary">Save changes</button>

    </form>

Thanks for your time!

A: The issue is because you've added the submit event handler in the if condition, therefore once the form is made valid again the old submit handler will stop the submission.
To fix this you need to change your logic to always execute on the submit handler and use preventDefault() to stop the submission if the file is not present. Try this:
$('#formType').submit(function(e) {
  var vidFileLength = $("#videoUploadFile")[0].files.length;
  if (vidFileLength === 0) {
    alert('Selecteer een afbeelding!');
    e.preventDefault();
  }
});


text:
Q: The given ruleset does not contain any rules with type System.Object, mscorlib, First, I am using www.codeeffects.com framework to make a business rule evaluator, but in my case I need the types to be 100% dynamic.
I have the following code in my Proof of Concept method.
public ActionResult Save(RuleModel ruleEditor)
{
    DummyEntitiesGen gen = new DummyEntitiesGen();
    Type t = gen.CreateType();
    List<dynamic> lista= gen.CreateTypeList();
    // At this point the rule model doesn't know which type to use as its source object
    // We need to "bind" the source type to the rule model
    ruleEditor.BindSource(t);

    // Add the rule model to the ViewBag object
    ViewBag.Rule = ruleEditor;

    // Make sure that the Rule Area is not empty and the current rule is valid
    if (ruleEditor.IsEmpty() || !ruleEditor.IsValid(StorageService.LoadRuleXml))
    {
        ViewBag.Message = "The rule is empty or invalid";
        return View("Index");
    }
    try
    {
        // Save the rule
        StorageService.SaveRule(
            ruleEditor.Id,
            ruleEditor.GetRuleXml(),
            ruleEditor.IsLoadedRuleOfEvalType == null ?
            true : (bool)ruleEditor.IsLoadedRuleOfEvalType);

        // Get all rules for Tool Bar and context menus and save it in the bag
        this.LoadMenuRules();

        DynamicEvaluator evaluator = new DynamicEvaluator(ruleEditor.GetRuleXml());
        //bool success = evaluator.Evaluate(lista, ruleEditor.Id);

        IEnumerable<dynamic> result = lista.Filter<dynamic>(ruleEditor.GetRuleXml());
        //var result = lista.AsQueryable<t>().Filter(ruleEditor.GetRuleXml());

        ViewBag.Message = "The rule was saved successfully";
    }
    catch (Exception ex)
    {
        ViewBag.Message = ex.Message;
    }
    return View("Index");
}

the object lista is fine and returns a list of dynamic types created that I can see at debug time.
However the line that is supposed to filter is giving me this exception:
The given ruleset does not contain any rules with type System.Object, mscorlib

A: The GetRuleXml() method returns an XML with the type attribute set to a type of the source object. In your case it would be the name of the type returned by the gen.CreateType() method, e.g.:
<rule id='03b33dd0-4389-4ac4-a5aa-bd81fab41e00' eval='true' webrule='4.0.0.8' utc='10/20/2011 4:19:27 PM'
type='MyApplication.MyClass, MyApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ab44223d08cca81e'>

During a compilation phase the engine checks the type of an instance object against the one specified by the type attribute. If they do not match you get that exception ("The given ruleset does not contain any rules...").
You could avoid it by clearing or removing the type attribute. Doing so bypasses type check during compilation.
That said, the CodeEffects rule engine does not support dynamic objects or types. Not yet anyway.
The DynamicEvaluator is a legacy class which has nothing to do with dynamic objects or types. It builds a dictionary of evaluators for each type of an object that gets evaluated allowing to reuse the same rule for various types so long their properties and methods match.
Once you remove the type attribute from the rule element, you will get a different exception, most likely "System.ArgumentException: 'x' is not a member of type 'System.Object'".
This is because there is no such type as dynamic in .NET. Dynamic merely tells a compiler to skip type checking during compilation and adds some magic at run-time. However, underneath it is passed as Object.
The engine uses expressions to build a rule, not reflection. Since it is the Object in case of dynamic, it will fail to find any properties or methods used in the rule's XML.
There are plans to add support for dynamic objects (objects implementing IDynamicMetaObjectProvider), but I don't know the timeframe.


text:
Q: How to take into account the symmetry of the metric tensor when doing the Functional derivative in GR? I have a Straightforward question. When the functional derivative of the Ricci scalar to get the GR field equations. As the derivative is done using the metric which is symmetric do I have to symmetrize my results.
On mathematica with the package xAct the "VarD" function always symmetrizes when I do a variation with a symmetric tensor.
For normal GR as I understand the symmetry pops out on its own, but as I'm working on other formulations of GR, sometimes this symmetry isn't a given.
Edit: As pointed in the comments by Qmechanic there is a similar answered question:  Variation of the metric with respect to the metric
 I'm convinced now, as I expected, that I should symmetrize the results.

A: Yes, since you are varying with respect to a symmetric tensor, only the symmetric part of the variation will survive on-shell.
To see this, suppose we are given a Lagrangian $\mathcal{L}=\mathcal{L}(T_{ab})$ which depends on a symmetric tensor field $T_{ab}$ (and perhaps some other independent fields) and an action $S=\int\text{d}^4x\mathcal{L}$. Then varying $S$ w.r.t $T^{ab}$ yields
$$\delta S=\int\text{d}^4xG_{ab}\delta T^{ab}=\int\text{d}^4x\big(G_{(ab)}+G_{[ab]}\big)\delta T^{ab}=\int\text{d}^4xG_{(ab)}\delta T^{ab}=0$$
$$\implies G_{(ab)}=0$$
where I have denoted $G_{ab}:=\frac{\delta\mathcal{L}}{\delta T^{ab}}$ and have used the fact that $\delta T^{ab}=\delta T^{(ab)}$ is symmetric to kill the antisymmetric part of $G_{ab}$. This isn't very rigorous, but you get the idea.


text:
Q: Установка ОС из под ОС Нужно сделать следующее: установить ОС Debian из под этой же ОС, т.е. я хочу подключить жесткий диск к компу, загрузиться со своего и установить на новый ЖД - ОС, как такое можно сделать?

A: Это делается с помошью debootstrap.
Сначала форматируешь и размечаешь диск. Смонтируй в /target
 mkdir -p /target
 mount /dev/sdb1 /target
 debootstrap jessie /target http://deb.debian.org/debian/

В fstab надо добавить путь к диску, лучше через uuid (ls -la /dev/disk/by-uuid | grep sdb).
В /target/fstab:
 UUID=b674ab88-c521-47b3-b4a1-9614590482a6 / ext4 rw,defaults 0 0

Потом биндишь /dev/ /proc/ /sys/
mount -B /dev/ /target/dev
mount -B /sys/ /target/sys
mount -B /proc/ /target/proc

Чрутишься туда и доустанавливаешь ядро, загрузчик и десктоп если надо
chroot /target /bin/bash
echo nameserver 77.88.8.8 > /etc/resolv.conf

apt update
apt install linux-image-amd64 tasksel grub
tasksel
grub-install /dev/sdb

Загрузчик ставится только вручную на нужный диск.
Не забудьте создать пользователей и установить пароль на root (или sudo):
apt install sudo adduser
adduser username
adduser username sudo

или
passwd root

Дальше выходи из chroot (контрол+d или exit) и пробуй загрузиться.
Wiki скудна на инструкции
https://wiki.debian.org/ru/Debootstrap
Подробная инструкция из мануалов
https://www.debian.org/releases/stable/amd64/apds03.html.ru


text:
Q: Loading data from angular service on startup UPDATE
I am currently doing this, and I'm not sure why it works, but I don't think this is the correct approach. I might be abusing digest cycles, whatever those are.
First, I want to have the array navigationList be inside a service so I can pass it anywhere. That service will also update that array.
app.factory('ChapterService', [ 'ExtService', function(ExtService) {

  var navigationList = [];

  var getNavigation = function() {
    ExtService.getUrl('navigation.json').then(function(data) {
      angular.copy(data.navigationList, navigationList);
    });
  }
  return{
   getNavigation: getNavigation,
    navigationList: navigationList,
}
}]);

Then in my controller, I call the service to update the array, then I point the scope variable to it.
  ChapterService.getNavigation();
  $scope.navigationList = ChapterService.navigationList;
  console.log($scope.navigationList);

But this is where it gets weird. console.log returns an empty array [], BUT I have an ng-repeat in my html that uses $scope.navigationList, and it's correctly displaying the items in that array... I think this has something to do with digest cycles, but I'm not sure. Could anyone explain it to me and tell me if I'm approaching this the wrong way?

I have a main factory that runs functions and calculations. I am trying to run
app.factory('ChapterService', [ 'ExtService', function(ExtService) {

  var navigation = {
    getNavigationData : function () {
      ExtService.getUrl('navigation.json').then(function(data) {
        return data;
      });
    }
  }

  return: {
       navigation: navigation

}

I did a console.log on the data before it gets returned and it's the correct data, but for some reason, I can't return it..
The ExtService that has the getUrl method is just the one that's typically used (it returns a promise)
In my controller, I want to do something like
$scope.navigation = ChapterService.navigation.getNavigationData();

in order to load the data from the file when the app initializes,
but that doesn't work and when I run
console.log(ChapterService.navigation.getNavigationData());

I get null, but I don't know why. Should I use app.run() for something like this? I need this data to be loaded before anything else is done and I don't think I'm using the best approach...
EDIT
I'm not sure if I should do something similar to what's being done in this jsfiddle, the pattern is unfamiliar to me, so I'm not sure how to re purpose it for my needs
My code for ExtService is
app.factory('ExtService', function($http, $q, $compile) {
   return {
     getUrl: function(url) {
       var newurl = url + "?nocache=" + (new Date()).getTime();
       var deferred = $q.defer();
       $http.get(newurl, {cache: false})
        .success(function (data) {
            deferred.resolve(data);
        })
        .error(function (error) {
            deferred.reject(error);
        });

      return deferred.promise;
     }
   }
});

EDIT 2
I'd like to separate the request logic away from the controller, but at the same time, have it done when the app starts. I'd like the service function to just return the data, so I don't have to do further .then or .success on it...

A: You are using promises incorrectly. Think about what this means:
var navigation = {
    getNavigationData : function () {
        ExtService.getUrl('navigation.json').then(function(data) {
            return data;
        });
    }
}

getNavigationData is a function that doesn't return anything. When you're in the "then" clause, you're in a different function so return data only returns from the inner function. In fact, .then(function(data) { return data; }) is a no-op.
The important thing to understand about promises is that once you're in the promise paradigm, it's difficult to get out of it - your best bet is to stay inside it.
So first, return a promise from your function:
app.factory('ChapterService', [ 'ExtService', function(ExtService) {
    var navigation = {
        getNavigationData: function () {
            return ExtService.getUrl('navigation.json');
        }
    }

    return {
        navigation: navigation
    }
}])

Then use that promise in your controller:
app.controller('MyController', function($scope, ExtService) {
    ExtService
        .navigation
        .getNavigationData()
        .then(function(data) {
            $scope.navigation = data;
        });
})

Update
If you really want to avoid the promise paradigm, try the following, although I recommend thoroughly understanding the implications of this approach before doing so. The object you return from the service isn't immediately populated but once the call returns, Angular will complete a digest cycle and any scope bindings will be refreshed.
app.factory('ChapterService', [ 'ExtService', function(ExtService) {
    var navigation = {
        getNavigationData: function () {
            // create an object to return from the function
            var returnData = { };

            // set the properties of the object when the call has returned
            ExtService.getUrl('navigation.json')
                .then(function(x) { returnData.nav = x });

            // return the object - NB at this point in the function,
            // the .nav property has not been set
            return returnData;
        }
    }

    return {
        navigation: navigation
    }
}])

app.controller('MyController', function($scope, ExtService) {
    // assign $scope.navigation to the object returned
    // from the function - NB at this point the .nav property
    // has not been set, your bindings will need to refer to
    // $scope.navigation.nav
    $scope.navigation = ExtService
        .navigation
        .getNavigationData();
})

A: You are using a promise, so return that promise and use the resolve (.then) in the controller:
app.factory('ChapterService', [ 'ExtService', function(ExtService) {

    var navigation = {
        getNavigationData: function () {
            return ExtService.getUrl('navigation.json'); // returns a promise
        });
    }

    return: {
        navigation: navigation
    }
}

controller:
ChapterService
    .navigation
    .getNavigationData()
    .then(function (data) {
        // success
        $scope.navigation = data;
    }, function (response) {
        // fail
    });

A: This is a different approach, I don't know what your data looks like so I am not able to test it for you.
Controller
.controller('homeCtrl', function($scope, $routeParams, ChapterService) {
    ChapterService.getNavigationData();
})

Factory
.factory('ChapterService', [ 'ExtService', function(ExtService)  {

        function makeRequest(response) {
            return ExtService.getUrl('navigation.json')
        }

        function parseResponse(response) {
            retries = 0;
            if (!response) {
                return false;
            }
            return response.data;
        }

        var navigation =  {
            getNavigationData: function () {
                return makeRequest()
                    .then(parseResponse)
                    .catch(function(err){
                        console.log(err);
                    });
            }
        }

        return navigation;

    }])


text:
Q: Parsing webpages, using re, how to determine the line of a found string? I am lookng at a website in python using code like this:
import urllib
import urllib2
import re

aResp = aResp = urllib2.urlopen("http://stackoverflow.com/");

web_pg = aResp.read();

pattern = "<title>Stack Overflow</title>"

m = re.search(pattern, web_pg)

if m:
   print "found"

else:
   print "Nothing found"

And I am trying to look at the tag after this and get the test inside of it. Is there any easy way to find out this information????
If it is simpler I could make do with something that just gives the line number of m and a way to get the HTML code of that line.

A: To capture text, use the () braces like so:
import urllib
import urllib2
import re

aResp = aResp = urllib2.urlopen("http://stackoverflow.com/");

web_pg = aResp.read();

pattern = "<title>(.*?)</title>"

m = re.search(pattern, web_pg)

if m:
   print m.group(1)

else:
   print "Nothing found"

The .group() function returns the first occurrence of the match.


text:
Q: irrationality of Bessel function in $p$-adic Let $J_0(z)=\sum_{n\ge 0}\frac{(-1)^n}{n!^2}\left(\frac z2\right)^{2n}$ be the Bessel function considered in $\mathbb C_p$. Let $\alpha\in\mathbb Q^*$ be in the convegence disk of $J_0$. Is $J_0(\alpha)$ irrational? That sounded a pretty natural question, but I find nothing about this in googling.
Any answer will be welcome.


text:
Q: Why am I receiving an unused extension error on a dynamic AMP page? From the AMP validator I am getting the following error.

The extension 'amp-date-picker' was found on this page, but is unused. Please remove this extension.

This is a dynamic page so sometimes the datepicker will appear on the page and sometimes it will not.
The AMP docs say the script needs adding to the head, so this means that sometimes there will be a scenario where there is no datepicker, but the script is still included.
As I do not think I should be adding this script in with the component HTML, what are my options to fix this error?
Thanks
David

A: You're getting the error due to performance reasons as most components either ignore or warn instead of throwing an error like this. You should be checking your content server-side and dynamically including the script it only if there's a need for it.
This is an example of something similar in PHP (Bolt CMS) which I built for a client a while ago, in the page head it checks for the inclusion of the amp-youtube tag in the body before including the script. You'll need to use whatever language you're using, of course.
{% set body = record.body|ampraw %}
{% if 'amp-youtube' in body %}
  <script async custom-element="amp-youtube" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script>
{% endif %}

You can view the validation rules for amp-date-picker here.


text:
Q: Div is not visible only in Firefox? I have the following css for my error div:
.side_error {
width: 325px;
position: absolute;
top: 0;
left: -335px;
padding: 8px 0 0 0;
text-align: right;
color: #FF0000;
display: block;
}

and the following css for my table td:
.main_form td {
padding: 5px 0 5px 0;
position: relative;
}

And my HTML structure:

Create an account
(or Sign In)

please enter your full name >>
<input type="text" name="fullname" placeholder="Full Name" class="input">

<input type="text" name="email" placeholder="Email" class="input">

<input type="password" name="pass1" placeholder="Password" class="input">

<input type="password" name="pass2" placeholder="Repeat Password" class="input">

<input type="checkbox" name="terms" value="yes" id="rm"> I agree to **** Terms.<input type="submit" name="submit" class="submit" value="Create Account">

The div with class side_error seems to appear in every browser exactly how I want it but in Firefox (version 17.0.1) it doesn't display at all, even when I use Firebug the div doesn't get colored when hovering the html code, its like it doesn't exist at all.
Any ideas?

A: Reorganized your css, see if this helps-
CSS-
.side_error
{
  width: 325px;
  position: relative;
  top: 20px;
  left: -327px;
  padding: 8px 0 0 0;
  text-align: right;
  color: #FF0000;
  display: inline-block;
}
.main_form td
{
   position:relative;
   padding: 5px 0 5px 0;
}
table
{
   width:330px;
}

See the working Fiddle- DEMO

A: remove left: -335px; and position: absolute; try use right :10px;
or put an extra div around content in td and assign class:

       Create an account
(or Sign In)


text:
Q: epoll file descriptor operations I'm trying to wrap my head around epoll in Linux.
The normal operation seems to be:
// Create the epoll_fd
int epoll_fd = epoll_create(10);

...

// Add file descriptors to it
struct epoll_event ev = {0};
ev.events |= EPOLLIN;
ev.data.ptr = ...;

/* for brevity, I don't do error checking here */
epoll_ctl(epoll_fd, EPOLL_CTL_ADD, some_fd, &ev);

...

// Wait for IO events
struct epoll_event events[10];
int num_events = epoll_wait(epoll_fd, events, 10, -1);

// Now handle the events
...

My question is this: given the epoll_fd seems to be a regular file descriptor, are there any other file operations that I can do with it, besides the three epoll function calls?

A: From the man page:

Q3     Is the epoll fd itself
  poll/epoll/selectable?
A3     Yes.

A: You can poll(2) your epoll_fd itself :)