text:
Q: PostType = Wiki, Wiki + Reputation can it be done? I would like to propose a new PostType to the tetralogy. PostType = Wiki.
What should be Wiki?
I think the ideal candidates for wiki style posts would be posts that are long and already are community wiki.
For example this query captures quite a few of them: http://odata.stackexchange.com/stackoverflow/q/66
What is different about Wiki posts?

*

*Wiki posts are owned by the community.

*You can gain reputation by improving Wiki posts.

*Wiki posts do not fit the current Q&A model, the question is the title, the answer is the body.

*Wiki posts only have commenting, there is no answering allowed.

*Wiki posts have a special UI

*Wiki posts have search priority (maybe)

OK, give some examples
List of freely available programming books is a wonderful post with lots of information, the trouble is, there is no incentive to keep it up to date. And the answers, well they are noisy and a repeat of what is at the top.
One more is Git for beginners. The big trouble is that you need a page reload every time you want to navigate to a section. And scroll-up foo.
Another C++ for a C# developer. It's really useful information that would cover probably a few hundred questions and really is a community effort.
The seminal Hidden Features of C#? would by amazing if it was just a single document with collapsible sections. After you work through 2 of them you just get tired of refreshing your web browser.
This one, The .NET SDK Programs - What does each tool do?, fits the wiki mold so tightly it's scary. It's a perfect candidate.
Other ideas around post type wiki

*

*Wikis could be used for some static pages on the site like this one.

*On meta we could use a wiki for the long requested change log

*If we allow an abstract for wikis (8 lines of so) they could be associated with a tag and show up in the box when a tag is selected.

So:

*

*Do we need this kind of post?

*What are the mechanics involved in building this?

A: This is a good idea, but I am not convinced that it is possible to combine wiki with reputation without becoming too complicated or open to abuse. I think that people will contribute without reputation incentives just to reduce the number of duplicate questions or because they want these resources for themselves.

A: I agree with @Aarobot. There is something here. Great idea waffles. I see a huge difference in this idea of a SOFU-wiki than the typical wiki-pedia.

*

*the wiki is produced by the SOFU community. Not only are the items brought up from questions that have been wiki-fied, but a huge source of information follows. A lot of it is very valuable information that I would guess is actually fairly untapped.

*the Wiki is moderated by 6K+ (or whatever) users ensuring that all information is maintained - adding new information and editing.

*a more dynamic, digital tome of vast amounts of diverse technical information and data.

Well, these are just a few ideas on why it is a good idea. This idea for a wiki just doesn't have the same feel as a wiki-pedia site would. I really think that it can be done in such a way that it isn't just another wiki.
This question is an example of a good discussion to wiki-fy.

A: In my opinion, this is closely related to the
Create a tag homepage/FAQ
proposal.
I don't see us doing this except as a [tag] page feature. The focus of the sites is not to be a host of epically large FAQ questions, but a host of related questions around a topic.
The natural place to coalesce the common elements of the topics is in the parent [tag] page which is the natural home for that "topic"  anyway.

Wiki posts do not fit the current Q&A model, the question is the title, the answer is the body.

.. which is why they're a bad fit. We do Q&A. There can be some wiki-ness around the [tag] parent but that's about it.

A: I'll be the (so far) lone dissenter and upvote the idea. Putting my Meta Internet Dollars at massive risk here, just so you know!
Why do I like the idea? SuperUser. Wha-wha-wha?! Yes. I recently discovered that one of my questions on SU was closed as an exact duplicate by random. At first I thought, hey, they're not dupes! The tech involved is different!
Then I realized why it was closed -- SU would be overrun by the phenomenon of a million super-similar-but-different-only-in-a-single-technology questions if mods weren't diligent. (And thank you for your diligence, mods, particularly in the land of Ewoks.)
As this dawned on me, I was thankful that the question was closed, but felt a little empty: How could the community address scenarios like this, where a million similar-but-just-slightly-different questions could come up?
I think your idea, waffles, could handle that scenario. And thus, I support the idea. Either that, or one master community wiki post in the current framework with answers for specific technologies. But I think your idea, if the ability to include named anchors were included, would probably be more effective. (And would provide accurate dupe fodder for those questions.)

A: Meh, too many implementation details and complications for very little gain in my opinion.
(post kept here for historical purposes. I withdraw this opinion though)


text:
Q: Can a depth-first search using a stack return a path to the goal? I'd like to use a stack and return a path, but I'm thinking it's not possible.
A node must be called directly by its parent so that it can receive the path behind it, whereas when this node is pushed onto a stack, it loses the path so far. Using a stack would result in a node being evaluated in isolation, and I couldn't pass the path to the node's parent through to the node.
I can't let nodes have the property of the path behind them, since it's a homework assignment.
I've been stumped on this one for over a week!

A: "A node must be called directly by its parent so that it can receive the path behind it," <- This seems okay.
whereas when this node is pushed onto a stack, it loses the path so far. <- This isn't anything to worry about I believe.
What you can do is to recursively build up the stack with something like
def makepath(someGraph, from, to):
    if(from == to)
        return ""

    nextNode= <...> #find out next node in path here
    return makepath(someGraph, nextNode, to) + str(nextNode)

A: Whenever you pop a node from the stack, you need a way of retrieving the path that led to that node.
One solution is push tuples of (node, path) on the stack instead of just node values. If path is a purely functional list like in Haskell, this is a good solution, but in Python it may not be as idiomatic. Also while the path strictly speaking isn't stored within the node, this solution probably isn't in the spirit of the question.
Another solution is to maintain a separate stack that contains the path to the previously visited node. The depth-first stack contains tuples of (node, depth) where depth is the depth of the node in the search. Before adding node to the end of the path, elements are popped from the path until the length of the path equals depth.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Assign python Decimal objects to MySQL DECIMAL columns I have a table "City" defined as:
CREATE TABLE `City` (
  `id` int(11) NOT NULL,
  `lat` decimal(9,6) default NULL,
  `long` decimal(9,6) default NULL,
  `lm_index` int(11) default NULL,
  `num_business` int(11) default NULL,
  `postal_code` varchar(16) default NULL,
PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

I use python with SQLAlchemy to map this table:
Base = declarative_base(engine)

class City(Base):
    ''''''
    __tablename__ = 'City'
    __table_args__ = {'autoload':True}
    def __init__(self, id, lat, long, lm_index, numbiz, postal):
        self.id = id
        self.lat = lat
        self.long = long
        self.lm_index = lm_index
        self.num_business = numbiz
        self.postal_code = postal

If I understand the python decimal package correctly, this should work:
from decimal import *

getcontext().prec = 6
lat = 12.11111111
long = 46.2222222

city = City(1, Decimal(str(lat)), Decimal(str(long)), 0, 0, 0)

However, I still get the same errors as I do when I don't call Decimal():
Warning: Data truncated for column 'lat' at row 1

What am I doing wrong here?

A: My guess is, because you're sending an instance of Decimal, the lat or long fields are being turned to something like a string representation of the instance. Again, I'm not sure. You can use pdb to debug that.
Anyway, there are better ways to deal with DECIMAL fields in MySQL via SQLAlchemy. Instead of handling the decimal processing yourself, you could just let sqlalchemy take care of it -
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class City(Base):
    __tablename__ = 'City'
    __table_args__ = {'autoload':True}

    id = Column(Integer, primary_key=True)
    lat =  Column(Numeric(precision=9, scale=6))
    long =  Column(Numeric(precision=9, scale=6))
    ...

Numeric field returns decimal.Decimal objects by default, applying conversion as needed.
Then you can initiate it as -
city = City(lat=12.11111111, long=46.2222222, ...)

If you override __init__() then you can initiate it like City(12.1111, 46.2222), but I prefer keeping the column name, that way you know at a glance which field is getting what, instead of counting the number of values each time.
I haven't tested the code, but it should work. Try.


text:
Q: How to read one line from `tail -f` through a pipeline, and then terminate? I would like to follow changes to a file via tail -f and then print out the first line that matches a grep command before terminating. What's the simplest way to do this? So far I've been experimenting with things like:
tail -f foo.log | grep 'bar' | head -1

However, the pipeline just hangs, presumably due to buffering. I also tried
tail -f foo.log | grep --line-buffered 'bar' | head -1

This prints out the line, but the process does not terminate unless I hit ^C, presumably because a second line of input is needed to terminate head -1. What's the best way to solve this problem?

A: The <() construct works in bash only. My solution is:
sleep $timeout &
pid=$!
tail -n +0 --pid=$pid -F "$file" | ( grep -q -m 1 "$regexp" && kill -PIPE $pid )
wait $pid

Besides it's working in a POSIX shell, one other advantage is that the waiting period can be limited with a timeout value. Note that the result code of this scriptlet is reversed: 0 means the timeout was reached.

A: tail -f foo.log | grep -m 1 bar

if the file foo.log is writen rarily to, you can do:
grep -m 1 bar <( tail -f foo.log )

It should be noted that the tail -f will stay in background until it will get another line to output. If this takes long time it might be problematic. solution in such case is:
grep -m 1 bar <( exec tail -f foo.log ); kill $! 2> /dev/null

kill will kill leftover tail -f process, and we hide errors, because it's possible that the tail will be gone by the time kill will be invoked.

A: tail -f waiting for SIGPIPE, which, as already pointed out by depesz, can only be triggered by another write of tail -f to a closed pipe after a successful grep -m 1 match, can be avoided if the tail -f command gets backgrounded and its background pid being sent to the grep subshell, which in turn implements a trap on exit that kills tail -f explicitly.
#(tail -f foo.log & echo ${!} ) |
(tail -f foo.log & echo ${!} && wait ) |
   (trap 'kill "$tailpid"; trap - EXIT' EXIT; tailpid="$(head -1)"; grep -m 1 bar)

A: Building on answer https://superuser.com/a/275962/37154 , I realized that if the tail would start too late, some instance of the indicated string may have gone by already. The solution is to make tail list the whole file.
grep -m 1 bar <( exec tail -n +1 -f foo.log ); kill $!

A: I think that applying unbuffer like this,
tail -f foo.log | unbuffer -p grep 'bar' | head -1

would work. I'm not at a system where I can test it, though, and I can't justify why it would work while grep --line-buffered does not. However, I did try this alternative which does seem to work:
tail -f foo.log | sed -n '/bar/{p;q}'

When the match to bar is found, p prints it and q immediately quits.


text:
Q: Verilog 4-bit ripple adder which is made up of full adders I simulated a 4-bit ripple adder made up of 4 full adders in Verilog. Here, I'm trying to understand what is happening with Cout. Cout stands for carry output. I can't explain how values E and F were obtained in Cout.
This is ripple_adder.v
module full_adder( A, B, CIN, Q, COUT );
input A, B, CIN;
output Q, COUT;
assign Q = A ^ B ^ CIN;
assign COUT = (A & B) | (B & CIN) | (CIN & A);
endmodule

module adder_ripple( a, b, q );
input [3:0] a, b;
output [3:0] q;
wire [3:0] cout;
full_adder add0 ( .Q(q[0]), .COUT(cout[0]),
 .A(a[0]), .B(b[0]), .CIN( 1'b0) );
full_adder add1 ( .Q(q[1]), .COUT(cout[1]),
 .A(a[1]), .B(b[1]), .CIN(cout[0]) );
full_adder add2 ( .Q(q[2]), .COUT(cout[2]),
 .A(a[2]), .B(b[2]), .CIN(cout[1]) );
full_adder add3 ( .Q(q[3]), .COUT(cout[3]),
 .A(a[3]), .B(b[3]), .CIN(cout[2]) );
endmodule

This is test bench for ripple_adder.v
`timescale 1ps/1ps
module adder_ripple_tp;
reg [3:0] a, b; // reg declaration for input
wire [3:0] q; // wire declaration for output
parameter STEP = 100000;
adder_ripple adder_ripple( a, b, q );
initial begin
$dumpfile("adder_ripple.vcd");
$dumpvars(0, adder_ripple_tp);
 a = 4'h0; b = 4'h0;
 #STEP a = 4'h5; b = 4'ha;
 #STEP a = 4'h7; b = 4'ha;
 #STEP a = 4'h1; b = 4'hf;
 #STEP a = 4'hf; b = 4'hf;
 #STEP $finish;
end
initial $monitor( $stime, " a=%h b=%h q=%h", a, b, q );
endmodule

The wave looks like this:

Can someone help me understand it?

A: The value of cout[3] represents the value of the 2^4=16, when it is asserted,0 when de-asserted.
For the vector where a=7, b=0xa=10, the answer is 17, which is indicated by the sum of value of q=1 + the value of cout[3] = 16.
cout is equal to 0xe=4'b1110 in this vector, indicating the sum of the least significant digit did not carry out, and the sum of each of the other digits did carry out.
For the vector where a=1, b=0xf=15, the answer is 16, which is indicated by the sum of q=0 + the value of cout[3] which is 16.
cout is equal to 0xf=4'b1111 in this state indicating the sum of each digits carried out.
For the vector where a=0xf=15, b=0xf=15, the answer is 30, which is indicated by the sum of q=0xe=14 + the value of cout[3] which is 16.
cout is equal to 0xf=4'b1111 in this state indicating the sum of each digits carried out.


text:
Q: Function as service in Symfony2 I am storing a string in database that I want to access from various places in my application. I figure out that the best solution will be create a function that is taking that string from database and register it as a service.
Function:
public function shopUrlAction()
{
  return new Response($this->getDoctrine()->getRepository('AppBundle:Settings')->find(1)->getName());
}

service.yml
services:
  app.default_controller:
    class: AppBundle\Controller\DefaultController

output in other controller:
$return['base_url'] = $this->forward('app.default_controller:shopUrlAction');

Unfortunately I am constantly getting

CRITICAL - Uncaught PHP Exception
  Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException:
  "You have requested a non-existent service "app.default_controller"."
  at /app/bootstrap.php.cache line
  2099  Context:
  {"exception":"Object(Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException)"}

I've cleared cache.

A: As I see from your question you have service.yml instead of services.yml (in plural form).
You should include your service.yml in main config.yml in imports section or use standard path to it (AppBundle/Resources/config/services.yml)


text:
Q: Nodejs Mongodb find performance issue I just recently put hands on mongodb, by that time I have been having many issues. I'm creating a card game, so I thought mongodb would be the best option for this.
Now I'm trying to find all my deck,hand and table card, the problem is that it takes so long to execute, even if collection is pretty small.
e.g
{"_id":"5bd3323b1431aa01eed604a8","userID":1,"handData":[{"id":"MLTOG","suit":"Spades","value":5,"face":"5","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"3ZgGQ","suit":"Spades","value":3,"face":"3","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"zdgyN","suit":"Clubs","value":2,"face":"2","userHide":false,"globalHide":false,"hasSuperPower":true},{"id":"oy4CS","suit":"Spades","value":4,"face":"4","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"PgTxA","suit":"Diamonds","value":3,"face":"3","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"zlx6Y","suit":"Diamonds","value":4,"face":"4","userHide":false,"globalHide":false,"hasSuperPower":false}]}

{"_id":"5bd3315f11716c01d3a5a4a4","gameID":"aasd12","deckData":[{"id":"rPd2D","suit":"Diamonds","value":7,"face":"7","userHide":false,"globalHide":false,"hasSuperPower":true},{"id":"ZslMO","suit":"Hearts","value":14,"face":"Ace","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"vJ4j2","suit":"Hearts","value":13,"face":"King","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"sQWuO","suit":"Clubs","value":12,"face":"Queen","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"SV6wb","suit":"Clubs","value":4,"face":"4","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"XGut7","suit":"Hearts","value":4,"face":"4","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"jmiM8","suit":"Hearts","value":3,"face":"3","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"BqQgl","suit":"Hearts","value":7,"face":"7","userHide":false,"globalHide":false,"hasSuperPower":true},{"id":"1sDky","suit":"Hearts","value":6,"face":"6","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"PWTot","suit":"Spades","value":12,"face":"Queen","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"ctBqJ","suit":"Spades","value":10,"face":"10","userHide":false,"globalHide":false,"hasSuperPower":true},{"id":"g7MX1","suit":"Clubs","value":7,"face":"7","userHide":false,"globalHide":false,"hasSuperPower":true},{"id":"voGO8","suit":"Hearts","value":5,"face":"5","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"SeOwQ","suit":"Spades","value":14,"face":"Ace","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"67eKt","suit":"Clubs","value":11,"face":"Jack","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"rBfas","suit":"Spades","value":13,"face":"King","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"xD5X6","suit":"Clubs","value":14,"face":"Ace","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"91yRB","suit":"Diamonds","value":11,"face":"Jack","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"TMbbQ","suit":"Spades","value":7,"face":"7","userHide":false,"globalHide":false,"hasSuperPower":true},{"id":"6NQvl","suit":"Diamonds","value":5,"face":"5","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"0pMrB","suit":"Clubs","value":10,"face":"10","userHide":false,"globalHide":false,"hasSuperPower":true},{"id":"zIMFm","suit":"Hearts","value":12,"face":"Queen","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"KeQNt","suit":"Hearts","value":8,"face":"8","userHide":false,"globalHide":false,"hasSuperPower":true},{"id":"KSxvM","suit":"Clubs","value":8,"face":"8","userHide":false,"globalHide":false,"hasSuperPower":true},{"id":"MaNEM","suit":"Clubs","value":5,"face":"5","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"jU2h3","suit":"Hearts","value":10,"face":"10","userHide":false,"globalHide":false,"hasSuperPower":true},{"id":"VqKOQ","suit":"Diamonds","value":9,"face":"9","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"S0dz2","suit":"Spades","value":2,"face":"2","userHide":false,"globalHide":false,"hasSuperPower":true},{"id":"ehIbj","suit":"Spades","value":6,"face":"6","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"VsDTD","suit":"Diamonds","value":13,"face":"King","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"tmzY9","suit":"Clubs","value":3,"face":"3","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"eSQ8n","suit":"Hearts","value":2,"face":"2","userHide":false,"globalHide":false,"hasSuperPower":true},{"id":"y3fEo","suit":"Clubs","value":9,"face":"9","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"m5EBi","suit":"Diamonds","value":14,"face":"Ace","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"4IFqQ","suit":"Diamonds","value":10,"face":"10","userHide":false,"globalHide":false,"hasSuperPower":true},{"id":"KlGhF","suit":"Spades","value":8,"face":"8","userHide":false,"globalHide":false,"hasSuperPower":true},{"id":"wsLfO","suit":"Diamonds","value":12,"face":"Queen","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"9O44l","suit":"Hearts","value":11,"face":"Jack","userHide":false,"globalHide":false,"hasSuperPower":false},{"id":"H0r9u","suit":"Diamonds","value":6,"face":"6","userHide":false,"globalHide":false,"hasSuperPower":false}]}

The fetch functions are like this, of course the mongoClient connection is not way to go, but im just using this function for testing.
const getDeckCards =  (gameid) =>{
    return new Promise ((resolve,reject) => {
      console.time("deck");
    MongoClient.connect(url, { useNewUrlParser: true }, function (err, client) {
    const db = client.db(dbName);
    const collection = db.collection("deck");
    resolve(collection.find({ gameID: gameid }).project({ _id: 0, gameID: 0 }).toArray());
    });
    console.timeEnd("deck");
  });
  }

  const getHandCards =  (userid) =>{
    return new Promise ((resolve,reject) => {
      console.time("hand");
    MongoClient.connect(url, { useNewUrlParser: true }, function (err, client) {
      const db = client.db(dbName);
    const collection = db.collection("hand");
    resolve(collection.find({ userID: userid }).project({ _id: 0, userID: 0 }).toArray());
    });
    console.timeEnd("hand");
  });
  }

  const getTableCards =  (gameid) =>{

    return new Promise ((resolve,reject) => {
      console.time("table");
    MongoClient.connect(url, { useNewUrlParser: true }, function (err, client) {
      const db = client.db(dbName);
    const collection = db.collection("table");
    resolve(collection.find({ gameID: gameid }).project({ _id: 0, gameID: 0 }).toArray());
    });
    console.timeEnd("table");
  });
  }

I try to get all promises and then return them as array.
const initGame = (async() => {
    console.time("init");
   let [deck,hand,table] = await Promise.all([
      getDeckCards("aasd12"),
      getHandCards(1),
      getTableCards("aasd12")
    ])

    console.timeEnd("init");
    return [deck[0],hand[0],table[0]];
  });

It shows that the deck,hand,table functions were pretty fast, THE result that I'm hoping to get, but the whole result takes 1 second what is incredibly slow for such small querys
deck: 12.235ms
hand: 1.977ms
table: 0.534ms
init: 1058.646ms

What I'm doing wrong? Is it the promise all function that takes soo long to execute or is it problem with my Mongodb query?

A: The problem is that you create a new connection to mongo every time.
The solution is to create a single connection and maintain it alive and close it when is no more needed (when the application is stopping).
This example code will sure have a good impact on your performance:
class GameManager {
  constructor() {
    this.mongoClient = null;
  }

  async connect(dbName) {
    this.mongoClient = await MongoClient.connect(url, { useNewUrlParser: true });
    this.db = this.mongoClient.db(dbName);
  }

  getDeckCards(gameId) {
    if (!this.mongoClient) {
      return Promise.reject();
    }

    return this.db.collection("deck")
      .find({ gameID: gameId })
      .project({ _id: 0, gameID: 0 })
      .toArray();
  }
}

const initGame = () => {
  console.time("init");
  const gameManager = new GameManager();
  return gameManager.connect(dbName)
    .then(() => {
      return Promise.all([
        getDeckCards("aasd12"),
        getHandCards(1),
        getTableCards("aasd12")
      ])
    })
    .then(() => {
      console.timeEnd("init");
    });
};

Remember also to create INDEXes on mongo on those fields you search for (for example the gameID in this case). With this management, you could access data in a faster way.


text:
Q: Spring boot application need to connect weblogic oracle datasource The spring boot application by default is connecting to derby embedded database as shown in the below statement.
Starting embedded database: url='jdbc:derby:memory:testdb;create=true', username='sa'
I don't know where it is picking the above url from
I need to connect weblogic oracle datasource I gave the following properties in the application.properties of the application but its not picking the below properties
spring.jpa.hibernate.ddl-auto=create-drop

# Oracle settings
spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/XE
spring.datasource.username=system
spring.datasource.password=vasu
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

Added the following entry in pom.xml
<dependency>
    <groupId>com.github.noraui</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.2</version>
</dependency>

A: I assume you already have your oracle datasource defined in the weblogic, so you don't need neither oracle driver in your application classpath nor spring.datasource.{url,username,password,driver-class-name} properties defined.
What you need instead is spring.datasource.jndi-name property. Just set it to jndi name of your datasource from weblogic and spring will pickup it just like that.
Of course you have to have an oracle driver in weblogic classpath (lib directory or something like that).
spring.datasource.jndi-name=java:jdbc/OracleDS

Documentation.


text:
Q: How to make mat-form-field Input text slide like marquee There is a long text to be shown inside mat-form-field input. I need the input to work as a HTML marquee. Which means text inside input should slide horizontally to left. Here is the code of my input field.
 <div class="col-xs-2 col-sm-2 col-md-2 col-lg-2">
  <mat-form-field appearance="none">
    <mat-label>Check In/Check Out</mat-label>

    <input style="max-width: 82%;" matInput placeholder="Check In" readonly="readonly" [(ngModel)]="CheckIn">
  </mat-form-field>
</div>


text:
Q: setBackgroundDrawable is throwing NullPointerException in creating Android Custom ActionBar I am getting NullPointerException on setBackgroundDrawable while creating the Custom ActionBar.
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    ActionBar actionBar = getActionBar();
    Bitmap b = BitmapFactory.decodeResource(getResources(),
            R.drawable.ic_launcher);

    actionBar.setBackgroundDrawable(new BitmapDrawable(getResources(), b));
    actionBar.setCustomView(R.layout.actionbar_view);

LogCat results are as follows:
Caused by: java.lang.NullPointerException
        at actionbarcustomview.practice.nkd.actionbarcustomviews.MainActivity.onCreate(MainActivity.java:30)
        at android.app.Activity.performCreate(Activity.java:4465)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)

Line 30 is
actionBar.setBackgroundDrawable(new BitmapDrawable(getResources(), b));

I am using Android Studio and configs are
    defaultConfig {
    applicationId "actionbarcustomview.practice.nkd.actionbarcustomviews"
    minSdkVersion 17
    targetSdkVersion 21
    versionCode 1
    versionName "1.0"
}

Please help me to fix this problem.

A: Here is a blog post that should help:
http://blog.perpetumdesign.com/2011/08/strange-case-of-dr-action-and-mr-bar.html
The problem is that ActionBar actionBar = getActionBar(); returns null.


text:
Q: Table cell button issue I am facing an issue with a button set in a table cell which covers two rows. it does not fill the second row. how can i make this button fill both rows? I have tried to set height in the style of the button as well as on the table cell itself without success. Please see my code is below:
1) the css style of the button:
.button {
    padding: 5px 15px;
    font-size: 1.1em;
    cursor: pointer;
    text-align: center;
    text-decoration: none;
    outline: none;
    color: #fff;
    background-color: #4CAF50;
    border: none;
    border-radius: 1px;
    box-shadow: 0 2px #999;
    width: 100%;
    vertical-align: middle;
}

And 2) my html table below:

        <button href="#0" class="button" id="cancel_order">Aκύρωση</button>

        <button class="button">Εκτύπωση</button>

        <button class="button">Παραγγελία</button>

        <button class="button">Απόδειξη</button>

A: https://jsfiddle.net/k5wefqz5/1/
Is this your expected result ?
You miss
 tag to complete your code.

A: Add this:
button {height:100%; }

Wrap table elements inside a
 in order to get  and
 to behave as expected.
SNIPPET

table {
  border: 1px solid red;
}
td {
  border: 1px solid black;
}
button {
  height: 100%;
}

      <button href="#0" class="button" id="cancel_order">Aκύρωση</button>

      <button class="button">Εκτύπωση</button>

      <button class="button">Παραγγελία</button>

      <button class="button">Απόδειξη</button>

A: In my opinion you should use css3 flexbox to achieve this as shown below:

.btn-holder {
  display: flex;
}

.btn-holder .btn-holder {
  flex-direction: column;
}

.button {
  margin: 0 5px 5px 0;
  padding: 5px 15px;
  font-size: 1.1em;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  outline: none;
  color: #fff;
  background-color: #4CAF50;
  border: none;
  border-radius: 1px;
  box-shadow: 0 2px #999;
}

  <button class="button" id="cancel_order">Aκύρωση</button>

    <button class="button">Εκτύπωση</button>
    <button class="button">Παραγγελία</button>

  <button class="button">Απόδειξη</button>


text:
Q: Save chart from screen device to png with R function I have a problem with all screen device packages. I would like creating a function that save plot to png file. My first aproximation as such as this:
   File <- function(plot){
   library(ggplot2)
    png(filename=paste0(deparse(substitute(plot)), width=800, height=600,units = "px")
    plot
    dev.off()
   }

But the script returns a completely black png file. If execute the code manual, the script function.
Are there any method to make it work?


text:
Q: Laplace's method with nontrivial parameter dependency I need to approximate the following integral using Laplace's method:
$$
\int_0^{\infty} \frac{x^{\lambda} \lambda^{-x}}{(1+x^2)^\lambda} dx \\ =
\int_0^{\infty} \exp\left(\lambda \log(x) - x\log(\lambda)-\lambda \log(1+x^2)\right) dx
$$
as $\lambda \to \infty$. However, I cannot directly apply Laplace's method as there's an untrivial dependency on $\lambda$. So I guess I need to do some change of variables or something like that but I didn't come up with anything useful.

A: The "method" version of the Laplace method can be applied directly with some care.
The basic intuition is that the factor $\lambda^{-x}$ does not vary much in the region dominated by the saddle point coming from the other factor $x^\lambda/(1+x^2)^\lambda$.  Away from the saddle point, $\lambda^{-x}$ is dominated by the the exponential smallness coming from $x^\lambda/(1+x^2)^\lambda$.
We begin by writing
$$
\frac{x^\lambda}{(1+x^2)^{\lambda}} = \exp\!\left[\lambda \log\!\left(\frac{x}{1+x^2}\right)\right] = e^{\lambda \varphi(x)}.
$$
The function $\varphi(x)$ has a maximum at $x = 1$, and near there we have
$$
\varphi(x) = -\log 2 - \frac{1}{2}(x-1)^2 + O((x-1)^3),
$$
so the width of the interval in which this critical point contributes to the integral is on the order of $1/\sqrt{\lambda}$.  To give ourselves some breathing room we'll consider the slightly larger interval $(1-\lambda^{-1/4},1+\lambda^{-1/4})$.  We thus split the integral as
$$
\int_0^{\infty} e^{\lambda \varphi(x)}\lambda^{-x} \,dx = \int_{1-\lambda^{-1/4}}^{1+\lambda^{-1/4}} e^{\lambda \varphi(x)}\lambda^{-x}\,dx + \left( \int_0^{1-\lambda^{-1/4}} + \int_{1+\lambda^{-1/4}}^\infty \right) e^{\lambda \varphi(x)}\lambda^{-x}\,dx.
$$
We'll first bound these last two integrals.  To bound the first we proceed like
$$
\begin{align}
\int_0^{1-\lambda^{-1/4}} e^{\lambda \varphi(x)}\lambda^{-x}\,dx &< \left. \frac{x^{\lambda}}{(1+x^2)^\lambda} \right|_{x = 1-\lambda^{-1/4}} \int_0^\infty \lambda^{-x}\,dx \\
&= \frac{2^{-\lambda}}{\log \lambda} \left(1 - \lambda^{-1/4}\right)^\lambda \left(1 - \lambda^{-1/4} + \frac{1}{2}\lambda^{-1/2}\right)^{-\lambda} \\
&= \frac{2^{-\lambda}}{\log \lambda} \exp\!\left[-\frac{1}{2}\lambda^{1/2} + O(\lambda^{1/4})\right]
\tag{1}
\end{align}
$$
as $\lambda \to \infty$.  For the second we have
$$
\begin{align}
\int_{1+\lambda^{-1/4}}^\infty e^{\lambda \varphi(x)}\lambda^{-x}\,dx &< \left. \frac{x^{\lambda}}{(1+x^2)^\lambda} \right|_{x = 1+\lambda^{-1/4}} \int_0^\infty \lambda^{-x}\,dx \\
&= \frac{2^{-\lambda}}{\log \lambda} \exp\!\left[-\frac{1}{2}\lambda^{1/2} + O(\lambda^{1/4})\right]
\tag{2}
\end{align}
$$
also as $\lambda \to \infty$.
For $x$ in the interval $(1-\lambda^{-1/4},1+\lambda^{1/4})$ we have
$$
\lambda^{-x} = \lambda^{-1} \sum_{k=0}^{\infty} \frac{(\log \lambda)^k}{k!} (1-x)^k
$$
uniformly in $x$.  It follows that
$$
\int_{1-\lambda^{-1/4}}^{1+\lambda^{-1/4}} e^{\lambda \varphi(x)}\lambda^{-x}\,dx = \lambda^{-1} \sum_{k=0}^{\infty} \frac{(\log \lambda)^k}{k!} \int_{1-\lambda^{-1/4}}^{1+\lambda^{-1/4}} e^{\lambda \varphi(x)} (1-x)^k\,dx. \tag{3}
$$
Using the usual techniques associated with the Laplace method we can then calculate asymptotic series for each of these these integrals then recombine them to conclude that we have an asymptotic series of the form
$$
\int_{1-\lambda^{-1/4}}^{1+\lambda^{-1/4}} e^{\lambda \varphi(x)}\lambda^{-x}\,dx \approx \lambda^{-3/2} 2^{-\lambda} \sum_{j=0}^{\infty} \lambda^{-j} \sum_{k=0}^{2j} c_{j,k} (\log \lambda)^k,
$$
valid as $\lambda \to \infty$.  The estimates in $(1)$ and $(2)$ are exponentially small compared to this, so we obtain for the original integral
$$
\int_0^{\infty} e^{\lambda \varphi(x)}\lambda^{-x} \,dx \approx \lambda^{-3/2} 2^{-\lambda} \sum_{j=0}^{\infty} \lambda^{-j} \sum_{k=0}^{2j} c_{j,k} (\log \lambda)^k.
$$

In particular we have the leading order behavior
  $$
\int_0^{\infty} \frac{x^\lambda \lambda^{-x}}{(1+x^2)^\lambda} \,dx \sim \int_{-\infty}^{\infty} e^{-\lambda \log 2 - \lambda/2 (x-1)^2} \lambda^{-1}\,dx = \sqrt{2\pi} \lambda^{-3/2} 2^{-\lambda}
$$
  as $\lambda \to \infty$.

The next few terms of the asymptotic series can be computed directly from $(3)$ - we get
$$
\begin{align}
&\int_0^{\infty} \frac{x^\lambda \lambda^{-x}}{(1+x^2)^\lambda} \\
&\quad = \sqrt{2\pi} \lambda^{-3/2} 2^{-\lambda} \left( 1 + \frac{2(\log\lambda)^2 - 6\log\lambda + 3}{4\lambda} \right. \\
&\qquad\qquad \left. + \frac{4(\log\lambda)^4 - 40(\log\lambda)^3 + 120(\log\lambda)^2 - 120\log\lambda + 25}{32\lambda^2} + \cdots \right)
\end{align}
$$

A: I think you can't apply the Laplace Method directly, at least no in the strong form described in the first equation here: Real approximation to the maximum using Laplace's method integral. If the goal is to compute the limit of the integral you can first bound the integral:
$$
\int_0^{\infty} \frac{x^{\lambda} \lambda^{-x}}{(1+x^2)^\lambda} dx < \int_0^{\infty} \frac{x^{\lambda}}{(1+x^2)^\lambda} dx
$$
Then  do the proposed manipulation:
$$ \int_0^{\infty} \exp\left(\lambda (\log(x) - \log(1+x^2))\right) dx$$
and only then apply the Laplace method.
At this point is looks rather trivial because the argument of the exponential is always negative. That is $M = \max(\log(x) - \log(1+x^2)) < 0$, but let's continue.
Laplace Method tells that the limit of the integral is proportional to $\sqrt{2\pi/\lambda}\exp(\lambda M)$ times a constant that depends on the curvature at the maximum (which is finite). Since $M$ is negative the limit is 0. The integral is positive and bounded by a function that tends to zero. So the answer is zero.
The maximum is $M = -\log(2)$ at $x_0 = 1$ and the second derivative is $-1$.
Therefore a naive or weak form of the Laplace Method (but probably correct) points to the following approximation of the original integral:
$$
\int_0^{\infty} \frac{x^{\lambda} \lambda^{-x}}{(1+x^2)^\lambda} dx \simeq \sqrt{\frac{2\pi}{\lambda}} \lambda^{-1} 2^{-\lambda}
$$
Althougt at first guess, I think that since the kernel function depends on $\lambda$ the order of the approximation is worst than the normal $O(\exp(-\lambda))$ (see below however).

For what it is worth, the original integral can be done exactly.
$$
-\frac{\log (\lambda ) \Gamma \left(\frac{\lambda }{2}-1\right) \Gamma \left(\frac{\lambda
   }{2}+1\right) \, _1F_2\left(\frac{\lambda }{2}+1;\frac{3}{2},2-\frac{\lambda }{2};-\frac{1}{4}
   \log ^2(\lambda )\right)}{2 \Gamma (\lambda )}+\frac{\sqrt{\pi } 2^{-\lambda } \Gamma
   \left(\frac{\lambda -1}{2}\right) \, _1F_2\left(\frac{\lambda
   }{2}+\frac{1}{2};\frac{1}{2},\frac{3}{2}-\frac{\lambda }{2};-\frac{1}{4} \log ^2(\lambda
   )\right)}{\Gamma \left(\frac{\lambda }{2}\right)}+\frac{\pi  \log ^{\lambda -1}(\lambda ) \csc
   (\pi  \lambda ) \, _1F_2\left(\lambda ;\frac{\lambda }{2}+\frac{1}{2},\frac{\lambda
   }{2};-\frac{1}{4} \log ^2(\lambda )\right)}{\Gamma (\lambda )}
$$
(source: symbolic Mathematica) and the limit is zero (source: numeric Mathematica). Additionally, numerically it seems that the order of the approximation analytically obtained above is actually worst than exponential but better than polynomial.

Error estimation: As per my conversation with @AntonioVargas and my numerical experiments, the error is confirmed to be indeed larger than the one expected from the Laplace Method:
$$
\int = \sqrt{2\pi}\lambda^{-3/2}2^{-\lambda} + O(\lambda^{-5/2}2^{-\lambda}\log^2\lambda)
$$
The other answer shows all the explicit terms up to order $O(\lambda^{-7/4})$.


text:
Q: How to implement save/load functionality of Java application data/state? I have an application of POJOs (plain old java objects) representing my data.
While running, the application manipulates and remembers data as desired.
Now I want to implement a save/load feature.

I am NOT asking about basic file I/O.
I am NOT asking whether ObjectOutputStream exists.

Options I have found are those such as:
1) JSON/XML/YAML libraries such as Gson, Jackson
2) Roll your own binary file format marking everything as Serializable with a Serialization Proxy pattern.
Option 1 is unsuitable because my data model can feature cyclic references. Gson resulted in a stack overflow.
Option 2 is unsuitable because the files should be cross platform and independent of JVM; it should work on desktop and android java.
A properties file is also obviously unsuitable due to the complexity of the model.

Please do not attack my use case; my data model is perfectly well designed. The example may not be.
I will now give example code of the kind of structure that needs to be saved.
class Application {

    //This College is my top level object. It could correspond to an individual save file.
    College college = new College();

    //I would love to be able to just throw this guy into a file.
    SomeLibrary.writeToFile(college);
    //And read another back.
    College college2 = SomeLibrary.readFromFile(anotherCollege);
}

class College {
    //The trees are implemented recursively, so this is actually just the root of each tree.
    Tree<Course> artCourseTree;
    Tree<Course> engineeringCourseTree;
    Tree<Course> businessCourseTree;

    List<Student> maleStudents;
    List<Student> femaleStudents;
}

class Course {
    //Each course only has 2 students in this example. Ignore.
    Student student1;
    Student student2;

    List<Exam> examsInCourse;
    LocalDate courseStartDate;
    Period duration;
}

class Student {
    String name;
    List<Exam> listOfExamsTaken;
}

class Exam {
    Student studentTakingIt;
    LocalDate dateTaken;
    BigDecimal score;
}

As you can see, Exams are intended to be the atomic object in this model at the bottom of the hierarchy. However, not only are they referenced by both Students and Courses, but they also refer back up to a Student and contain nonprimitives such as LocalDate and BigDecimal. The model is given meaning by referencing different subsets of Exams in different Courses and Students.
I need to save the relationships, the arrangement of these things, an arbitrary number of these things, as well as the data they hold.
What hope do I have of saving and loading such a model?
What options are there to implement a save/load feature on such a model, with such constraints?

Is it really industry standard for every java program to roll its own binary file format and create a monstrous apparatus to serialize and deserialize everything? It's that or JSON? What am I missing here? Do I have to just snapshot the VM somehow? Why is there not a standard practice for this?

A: Circular references is a common use case and can be handled by providing @JsonManagedReference or @JsonBackReference. Check out this SO answer for more details. Another option is to implement custom serializer and solve circular references by yourself. Here is the example for the same.
However, do consider the following aspects before going ahead with using files as database

*

*You will have to manage concurrent writes by yourself. If not correctly handled might result in corruption/loss of the data because files are not ACID compliant by nature.

*The solution is not scalable as file size will grow. Time to serialize and deserialize will increase proportionately.

*You won't be able to query easily on the data stored in the file. You will always have to deserialize data first and then query on POJOs.

I'll highly recommend checking SQLite which is small, fast, self-contained, high-reliability, full-featured, SQL database engine.


text:
Q: react native getting a error as this.setState is not a function hi there i"m new to react native during my built process i am getting this error
this.setState is not a function
and my code
type Props = {};
export default class App extends Component<Props> {

componentDidMount(){
 Proximity.addListener(this._proximityListener);
}
 _proximityListener(data) {
   this.setState({
     proximity: data.proximity,
     distance: data.distance // Android-only
   });
 }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
            00
        </Text>
      </View>
    );
  }
}

how to solve this error ? .,

A: Turn your _proximityListener function into an arrow function like this:
_proximityListener = (data) => {...
This will bind the method to the class and give that method access to the 'this' keyword. :)

A: Change your componentDidMount function to
componentDidMount(){
  Proximity.addListener(this._proximityListener.bind(this));
}


text:
Q: Using ubiquity for the Full disk encrypted install to disk on /dev/sdb instead of /dev/sda Last week I got a brand new Dell M3800 for work with Ubuntu 14.04 preinstalled. However, since the company has a disk encryption policy I needed to reinstall Ubuntu with encryption enabled. However when trying to reinstall with encryption on the SSD (which contained the preinstalled OS) using the created Dell recovery image, the installation failed. I also tried with Ubuntu 14.04.3 Live-CD (on USB-stick) and ubiquity crashed. I have now reached the conclusion that it is due to my extra HDD (unformatted) located on /dev/sda.
After a lot of headache and trial-and-error I happened to see that ubiquity crashed when trying to run "grub-install /dev/sda" (despite the fact that I had told it to install FDE on /dev/sdb). I know that I can choose /boot to be wherever I want (such as on the EFI partition on /dev/sdb) if I choose the advanced install. But, can I also in ubiquity's advanced install create the encrypted partitions (/, swap) so that it gets the same structure as if I would only have had one disk plugged in (i.e. the default for ubuntu installs with FDE)? If prepping the partitions manually in advance to installing is the only option then of course such answers are also more than welcome!
Thanks!

As per @oldfreds suggestion before focusing on the ubiquity bug I also have a pastebin of my boot info of the failed encrypted install from the Dell recovery iso.

A: If installing Ubuntu in UEFI boot mode to a second drive, either internal or external as full install, you need to have drive seen as sda gpt partitioned with an ESP - efi system partition, FAT32 formatted with boot flag, 100 to 500MB. You also want an ESP on the drive you install Ubuntu, but it may not be used, during install. Best to copy ESP boot files back to install drive if sda drive ever fails/is removed or other issues.
Grub seems to only want to install its UEFI boot files to an ESP on drive seen as sda. It may even say during install, installing to sdb, but will error out if no ESP on sda. Can be a bigger issue on a few systems where install flash drive is seen as sda.
Once you start using UEFI, best that all drives be gpt and every drive with an install has an ESP partition near beginning of drive. Since I also suggest an install on every drive, then every drive should have an ESP, even if just for future use.
Update for removeable drives:
Two drive or any second, external or other drive than sda.
Note that full install to any drive other than sda in UEFI mode has some issues. Grub only installs to the ESP - efi system partition on sda. And you then have to copy files to your install.
And Ubuntu's UEFI grub only installs to the ESP on sda, or not the external drive and not to /EFI/Boot/bootx64.efi. For my PC UEFI full install to a flash drive I manually copied /EFI/ubuntu on sda's ESP to flash drive's ESP. Then copied it again to /EFI/Boot and renamed shimx64.efi to bootx64.efi. I then updated fstab to have correct UUID for ESP on external drive.
The version of grub in a full install is hard coded to find the rest of grub in /EFI/ubuntu so both copies are required. There are ways to directly install grub as bootx64.efi, but then you have to manually maintain grub.cfg.
And if you do not want UEFI entries on internal drive, after copying entries to external:
How do I remove "Ubuntu" in the bios boot menu? (UEFI)


text:
Q: Windows API to make Windows Vista and 7 semi-transparent screenshots Windows Vista and Windows 7 display semi-transparent forms when Aero is activated. And some screen-taking applications such as WinSnap or Windows Clippings are able to capture those windows as a semi-transparent PNG image. What Windows API are they using to obtain such a beautiful capture ?

A: There isn't any, to my knowledge. If you look closely, at least WindowClippings takes two separate screenshots. One with white background and one with black background. It then uses those two screenshots to calculate the transparency of the glass pixels.


text:
Q: Edge Extension with NativeMessaging I have an edge extension with native messaging support where it communicates with uwp application running in the system. Is it mandatory to have extension packaged within the appx folder of uwp app. if not then how can we upload the extension in edge extension store.
I followed the secureInput sample:
https://github.com/MicrosoftEdge/MicrosoftEdge-Extensions-Demos/tree/master/SecureInput
They are putting extension within the Appx folder of UWP application. how will I upload extension in edge extension store.

A: To make an Extension communicate with a UWP App - the Extension and certain runtime components of UWP has to be packaged in the same Appx Package. Please read the documentation here: https://learn.microsoft.com/en-us/microsoft-edge/extensions/guides/native-messaging
Also, it will be much easier to create a Store eligible package through Visual Studio.


text:
Q: Update database table with changes made to DataTable I'm trying to update a column and delete the row that follows it in a DataTable retrieved from sql table, whenever the column equals a value and the same column in the row which follows starts with another value.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
        SqlDataAdapter adapter = new SqlDataAdapter("SELECT * from tbl_Copy_Journal", con);
        DataSet Journals = new DataSet();
        adapter.Fill(Journals, "tbl_Copy_Journal");
        foreach (DataTable table in Journals.Tables)
        {
            for (int i = 0; i < Journals.Tables[0].Rows.Count; i++)
            {
                String action = Journals.Tables[0].Rows[i]["Action"].ToString();
                if (action == "reading dispensed")
                {

                    String action1= Journals.Tables[0].Rows[i+1]["Action"].ToString();
                    if (action1.StartsWith("Referred"))
                    {

                        String _Action = Journals.Tables[0].Rows[i]["Action"].ToString() + ", " + Journals.Tables[0].Rows[i + 1]["Action"].ToString();
                        Journals.Tables[0].Rows[i + 1].Delete();
                        Journals.Tables[0].Rows[i]["Action"] = _Action;
                    }
                    adapter.Update(Journals, "tbl_Copy_Journal");
                    Journals.AcceptChanges();
                }

            }
        }

The code returns Update requires a valid UpdateCommand when passed DataRow collection with modified rows.
Is there a way to delete and update rows in datatable and to fix this code. Any help is appreciated.

A: You fix it by doing what they ask.  Supply the UpdateCommand.


text:
Q: PHP Parse Date From String I received a date string from API respond like this

"2013-07-09T04:58:23.075Z"

How can I parse that string, say to change format to

2013-07-09 [04:58:23]

The time indeed is not based on my local time, I think the .075Z should change something about the time.
Thanks in advance for your help.

A: try this
$date = '2013-07-09T04:58:23.075Z';
$seconds = strtotime($date);

echo date('Y-m-d [H:i:s]', $seconds);

Hope it helps!

A: You can do that using the DateTime object.
$Date = new DateTime('2013-07-09T04:58:23.075Z'); //create dateTime object
$Date->setTimezone(new DateTimeZone('Europe/Amsterdam')); //set the timezone

echo $Date->format('d/m/Y H:i');

A: $time = "2013-07-09T04:58:23.075Z";
$exp = explode('T',$time);
echo $exp[0] .' [' .substr($exp[1], 0, -5) . ']';

I'm using it like this.

A: @Benz
simply add below:

date_default_timezone_set('Australia/Brisbane');

echo date('d/m/Y H:i', strtotime('2013-07-09T04:58:23.075Z'));

were done! Hope this help.


text:
Q: Find factorial Using call by reference function in C++ I am missing very minor thing here i could not figure it out, i am just try to get the factorial of the number inputted, using a recursive call by reference concept in C++.
Please let me know what am i missing. Declaring few additional variables for more further alterations in programs.
#include <iostream>
using namespace std;
int factorial(int &m);
int factorial(int &m)
{
    int i,result=0;

    if(m>=1)
    return  m * factorial(m-1);
    else
        return 0;

}

int main(){

    int m,i,factorial1=1;

    cout<<"Please enter the number to factor   "<<std::endl;
    cin>>m;
    factorial1=factorial(m);

    cout<<"Factorial value is " << factorial1<<std::endl;
    return 0;
    }

Getting error as below
factorial_func.cc: In function 'int factorial(int&)':
factorial_func.cc:33:25: error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'
   33 |  return m * factorial((m-1));
      |                       ~~^~~
factorial_func.cc:27:20: note:   initializing argument 1 of 'int factorial(int&)'
   27 | int factorial(int &m)
      |               ~~~~~^

A: The errors in your program:

*

*It tries to bind a non-constant lvalue (roughly it means a variable that could be assigned in the left hand side of = sign) reference of type an integer reference (from argument) to an rvalue of an integer in the syntax:
return  m * factorial(m - 1);

*Passing a reference is not required here at all. You may remove &.

*The else statement returns a zero instead of one when the m is lesser than 1 and that gives you unexpected output since any multiplication operation with a zero is always a zero.
You should try:

*

*Returning an integer from the argument directly rather than returning a reference value.

*You must return 1 instead of 0 when m reaches lesser than 1 in the else condition.

*The variables declared in factorial() are totally unused and redundant and i is unused in main().

Code redefined:
#include <iostream>

int factorial(int param) {
    if (param >= 1)
        return param * factorial(param - 1); // new * (-1 than new) recursively
    else
        return 1;
}

int main(void) {
    int fact = 1;
    int num;

    std::cout << "Please enter the number to factor: ";
    std::cin >> num;

    fact = factorial(num);

    std::cout << "Factorial is: " << fact << std::endl;

    return 0;
}

After fixing the errors, you'll get output like:
$ g++ -o prog prog.cpp; ./prog
Please enter the number to factor: 5 // --- INPUT
Factorial is: 120 // --- OUTPUT

A: Dude's answer is correct, there is no need to apply an lvalue ref as argument, a pass by (r)value is correct, this applies as general advice for recursive functionality to avoid side effects.
More serious is a fault: factorial of 0 is not 0, but by definition it is 1 !!!
Whether this sounds illogical, see the discussion on https://www.quora.com/Why-does-zero-factorial-0-equal-one-1-1
@Dorian: It's easy to spare 2 recursive calls by tackling the factorials of 0 1 2:
int factorial(int m)
{
    if (m > 2)
        return  m * factorial(m - 1);
    else if (m == 0)
        m = 1;
    return m;
}

A: Here's your working code.
Some tipps:

*

*why not use using namespace std

*You need to pass 1 in the last factorial, otherwise your result is multiplied by 0 and that's 0, so it won't work

*if you only pass single ints, you can pass them easier by value (gives you less problems in the beginning).
BUT: in any case passing by reference here is wrong, because you don't want the original value to change, but in recursion you want to have a RETURN value.

*regarding you original error: you are trying to bind an rvalue (a value that stands ONLY on the right side of an equation) to an lvalue reference (&m), which you cannot do, since if you are changing the lvalue reference, you cannot change the right side of the equation. You can use rvalue references (&&m), but this is quite advance C++ and you should maybe read up here first to get an idea of what you are dealing with.
#include <iostream>
int factorial(int m);
int factorial(int m)
{
    if (m >= 1)
       return  m * factorial(m-1);
    else
       return 1;

}

int main(){

    int m, factorial1 = 1;

    std::cout << "Please enter the number to factor" <<std::endl;
    std::cin >> m;
    factorial1=factorial(m);

    std::cout<<"Factorial value is " << factorial1 << std::endl;
    return 0;
}


text:
Q: How to find if any of elements within an array are within range between 50 and 99 in JavaScript? This is given array:
var a = [2, 5, 8, 16, 35, 42, 55, 67, 89, 95, 102, 108, 112];

How to find if ANY of the elements from the array a are within range of 50 to 99? To return true if ANY of these elements are within range 50 to 99, and false if not!
How to find if ALL of the elements of this array a are within range of 50 to 99? To return true if ALL of these elements are within range 50 to 99 and false if at least one element is outside this range!

A: Array#some() and Array#every()

var a = [2, 5, 8, 16, 35, 42, 55, 67, 89, 95, 102, 108, 112];

console.log("some", a.some(value => value > 50 && value < 99));
console.log("every", a.every(value => value > 50 && value < 99));

also check out the other array methods.

A: You can use arrays functions some and every for this.
In this solution I assumed that 50 and 99 are inclusive and they are also valid values.

How to find if ANY of the elements from the array a are within range
of 50 to 99? To return true if ANY of these elements are within range
50 to 99, and false if not!

You can use .some()
a.some((x) => x >= 50 && x <= 99)

How to find if ALL of the elements of this array a are within range of
50 to 99? To return true if ALL of these elements are within range 50
to 99 and false if at least one element is outside this range!

You can use .every()
a.every((x) => x >= 50 && x <= 99)

var a = [2, 5, 8, 16, 35, 42, 55, 67, 89, 95, 102, 108, 112];

console.log(a.some((x) => x >= 50 && x <= 99));
console.log(a.every((x) => x >= 50 && x <= 99));

Here you can read more

*

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

A:

var a = [2, 5, 8, 16, 35, 42, 55, 67, 89, 95, 102, 108, 112];

//if at least one element in the range of 50 and 99
console.log(a.filter(e => e >= 50 && e <= 99).length > 0)

//if all elements are in the range of 50 and 99
console.log(a.filter(e => e >= 50 && e <= 99).length === a.length)

A: You can you some and every.

const A = [2, 5, 8, 16, 35, 42, 55, 67, 89, 95, 102, 108, 112];

console.log('#1 ', A.some(element => element > 50 && element < 99))

console.log('#2 ', A.every(element => element > 50 && element < 99))


text:
Q: Comparing two different types with Entity Framework Assume I have a Posts table with field Owner of type Person (which has field Name).
I'm trying to make this shorthand expression work:
from p in Posts where p.Author == "SomeNameAsString" select p;

Which means I would have to compare object of type Person with a string.
I tried to override Equals and to override operators == and !=, but I'm still getting exception "DbComparisonExpression requires arguments with comparable types.".
Is there a way to make two different types comparable in Entity Framework?

A: EF tries to translate your query into SQL, and while doing that it doesn't seem to take into account your type conversion operators. Simply use this query instead:
from p in Posts where p.Author.Name == "SomeNameAsString" select p;

A: Have you tried
 from p in Posts where p.Author.Name == "SomeNameAsString" select p;

(if Name is a property on Author)


text:
Q: Python ModuleNotFoundError: No module named ''' I want to import a file from subdir and I get an error like that:

ModuleNotFoundError: No module named 'special'

│
├── constants.py
├── crawler.py
├── case.py ===================>>>> I working on this file
├── special
    ├── __init__.py
    └── wantToImport.py =================>>>I want to import this file

My case.py like that:
from special.wantToImport import ImportClass

And my wantToImport.py file like that:
class ImportClass:

    def mydefination(self):
        #Some codes here

I want to use mydefinitioon function on my case.py file But I cannot import this file.
Why Im getting this error?
How can I solve this?

A: You should tell Python that your module's path is inside the current directory (using a .):
from .special.wantToImport import ImportClass

A: Try creating a __init__.py file in the directory where you are working and use it to refer your module.
│
root
├── constants.py
├── crawler.py
├── case.py ===================>>>> I working on this file
├── __init__.py
├── special
    ├── __init__.py
    └── wantToImport.py =================>>>I want to import this file

inport it using
from root.special.wantToImport import ImportClass


text:
Q: inserting into a set which is part of map  > I created a map containing a set as a value, but now I'm stuck on how to add the values into the set.
map <int, set<string> > myMap;

I tried something like this and it works fine, but it's useless for me, because I fill the set in the loop (so every set contains all values from the sets before, which is not what I what I'm looking for).
set <string> mySet;

while ( expression )
{
mySet.insert(str);
myMap.insert ( pair<int, set<string> > (myNumber, mySet) );
}

A:     #include <map>
    #include <set>
    #include <string>
    #include <iostream>

    int main(int argc,char** argv)
    {
        typedef std::map <int, std::set<std::string> > maptype;
        maptype myMap;

       myMap[rand()%100].insert("susan");
       myMap[rand()%100].insert("bob");
       myMap[rand()%100].insert("bill");

       for (maptype::iterator it = myMap.begin(); it != myMap.end(); ++it)
       {
           std::cout << it->first << ",";
           const std::set<std::string>& set = it->second;

           for (std::set<std::string>::iterator setit = set.begin();
                setit != set.end();
                ++setit)
           {
               std::cout << *setit << ",";
           }
           std::cout << std::endl;
       }
    }


text:
Q: Promela - non-determinism not non-deterministic? Consider this snippet:
chan sel = [0] of {int};

active proctype Selector(){
    int not_me;

    endselector:
    do
    ::  sel ? not_me;
        if
        :: 0 != not_me -> sel ! 0;
        :: 1 != not_me -> sel ! 1;
        :: 2 != not_me -> sel ! 2;
        :: 3 != not_me -> sel ! 3;
        :: else -> -1;
        fi

    od
}

proctype H(){
    int i = -1;
    int count = 1000;
    do
    :: sel ! i; sel ? i; printf("currently selected: %d\n",i); count = count -1;
    :: count < 0 -> break;
    od

    assert(false);
}

init{
    atomic{
        run H();
    }
}

You'd expect this to print pretty the values 0..3 pretty arbitrarily until the counter falls below 0, at which point it can either print another number or it will terminate.
However, that doesn't seem to be the case.
The only values returned are 0, then 1, then 0, then 1, then 0, then 1, ...
Did I somehow misunderstand the "non-determinism" of the if/fi statements?
(using ispin on ubuntu, if that matters).

A: Relevant part of language spec. Seems non-determinstic to me.
If you're looking at (a few) traces of the system only, then you're at the mercy of the (pseudo) random generator.
I thought the main purpose of SPIN is to prove properties. So, you could write a formula F that describes the trace(s) that you want, and then have SPIN check that "system and F" has a model.

A: If you are running Spin in 'simulation' mode, then the else options are visited deterministically, I believe.  So in the Selector proctype, the simulation proceeds in the if by checking the options as: 0 ~= not_me and then the 1, 2, 3 options.  For your execution, you thus ping pong between 0 and 1.
You can confirm this, by replacing your if statement with:
if
:: 0 != not_me -> sel ! 0;
:: 1 != not_me -> sel ! 1;
:: else -> assert(false)
fi

and your simulation will never reach the assert.
Spin can also be run in 'verification' mode - generate a pan executable and execute that.  Then, all cases will be visited (modulo limits in memory and time).  However, in 'verification' mode nothing is printed out - so you might be hard pressed to see the other cases!


text:
Q: Remotely access my computer's framebuffer console from Android I need to remotely view my computer's display.
I am using programs that I launch from a text console, then they create their own graphical session, like Kodi or EmulationStation (it does not start if X is running). And because they don't use the X server's framebuffer VNC can't capture them.
I tried using VNC (tightvnc and x11vnc), but nearly none of my applications use the X window system.
For the client I want to use an Android device.

A: You're probably using something which uses the framebuffer directly, without using X. It is not possible to display such things remotely.
I don't know this emulationstation thing, but I can say that kodi works just fine with an X server. Also, it has its own android remote app which is a more useful way of controlling it from android; you might want to look at that instead.

A: If you're not using X, what are you using?
For text-only/shell display, ssh is the way to go. For X, you have two options: remote display by changing your display to a network location with an X server, or VNC.
You can also try proprietary solutions, for example TeamViewer, which supports android clients: https://www.teamviewer.com/en/index.aspx
EDIT: There are reports from people that hint that TeamViewer may capture the framebuffer: http://forums.anandtech.com/showthread.php?t=2293900


text:
Q: Flask Web App: Filter table view by button I would like to be able to filter the table in this html page by button, i.e domain. Check here Html View. For example if someone clicks on photographer only photographers show up.
Flask function:
@app.route('/find_artist',methods=['POST', 'GET'])
def find_artist():
    if session.get("email"):
        if request.method == 'GET':
            return render_template('find_artist.html')
        curl = mysql.connection.cursor()
        curl.execute("SELECT * FROM freelancers")
        data = curl.fetchall()
        curl.close()
        return render_template(
            "find_artist.html",
            freelancers=data)
    else:
        return redirect(url_for('login'))

HTML code for buttons and table:

  <button class="btn active" > Show all</button>
  <button class="btn" > Illustrator</button>
  <button class="btn"> Animator</button>
  <button class="btn" > Digital Designer</button>
  <button class="btn">Photographer</button>
  <button class="btn"> Filmmaker</button>
  <button class="btn"> Graphic Design</button>

          Serial
          First Name
          Last Name
          Email
          Domain
          Experience

        {% for item in freelancers %}

          {{item["id"]}}
          {{item["first_name"]}}
          {{item["last_name"]}}
          {{item["email"]}}
          {{item["domain"]}}
          {{item["experience"]}}

        {% endfor %}

Thank you :)

A: The solution that worked for me is to create a separate endpoint for each button.
def multiple_buttons(condition):
    if session.get("email"):
        curl = mysql.connection.cursor()
        curl.execute("SELECT * FROM freelancers WHERE domain LIKE %s", [condition])
        data = curl.fetchall()
        curl.close()
        return render_template(
            "find_artist.html",
            freelancers=data)
    else:
        return redirect(url_for('login'))

@app.route('/showall',methods=['POST'])
def showall():
    return multiple_buttons(None)

@app.route('/illustrator',methods=['POST'])
def illustrator():
    return multiple_buttons('Illustrator')

HTML :
<form action="/showall" method="post" style="display:inline-block">
      <button class="btn active" name="showall"  type="submit"> Show All</button>
  </form>
  <form action="/illustrator" method="post" style="display:inline-block">
      <button class="btn" name="illustrator"  type="submit"> Illustrator</button>
  </form>

This answer was very helpful: https://stackoverflow.com/a/42859886/8131701


text:
Q: Duplicate Action names in same namespace .NET MVC I'm quite inexperienced with .NET MVC and as I looked my problem up, all the solutions concerning it were situations where people tried to use same controller name in different namespaces. I've a situation with duplicate controller names in same namespace and I'm wondering if there's a very simple solution that I can't seem to find.
    [HttpPost]
    public IActionResult Insert(AddedItem model, ICollection<IFormFile> files)
    {

        _insertProductService.InsertData(model.Name, model.Author, model.Description, files);
        ModelState.Clear();
        ViewBag.SuccessMessage = "Item has been added!";
        return View();
    }

    [HttpPost]
    public IActionResult Insert(AddedCategory model, ICollection<IFormFile> files)
    {

        _insertCategoryService.InsertData(model.Name, model.Author, files);
        ModelState.Clear();
        ViewBag.SuccessMessage = "Category has been added!";
        return View();
    }

I get the following error:

AmbiguousActionException: Multiple actions matched. The following
  actions matched route data and had all constraints satisfied

I've two forms in partial views that are called from Insert page. What is the best way to "force" application to choose the fitting IActionResult?
I think ActionConstraints might be the solution, however I struggle to understand them. In case I'm right about ActionConstraints, could someone please provide me a simple example that I could adjust in my solution?
insert.cshtml below as suggested:
 @{
        ViewData["Title"] = "Add new";
    }
    @section Scripts2 {

    }

@ViewData["Title"].

@ViewData["Message"]

Product

Category

            @await Html.PartialAsync("~/Views/Shared/ProductFormPartial.cshtml")

            @await Html.PartialAsync("~/Views/Shared/CategoryFormPartial.cshtml")


text:
Q: What is the Alternative for springfox https://github.com/springdoc/springdoc-openapi.git
Only disabled the SpringFox dependencies, added SpringDoc, and replaced the SpringFox bean, with a SpringDoc bean. Everything is working as expected. All I need to do is to convert a couple of annotations on each rest service so SpringDoc displays everything correctly. SpringDoc does work

A: Springdoc openapi is latest alternative for springfox, as springfox is not comparable with spring boot 2.2.0 and spring hateos

A: https://github.com/RabiAPI/Evalon4J
This is a command line tool for generating java restful api documentation,
The best point is it's using pure static analysis, no need to compile or build your project first.
Supported frameworks

*

*Spring MVC

*JAX-RS

*Swagger 2.0 Annotations

*OpenAPI 3.0 Annotations

*JSR303 Bean Validation

Now it can export your api to markdown format.


text:
Q: Jersey 2: What replaces FEATURE_FILTER_FORWARD_ON_404? What is the Jersey 2 equivalent of ServletContainer.FEATURE_FILTER_FORWARD_ON_404 from Jersey 1?
ServletContainer.FEATURE_FILTER_FORWARD_ON_404 is defined as:

If true and a 404 response with no entity body is returned from either the runtime or the application then the runtime forwards the request to the next filter in the filter chain

Please explain why you are downvoting. I can't improve the question/answer if you don't provide an explanation of what is wrong.

A: The properties you should be using are ServletProperties.FILTER_FORWARD_ON_404 and ServletProperties.FILTER_STATIC_CONTENT_REGEX.
ServletProperties.FILTER_FORWARD_ON_404 is defined as:

If set to true and a 404 response with no entity body is returned from either the runtime or the application then the runtime forwards the request to the next filter in the filter chain.

ServletProperties.FILTER_STATIC_CONTENT_REGEX is defined as:

If set the regular expression is used to match an incoming servlet path URI to some web page content such as static resources or JSPs to be handled by the underlying servlet engine.

A: @gili is correct. For a complete running example of the jersey 2.x config check out my simple toy project on github:
https://github.com/depsypher/flapjack
Essentially you'll have to run the Jersey ServletContainer as a filter and provide the jersey.config.servlet.filter.forwardOn404 property as an init param.
Here's an example of the setup using Spring Boot; the web.xml equivalent should be pretty obvious:
FilterRegistrationBean filter = new FilterRegistrationBean(new ServletContainer());
filter.addInitParameter("jersey.config.servlet.filter.forwardOn404", "true");


text:
Q: best way to test form submitting I have a form that posts to an external url
<form method="post" action="http://api.domain.com/AddAnswer">

and I'm using MongoHQ to "dump" the result of that form
I wanted to make a simple test to submit 100 forms just to see if I get 100 answers in MongoHQ
Is there any available services out there for such, or I need to create my own auto-submitting?
Blitz.io only work with GET's, and I was thinking as well that would be nice to test the browser as well, as Chrome always get the Origin error as form host and form action are in different servers (even though the form is submitted correctly).
If no service available for such scenario, how would you proceded?
I was thinking in creating a HTML page and hosted somewhere, then open a Windows/Web page that I would hit that url 100 times.
I could easily add
$(function() {

    var dt = new Date();

    // set date so we can have different posts data
    $("#dt").val(dt.getTime());

    // auto submit
    $("form").submit();
});

to the static page...

A: If I get your idea correct, you want to execute 100 post requests and then to verify that the response is correct.
If I am right, I can suggest you http://www.soapui.org/ . It is pretty simple to create that kind of test cases by following the tutorials they provide. Basically in your case you just need to develop a test which execute the request and verify the response content (if just waiting for response code 200 is not enough for you). Then you need to develop load test which call your verification test N-time. And that's all. As a result you will have test case which verify that you have N right responses.


text:
Q: CSS variables in Material ui - createMuiTheme I am trying to create a material ui theme using the existing colors defined as css variables my-pallette.scss:
:root {
  --primary-color: '#FF0000';
  ...
}

And use this like this:
import { createMuiTheme } from '@material-ui/core/styles';

export const muiTheme = createMuiTheme({
  palette: {
    primary: {
      main: 'var(--primary-color)',
    },
  },
});

This throws an error:

Uncaught Error: Material-UI: Unsupported var(--primary-color) color.
We support the following formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla().

According to this Github thread: Support CSS variables as theme option this is unsupported at the moment.
Is there any workaround so I can use var(--primary-color) as a primary color in material ui createMuiTheme?
The end goal is to use material ui components in their simplest form with their primary, scondary, etc colors overwritten by my colors.
<Radio color="primary" />

I have tried using the colors from my pallets like this:
const cssVariables = {
  primaryColor: getComputedStyle(document.documentElement).getPropertyValue('var(--primary-color)'),
};

and use cssVariables.primaryColor but this doesn't work and feels very counterintuitive.
My last solution is to duplicate the palette as a normal object as use it as it is but this seems a nightmare for maintenance.

A: The MUI team is currently working on a solution to support CSS variables. You can track the progress here and check the details here. There is also an official documentation here.
UPD of 21.12.2022
CSS variables are supported now by the MUI as an experimental API, check documentation here.

A: The workaround posted by NearHuscarl gets the job done, but there's a flicker caused by the palette change. This can be avoided with lazy initialization in useState.
const cssVar = (name: string) =>
  getComputedStyle(document.documentElement).getPropertyValue(name).trim();

const App: React.FC = () => {
  const [theme] = useState(() =>
    createTheme({
      palette: {
        primary: {
          main: cssVar("--color-primary"),
          light: cssVar("--color-primary-light"),
          dark: cssVar("--color-primary-dark"),
          bg: cssVar("--color-primary-bg"),
          contrastText: cssVar("--color-primary-contrast-text"),
        },
      },
    })
  );

  return (
    <ThemeProvider theme={theme}>
      <YourApp />
    </ThemeProvider>
  );
};

A: The ugly workaround works, but I suspect you are calling getComputedStyle() in the module scope when the stylesheets may not be initialized yet.
Try putting it in the render method like this.
const [theme, setTheme] = React.useState(null);

React.useLayoutEffect(() => {
  const color = getComputedStyle(document.documentElement)
    .getPropertyValue("--your-css-color")
    .trim(); // the result have a leading whitespace.

  setTheme(
    createMuiTheme({
      palette: {
        primary: {
          main: color
        }
      }
    })
  );
}, []);

Live Demo

A: Setting colors from theme options may be more effectively. With this method you could define material ui colors as css variables.

import React, { useEffect } from 'react'
import { createTheme, ThemeProvider } from '@mui/material/styles'

import { indigo, amber } from '@mui/material/colors'
const themeOptions = createTheme({
  palette: {
    primary: { main: indigo[500] },
    secondary: { main: amber[600] },
    background: { default: '#F3F6F9' },
  },
})
const colorKeys = ['background', 'common', 'error', 'grey', 'info', 'primary', 'secondary', 'success', 'text', 'warning']
const r = document.querySelector(':root')
const AppThemeProvider = ({ children }) => {
  useEffect(() => {
    colorKeys.forEach((color) => {
      const themeColorObj = themeOptions.palette[color]
      for (const key in themeColorObj) {
        if (Object.hasOwnProperty.call(themeColorObj, key)) {
          const colorVal = themeColorObj[key]
          r.style.setProperty(`--color-${color}-${key}`, colorVal)
        }
      }
    })
  }, [])
  return <ThemeProvider theme={themeOptions}>{children}</ThemeProvider>
}
export default AppThemeProvider

With this way you could use css variables as sass or common css.
.dx-link-edit {
  color: var(--color-primary-main);}


text:
Q: Replacing / hide div with module I am wondering if there is a way to replace or hide a certain div with a module.
I'm not talking about a whole new .phtml file. If you can make a part phtml file thats fine but i don't know how. It needs to work with a theme so i want to make it more universal then just copy/pasting the .phtml file and adjusting it.
Is there a way to replace a part of a template only?
More in detail i want to delete :
<form data-role="tocart-form">

Thanks for your time of you are anwering this.
This is for Magento 2

A: I'm not too sure what you're asking, it sounds like you want to remove or hide an element only inside a template?
I'm not sure why you'd want to do this, if you want to hide it then use CSS and if you want to remove it then either remove the block via XML or remove the markup in the template by overwriting it. Here is an answer on how to override a template with your module.


text:
Q: Parsing XML from string I'm sure this is very simple..
I have this as a string:
<OnTheRoadQuote xmlns:i="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://schemas.datacontract.org/2004/07/OTRAPI.Services.Models">
<BasicPrice>15595.8333</BasicPrice>
<CO2>93</CO2>
<Dealer>Audi</Dealer>
<DeliveryCost>524.9900</DeliveryCost>
<DiscountPrice>14348.166636</DiscountPrice>
<DiscountSum>1247.666664</DiscountSum>
<Discounts>
<Discount>
<DiscountApplication>Percentage</DiscountApplication>
<DiscountDescription>Dealer Discount on Vehicle and Options %</DiscountDescription>
<DiscountID>Discount1</DiscountID>
<DiscountType>VehicleAndOptions</DiscountType>
<DiscountValue>8</DiscountValue>
</Discount>
</Discounts>
<OTR>17902.7879632</OTR>
</OnTheRoadQuote>

How do I read the value of the OTR node?
I've got an XmlReader but not sure how to use it.
Thanks

A: Using XmlReader, and fixing a typo in your root element (missing space before the second xmlns):
string xml = @"<OnTheRoadQuote xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/OTRAPI.Services.Models"">
  <BasicPrice>15595.8333</BasicPrice>
  <CO2>93</CO2>
  <Dealer>Audi</Dealer>
  <DeliveryCost>524.9900</DeliveryCost>
  <DiscountPrice>14348.166636</DiscountPrice>
  <DiscountSum>1247.666664</DiscountSum>
  <Discounts>
    <Discount>
        <DiscountApplication>Percentage</DiscountApplication>
        <DiscountDescription>Dealer Discount on Vehicle and Options %</DiscountDescription>
        <DiscountID>Discount1</DiscountID>
        <DiscountType>VehicleAndOptions</DiscountType>
        <DiscountValue>8</DiscountValue>
    </Discount>
  </Discounts>
  <OTR>17902.7879632</OTR>
</OnTheRoadQuote>";

string otrValue = "";
using (XmlReader reader = XmlReader.Create(new StringReader(xml))) // use a StringReader to load the XML string into an XmlReader
{
   reader.ReadToFollowing("OTR"); // move the reader to OTR
   reader.ReadStartElement(); // consume the start element
   otrValue = reader.Value; // store the value in the otrValue string.
}

Keep in mind that XmlReader is forward only, meaning that you can't navigate it backwards through the XML data to read, for example, Discounts, once you've pushed it to the OTR node.  If you want to do that, you should look into using XmlDocument or (preferably) XDocument.  However, if all you need to do is get the OTR value, this should be the most efficient (time and space) way of doing so.

A: With less code, you can use LINQ to XML and load an XElement with the xml or a file. There are also other options.
XElement element = XElement.Load(....);
var node = element.Element("OTR");

https://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.load%28v=vs.110%29.aspx


text:
Q: Standard Deviation in R I am trying to calculate the standard deviation from scratch in R (I do know R has a build-in function for that), but I'm not getting the correct results, so I don't know what I'm doing wrong.
My.SD<-function(X) {
  M<-(sum(X)/length(X))
  my.var<-sum((X-M)^2)
  StanDev<-sqrt(my.var/length(X))
  print(StanDev)
}

A: I guess you might need to use (length(X)-1) rather than length(x), i.e.,
My.SD<-function(X) {
  M<-(sum(X)/length(X))
  my.var<-sum((X-M)^2)
  StanDev<-sqrt(my.var/(length(X)-1))
  print(StanDev)
}

since here it should be sample standard deviation.


text:
Q: LaTeX, ntheorem package and memoir document class: no room for new \count error So I want to use memoir document class and the ntheorem package with the thmmarks option. When I try and compile a file like this, I get "no room for a new \count" errors. What can I do about this?
ntheorem with thmmarks option works fine in article, and ntheorem works alright in memoir as long as I don't try and use the thmmarks option...
To reformulate the question: Is there a way to, I don't know, cut out parts of the memoir class definitions that I don't use to free up some \counts for ntheorem thmmarks? Or is there a way to alter how many \counts LaTeX allows so that there are enough to share?
(I'm fully aware that insisting on using memoir for typesetting a theorem-heavy document is a little perverse, but what the heck.)

A: See the TeX FAQ entry about this error: No room for a new "thing".
With any modern LaTeX installation, you're going to be using eTeX.  Thus, based on that FAQ entry, you should be able to fix the problem by inserting
\usepackage{etex}

immediately after your \documentclass line.  If that's insufficient, try also adding the \reserveinserts{n} line suggested there with some appropriate number of additional inserts (which I guess you can find by trial and error), to reserve additional space.  (A bit of Google-searching on reserveinserts ntheorem indicates that this is a common problem with the ntheorem package, and finds a suggestion of 10 as a reasonable value, though you may need more.)
If that works, you might also write to the Memoir class author, and suggest that he add a note to this effect in the manual.
This thread also suggests an alternate method of loading the ntheorem package that may help, if \reserveinserts doesn't do the trick:
http://newsgroups.derkeiler.com/Archive/Comp/comp.text.tex/2009-03/msg00531.html

A: memoir wasn't really designed to be setting all that math-- hence the name memoir and as such, memoir does things in kind-of its own way, and provides much more functionality out of the box than article, report, or book. this comes at a cost though, as some packages aren't compatible with memoir... you might be better of using article, report or book. However, there is an extensive list of errors in the memoir manual. read it!


text:
Q: Counting number of rows in mysql table of a particular id optimally I am using this code
$sql1 = mysql_query("SELECT section_id FROM forum_posts WHERE section_id='$sectionID'  ");
$num_rows = mysql_num_rows($sql1);

to count the number of posts under specific category to show on the home page of the forum that how many posts are there in a particular section.
So is there a better option that to go through all the posts of that type. I think it will be a huge performance drain if I use this.
Edit 1: I just have to display the number of posts under each section in the forum so I want to check in the homepage how many topics each sections has as of now.
What will be the optimal mysql query for it.
Edit 2: Should I replace teh mysql_query function as stated in the phpmanual?

A: Just use count in sql itself.
$sql1 = mysql_query("SELECT count(post_id) as 'count_of_posts' FROM forum_posts WHERE section_id='$sectionID' ");

If you want to get all section counts at the same time you can do it this way:
$sql1 = mysql_query("SELECT section_id, count(post_id) as 'count_of_posts' FROM forum_posts WHERE section_id='$sectionID' group by section_id");

A: It is more normal SQL, to count the rows using a COUNT() aggregate function. If you need to count several sections at once, then use GROUP BY. But you knew that, right?
Benchmark first, optimise second.

*

*Load your test server (which must be production-spec) with a production-size load of data; configure all parameters the same as your production server.

*Repeatedly run the code and time it.

*If it does not seem to slow, you're finished.

My suggestions:

*

*Explain the query. If it is running a full table scan, then add an index on Section ID. This should reduce the full table scan, at least to a full index scan. This may be still too slow.

*If this is still too slow, consider caching the result somewhere. You can invalidate this cache when posts are added, deleted or moved to another section.

*If the caching is inconvenient or doesn't work - for instance if you have a less than 90% hit rate on the cache, consider permanently storing the counts, and manually adjusting them. Then you don't need to recalculate the counts for a section when its posts haven't changed.

Suppose you have 1e9 posts, in 1e3 sections. Most of the time, most sections' posts won't change. So you can just modify the counts for the section(s) affected by an operation - for example, for add/delete, you just update one section, and for a move, two sections, leaving 998 sections' counts unmodified and avoiding expensive counting operations.
But I think it is highly unlikely that you have 1e9 posts (I'm sure Stackoverflow does not).
Consider investigating how Stack Overflow manages its tags-questions counts.

A: SELECT distinct section_id, count(section_id) as num_of_posts FROM forum_posts WHERE section_id='$sectionID' group by section_id
then do a $num_of_rows = $sql1['num_of_posts'];
Or keeping your query as it is, do a count($sql1);


text:
Q: SQL Server 2008: The login is from an untrusted domain and cannot be used with Windows authentication The question here is different from 1 & 2
When trying to connect to a SQL Server database that is on another system in the network both are in workgroup, when attempting to connect to a SQL Server 2008 instance using SQL Server Management Studio with Windows authentication, I get connected.
But when trying to connect from my application, I get the following error

(Login failed. The login is from an untrusted domain and cannot be
  used with Windows authentication.) Native=18452).

If SQL Server Management Studio can connect, what would be required for my application to get connected?

A: If you are using Windows 7, you might have to "run as administrator".  This will allow the app to reuse your windows credentials and pass them to the SQL Server.  Otherwise, you will pass guest credentials to the SQL Server.

A: Since you are running in a workgroup the only possible authentication is one using 'mirrored NT accounts', which means that the process trying to authenticate must be running under an identity that is 'mirrored' on the host that is authenticating the process. 'Mirrored' accounts are distinct local accounts with identical name and password on both hosts doing the authentication.
So it must follow that you're running SSMS from an account that it is mirrored on the SQL Server host (eg. <computername>\Administrator, which is mirrored by the <sqlhost>\Administrator and has the same password). Note that UAC has nothing to do here (ie running as administrator will not help).
Your application is probably running under a different local account (default IIS appool perhaps?) and the account under which the application runs is not mirrored on the SQL Server host.
Your best solution is to ditch the makeshift network and deploy a proper AD (domain). As an interim, make sure you run your application under an account that is mirrored on thew SQL Server host machine.


text:
Q: Checkbox not true when checked for every panel in my recyclerview? so I created a recyclerview and I am inflating an xml file into that recyclerview, inside my customxml file I have a checkbox, however, when I click on the checkbox it always gives me the true statement for the first panel in the recyclerview and the rest are false whats up with that?
  public void CheckBox(View view) {
    final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
    if (checkBox.isChecked()) {
        System.out.println("SET TO CHECKED");

    }

else{
        System.out.println("SET TO UNCHECKED");
        }

}

A: Note that in a RecyclerView, multiple child views will have the same id. I suspect that final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox); does not return the checkbox that you actually want. It sounds like it always returns the first one in the list, not the one which is clicked on. Since CheckBox() is the onClick listener for your checkboxes, there is no reason to call findViewById(). You can simply use the view which is sent as a parameter:
Checkbox checkbox = (Checkbox)view;

A: Try like this:
     final CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox_id);
     if (checkBox.isChecked()) {
         checkBox.setChecked(false);


text:
Q: JAVA Client-server game I have to prepare a game inspired by this game. Of course it should be much simple, but unortunately it has to use client-server communication in order to allow two players to play together. So far I prepared textures and I'm trying to make one of cars moving. Sadly it is not as simple as it seems. I got stuck and I can't go on... I want to use just four arrows: UP - car speeds up, DOWN - car slows down, LEFT - turns left, RIGHT - turns right. Of course if we don't push UP button or DOWN button, car should slow down, but more slightly. I beg for tips!
This is my code:
package destructionderby;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

class CRX extends JFrame implements KeyListener
{
   File imageFile2;
   BufferedImage crxModel;
   public int speed;
   int posX, posY;
   JPanel crxPanel;
   public CRX()
    {
        speed = 0;
        posX=562;
        posY = 420;
        crxPanel = new JPanel();
        imageFile2 = new File("crx.png");
        try
        {
            crxModel = ImageIO.read(imageFile2);
        }
        catch (IOException e)
        {
            System.err.println("File access error");
        }
        addKeyListener(this);
    }
    public void paint(Graphics g)
    {
        while (true)
        {
            Graphics2D g2d = (Graphics2D) g;
            g2d.drawImage(crxModel, posX+speed, posY, null);
            repaint();
        }
    }

    //-------------------KEY LISTENER--------------------
    public void keyTyped (KeyEvent key)
    {
            if (key.getKeyCode()==38) //38 == UP; 40==DOWN; 37==LEFT; 39==RIGHT
            {
                speed +=10;
            }
            if (key.getKeyCode()==40)
            {
                if (speed >10)
                {
                    speed-=10;
                }
                else speed=0;
            }
    }
    @Override
    public void keyPressed(KeyEvent key)
    {

    }
    @Override
    public void keyReleased(KeyEvent key)
    {

    }
}

class MainWindow extends JFrame
{
    JPanel mainWindow;
    BufferedImage backgroundImage;
    CRX crx;
    MainWindow()
    {
        super("Destruction Derby");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(800,600);
        setResizable(false);
        setVisible(true);
        init();
    }
    void init()
    {
        mainWindow = new JPanel();
        File imageFile= new File("background.png");
        //:::...ZAŁADOWANIE OBRAZKA TŁA:::...
        try
        {
            backgroundImage = ImageIO.read(imageFile);
        }
        catch (IOException e)
        {
            System.err.println("File access error");
        }
        crx = new CRX();
        paint(getGraphics());
     }

    @Override
    public void paint(Graphics g)
    {
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(backgroundImage, 0, 0, this);
        crx.paint(getGraphics());
    }
}

public class DestructionDerby
{
    public static void main(String[] args)
    {
        new MainWindow();
    }
}

And there is my NetBeans project: http://www2.zippyshare.com/v/30402578/file.html

A: *

*JFrame by default never to react to KeyEvent, put there JPanel

*don't paint() directly to JFrame, use JPanel instead

*override paintComponent in JPanel, add super.paintComponent() as 1st code line (same for paint())

*use KeyBindings (tons examples about these Keys here) instead of KeyListener

*for why reasons there are two JFrames, don't extend JFrame, create an local variable

*load Image to local variable too


text:
Q: Can we have variable keys defined inside a hash? I am trying to create a hash as follows :
my $block_name = pm88_60_464 ;
my %hash_for_tstamp = qw (
         layout/${block_name}.proj/tech  ap_db_time
         rpts/sem_check/sem_check_analysis.rpt  sem_analysis
  );

my $key;
my $value;

while (($key,$value) = each (%hash_for_tstamp)) {
  ${$time_summary}{"$value"} = ctime(stat($key)->mtime) ;
}

While running above code i am getting below error.
stat() on unopened filehandle File::stat::layout/${block_name}.proj/tech .
Can't call method "mtime" on an undefined value at audit_automation.pl line 205.

So what i've understood by this error is that we are allowed to have variable keys inside hash.

A: The issue is one of variable interpolation, or the lack thereof when using the qw// construct.  There is no variable interpolation inside of qw//, as is explained in perlop Quote and Quote-like Operators
You can resolve the situation by using the appropriate quote-like construct; in this case, double-quotes where variable interpolation is desired.  Here's an example:
my $block_name = "pm88_60_464";
my %hash_for_tstamp = (
    "layout/${block_name}.proj/tech",        "ap_db_time",
    "rpts/sem_check/sem_check_analysis.rpt", "sem_analysis"
);

while ( my ($key,$value) = each (%hash_for_tstamp) ) {
  print "($key),($value)\n";
}