text:
Q: How typeset a numeric table from a CSV file I have a CSV file (db.txt)like this:
30.0,   0.0,    0.0
60.0,   1.9098, 5.8779
90.0,   6.9098, 9.5106
120.0,  13.09,  9.5106
150.0,  18.09,  5.8779
180.0,  20.0,   0.0

I need to typeset it. My problem is related with the wrong alignment of decimal point and the number of decimals (must be a constant for each column):
\renewcommand*{\dtlrealalign}{r}

\DTLloaddb[
    noheader,
    keys={x,y,theta},
    headers={
        \shortstack{$\boldsymbol{\theta_{2,i}}$},
        \shortstack{X},
        \shortstack{Y}
             }
  ]{db}{db.txt}
\begin{table}[t]
  \caption{Database file}
  \centering
  \DTLdisplaydb{db}
\end{table}

Any advice, please?

A: There's no problem to do this with the datatool package and siunitx as well.  Here's your example done in that way:
\documentclass{article}
\usepackage{datatool}
\usepackage{siunitx}
\usepackage{booktabs} % for nicer tables
\usepackage{caption} % improve caption spacing (among other things)
\usepackage{bm}
\renewcommand*\dtldisplaystarttab{\toprule}
\renewcommand*\dtldisplayendtab{\tabularnewline\bottomrule}
\renewcommand*\dtldisplayafterhead{\midrule}

\begin{document}
\DTLloaddb
 [
    noheader,
    keys={x,y,theta},
    headers={
    \shortstack{$\boldsymbol{\theta_{{2,i}}}$},
    \shortstack{X},
    \shortstack{Y}}
  ]
  {db}{db.txt}
\begin{table}[t]
\sisetup{
    parse-numbers   = false,
    table-number-alignment = left,
    table-figures-integer = 4,
    table-figures-decimal = 4,
    input-decimal-markers = .
    }
    \renewcommand*\dtlrealalign{S}
  \caption{Database file}
  \centering
  \DTLdisplaydb{db}
\end{table}

\end{document}

A: You can use pgfplotstable for this. If you load the array package, you can set the option dec sep align for pgfplotstabletypeset to get the alignment at the decimal point. Padding the numbers with zeros can be accomplished by setting fixed zerofill, the number of decimals can be set using precision, either for all columns or for individual columns by using display column/<index>/precision=<digits>.

\documentclass{article}
\usepackage{filecontents}       % For the example data
\usepackage{pgfplotstable}
\usepackage{array}      % For aligining at decimal point

\begin{filecontents}{testdata.csv}
theta, x, y
30.0,   0.0,    0.0
60.0,   1.9098, 5.8779
90.0,   6.9098, 9.5106
120.0,  13.09,  9.5106
150.0,  18.09,  5.8779
180.0,  20.0,   0.0
\end{filecontents}

\begin{document}
\pgfplotstableread[col sep=comma]{testdata.csv}{\table}

\pgfplotstabletypeset[
    dec sep align,      % Align at decimal point
    fixed zerofill,     % Fill numbers with zeros
    precision=4,        % Set number of decimals
    display columns/0/.style={precision=1}, % Change for first column (column 0)
    ] {\table}
\end{document}

Alternatively, you can use pgfplotstable and the siunitx package to align the columns. I've used it here in conjunction with booktabs and properly formatted column headers:

\documentclass{article}
\usepackage{pgfplotstable}
\usepackage{siunitx}
\usepackage{booktabs}

\begin{filecontents}{testdata.csv}
theta, x, y
30.0,   0.0,    0.0
60.0,   1.9098, 5.8779
90.0,   6.9098, 9.5106
120.0,  13.09,  9.5106
150.0,  18.09,  5.8779
180.0,  20.0,   0.0
\end{filecontents}

\begin{document}
\pgfplotstableread[col sep=comma]{testdata.csv}{\table}

\pgfplotstabletypeset[
    dec sep align=S,    % Use the siunitx `S` column type for aligning at decimal point
    fixed zerofill,     % Fill numbers with zeros
    precision=4,        % Set number of decimals
    display columns/0/.style={
        precision=1,    % Change for first column (column index 0)
        column name=$\theta_{2,i}$
    },
    display columns/1/.style={column name=$X$},
    display columns/2/.style={column name=$Y$},
    every head row/.style={before row=\toprule, after row=\midrule},
    every last row/.style={after row=\bottomrule},
    ] {\table}
\end{document}


text:
Q: How to get parameter from url? I have been developing a PHP page using Code Igniter. There is some function from controller:
public function language_testing($language_code, $logout=0)
{
      echo ($language_code);
      //come actions
}

And I'm trying to send the following url: http://mypage.com/index.php/controller/language_testing/bg#9
But my function shows me "bg" instead of "bg#9". Please, tell me, how can I get a content after "#"? I need it so much.

A: You should be posting to the following URL to get the value to appear in $logout:
http://mypage.com/index.php/controller/language_testing/bg/9

Otherwise, the data after the pound sign isn't accessible by the server.

A: http://au.php.net/manual/en/function.parse-url.php
$urlComp=parse_url($yourURL);
echo $urlComp['fragment'];

A: You can't. The # is a HTML bookmark, used to redirect focus around a page using IDs on HTML elements. Browsers won't submit this as part of a URL to the server.
Depending on your rewrite rules, you'll either want to create a link that's semantically pleasing, like http://site.com/path/index.php/bg/9 or as http://site.com/path/index.php?bg=9 (which is what your rewrite rules would be achieving anyway).
Note if you really need the # sign to be submitted for some reason then you'll need to submit it using %23 in the URL (@jth_92 beat me to it).

A: You need to alter the function params add one more parameter for code as well
public function language_testing($language, $code , $logout=0){
  echo ($language);
  echo ($code);
  //come actions

}
and call it just like
     http://mypage.com/index.php/controller/language_testing/bg/9
it will resolve your problem and then you can concatenate both values

A: The # is an HTML entity that is used in anchor tags to jump to a name reference. For example:
Jump to test on page
Test

Thus, it is not being interpreted as part of your parameter. You should be able to use bg%23 as %23 is the escape character for hashing.
http://mypage.com/index.php/controller/language_testing/bg%239
How to escape hash character in URL

redpajama_set_name: RedPajamaStackExchange


text:
Q: MSIE Browser height? Does anyone know how to get the browser height in IE7+ with javascript? I've seen several ways to get the document or the body height but this is not the same. window.innerHeight works fine in firefox and other browsers, but ie doesnt seem to support it. Thanks

A: var windowWidth = -1, windowHeight = -1;

if(typeof(window.innerWidth) == 'number') { //Non-IE
    windowWidth = window.innerWidth;
    windowHeight = window.innerHeight;
} else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) { //IE 6+ in 'standards compliant mode'
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
}

That's worked pretty well for me.

A: To determine the actual size of the browser window, use the following properties:
Mozilla based browswers
window.innerWidth
window.innerHeight

Microsoft Internet Explorer
document.body.offsetWidth
document.body.offsetHeight

Here is some code that I use:
var winW = 630, winH = 460;

if (navigator.appName.indexOf("Microsoft") == -1) {
 if (navigator.appName=="Netscape") {
  winW = window.innerWidth;
  winH = window.innerHeight;
 }
 if (navigator.appName.indexOf("Microsoft") != -1) {
  winW = document.body.offsetWidth;
  winH = document.body.offsetHeight;
 }
}


text:
Q: Algorithm for generating an array with a subarray sum of zero I am trying to randomly generate an array of integers of range between -10^7 to 10^7 such that there exists a sub-array with a sum of zero.
For example : 7 6 4 8 -4 -8
1<=Size of array<=10^5
I am able to do it using brute-force but it is taking a lot of time as I have to generate very big such arrays. Is there any efficient way of achieving this using python or c++?
Edit: Actually I want to generate a lot of such arrays with different scenarios. I am generating these arrays as testcases for a problem to determine whether any given array of positive and negative integers contain a sub-array with zero sum.
Tried brute force code:
import random
N = random.randint(10,100)
mylist = []
for i in xrange(1,N):
  mylist.append(random.randint(-100,100))
list2 = [1,-1]
mylist = mylist[1:N-2] + list2 + mylist[N-2:N]
print mylist

So I have to manually tweak it a lot.
Thanks!

A: The answer depends on how random you want your array to be. Like some of the commenters mentioned, you can always include a zero and are thus guaranteed to have a subarray with sum of zero. I thought it would be helpful to your eventual solution, so I want to mention that you can check if an array has a subarray with sum of zero in O(N^2) time.
def array_has_zerosubarray( A ):
    for _begin in xrange(0,len(A)-1):
       for _end in xrange(_begin+1,len(A)):
           sum = 0
           for ai in range(_begin,_end):
               sum = sum + A[ai]
           if sum==0:
              return True
    return False


text:
Q: Room Tag type - REVIT API I have Room Tag family & its types as follows :

*

*Room Tag Rec : Length X Width

*Room Tag Rec : Width X Length

*Room Tag Rec : Square

My question is, How to assign above room tag types in room tag in REVIT 2018 API
My existing tag name is Room Tag : Room Tag With Area.
I want set (Change) to Room Tag Rec : Length X Width.
There is no name set option.

A: you have to get the RoomTag-s from the document with the FilteredElementCollector class and you can use the BuiltInCategory, as a filter. At the end of the day a room tag type is just another type of FamilySymbol:
var roomTagInstance = doc.Create.NewRoomTag(args);
var roomTagTypes = new FilteredElementCollector(doc).
                       OfCategory(BuiltInCategory.OST_RoomTags).
                       Cast<FamilySymbol>();
roomTagInstance.ChangeTypeId(roomTagTypes.First(filter here))

Cheers


text:
Q: Parsing a string by a delimeter in C++ Ok, so I need some info parsed and I would like to know what would be the best way to do it.
Ok so here is the string that I need to parse. The delimeter is the "^"
John Doe^Male^20

I need to parse the string into name, gender, and age variables. What would be the best way to do it in C++? I was thinking about looping  and set the condition to while(!string.empty()
and then assign all characters up until the '^' to a string, and then erase what I have already assigned. Is there a better way of doing this?

A: You can use getline in C++ stream.
istream& getline(istream& is,string& str,char delimiter='\n')
change delimiter to '^'

A: You have a few options. One good option you have, if you can use boost, is the split algorithm they provide in their string library. You can check out this so question to see the boost answer in action: How to split a string in c
If you cannot use boost, you can use string::find to get the index of a character:
string str = "John Doe^Male^20";

int last = 0;
int cPos = -1;
while ((cPos = str.find('^', cPos + 1)) != string::npos)
{
   string sub = str.substr(last, cPos - last);

   // Do something with the string

   last = cPos + 1;
}

A: #include <stdio.h>

#include <string.h>

int main ()

{

  char str[] = "This is a sample string";

  char * pch;

  printf ("Looking for the 's' character in \"%s\"...\n",str);

  pch=strchr(str,'s');

  while (pch!=NULL)

  {

    printf ("found at %d\n",pch-str+1);

    pch=strchr(pch+1,'s');

  }

  return 0;

}

Do something like this in an array.

A: You have a number of choices but I would use strtok(), myself. It would make short work of this.


text:
Q: In Dan Abnett's "Gaunt's Ghosts: The Anarch", when were the Tanith infiltrated? WARNING: this question is about the latest novel in the Gaunt's Ghosts series by Dan Abnett. It's really hard to ask it without spoiling anything about the story arc set up in Salvation's Reach and continued through The Warmaster and The Anarch, so if you haven't read those, please stop reading here. Really heavy spoilers for The Anarch follow, though I tagged what I could.
A big reveal in The Anarch, foreshadowed in The Warmaster, is that Chaos magister Anakwanar Sek, the main villain of the current story arc, had placed two sleeper agents in the midst of the unsuspecting Tanith First regiment. These two agents turn out to be

 murderous woe machines, disguised as the human-looking Yoncy and Dalin Criid, the supposedly biological children of Gol Kolea, later adopted by Captain Tona Criid.

They are activated during the events of The Anarch and go on a rampage, causing much carnage and, um, woe.
My question is: when and how were they infiltrated into the Tanith Regiment, and

 were Yoncy and Dalin initially human at all, or was it a case that Gol Kolea never had any children to begin with, the whole deal a false memory implanted by Sek? And if so, how?

or was there a real switch, and if so, when did it happen? During or after Verghast and the Zoican war? And why is it important that

 Gol Kolea remembers being told Yoncy was originally a boy, but then she is a girl? I read (but cannot find a reference) this was a continuity error by Dan Abnett, later acknowledged in-universe by the characters, but why does it matter? If Sek wanted to replace Yoncy with a woe machine, why change its gender? He didn't find it necessary to change Dalin's, so male-looking woe machines are feasible. So what was the point? Just a joke by Abnett acknowledging he made a mistake?

I am well aware none of this is answered in the novel series, because I've read them all. But maybe Dan Abnett has hinted at an answer in an interview, or in the Sabbat Crusade book?

A: The idea that they were replaced before or during the Zoican War on Verghast doesn't make sense to me for a couple of major reasons.
The first is that, if they are infiltrators, they're a child and a baby at this point and can't meaningfully participate in the conflict. They would have a role to play in a longer war, but Asphodel isn't planning on a long war. He has a plan that (so far as he knows) will completely level Vervunhive in about two months. If he had any inkling that this plan wouldn't work and he'd need a backup, he wouldn't have personally accompanied the Spike. As it was, because he and his propaganda broadcasts were cut short, his troops were routed.
Another problem is the chain of custody: except for a few brief encounters towards the end of the book, Tona Criid spends all of Necropolis from the very first chapter with Dalin and Yoncy. If there was a switch during the book, it would have to be at the climax, while Asphodel is at the cusp of victory - hardly the time to be worrying about infiltrating the enemy. He is clearly set on a plan of annihilation; his troops even encircled Vervunhive to gun down refugees on the north bank of the river. If he wanted to infiltrate other Imperial cities, he would've inveigled his infiltrators among those refugees and allowed them to escape.
It's worth remembering too that Asphodel didn't need infiltrators, because he'd brought High Master Salvator Sondar under his sway. Why bother to sneak in a few fake grunts when you've already got the boss?
It's possible that another Chaos warlord placed them in Vervunhive before the beginning of the book, not knowing about what would happen. (Or perhaps knowing, and knowing they would survive - but if Chaos is providing that level of foreknowledge, why did any of the Salvation's Reach mission happen? To say nothing of the events of Traitor General, or the trap in Sabbat Martyr.) The question then becomes, why them? The Koleas were no one special; they didn't even live in Vervunhive. If Chaos could work such a perfect changeling ruse, why not on someone whose children would grow up to be important, such as a noble family?
Another counterargument is that throughout the series, various Chaos forces have proven very adept at infiltration and subversion on short notice. In First and Only, a trooper named Adare is cut by a Chaos artifact and within minutes has become a shambling horror made of bones. In Sabbat Martyr, Pater Sin takes control of Lijah Cuu with no forewarning or preparation (although it does take a very specific type of mind to do so). And of course, in Salvation's Reach Sirkle kills and replaces a bandsman more or less effortlessly. It wouldn't have been difficult for the woe machines to do the same to the real Dalin and Yoncy at pretty much any point.
Finally, as Greg E Uke points out in comments on another answer, in The Armor of Contempt Dalin goes through Guard basic training and is (as I recall) injured in combat on Gereon, which entails a number of scenes from his point of view. At no point is there the slightest hint that he is in any way, physically or mentally, anything other than a normal human. He has normal human limits to his abilities, he bleeds normally, etc.

Edit: As for when the woe machines were placed in the regiment, I would suggest that it's relatively recently: well after Gaunt was established as a prominent figure in the Crusade and probably after the mission to Salvation's Reach. More specific than that it may not be possible to pin down.
My thinking here is twofold: first, if Gaunt and the Tanith are already a noteworthy thorn in the side of Chaos, it removes the need for Sek to have predicted that they (out of all the thousands of Guard units in the crusade) would become important later. Second, I feel that if the woe machines were active during the Salvation's Reach mission, they would have interfered somehow, perhaps during Sirkle's assassination attempt.

A: Gol Kolea had two sons, but both died in Vervunhive. His mind was tampered with at some point after he was saved by the Saint. Her 'miracle healing' drew on warp energies, which made him more susceptible to the warp. The bad shadow straight up tells him as much.
The woe machines were created by Heritor Asphodel, who is dead. Sek found them and figured out how to use them, but he didn't make them. Dalin and Yoncy were 'rescued' by the regiment on the same world Asphodel was killed on. He put them there.
Sek is obviously a Tzeentch sorcerer. That means he's a cunning intellectual with prophetic powers. He foresaw that Gaunt and his Ghosts would rise to greatness. Probably that Gaunt would become Warmaster. So he insinuated the kids into the regiment knowing that EVENTUALLY when Gaunt fulfilled his destiny he would be close to the Warmaster, the Saint, and all the bigshot generals. Then he could activate them and wipe everyone out at once. He didn't need to know when it would happen, only that it eventually wound. And I imagine Tzeentch told him.
As for the boy girl thing...I imagine they were already made by the time he got his hands on them. A boy and a girl, and they looked the way they were built. So he had to work with what he had. If that means altering some dudes memories so he thinks he had a son and daughter, on well.

A: There is another "layer" to the story if you look at it from a divine influence standpoint.
The kids were never Gol Kolea's children, but he thought they were for some reason. I suspect it was actually the Emperor who made him think that. He got that idea in his head after the Saint healed him, but it's unclear why.
What if his memories weren't a deception by Sek? What if they were put there by the Emperor so he would love the woe machines and make them human?
In the end, love is what killed them both. If they hadn't been made vulnerable they would have been unkillable. Tzeench created monsters disguised as humans, and the Emperor countered by making them too human to fulfil their purpose. He's the god of humanity after all. That's his thing.
Is this theory too crazy? Gol was never manipulated by Sek at all? The Saint says he was the first 'instrument' she ever made.


text:
Q: Long series of D3 transitions - code structure Synopsis
I am currently working on a project where I use D3 for storytelling. For that purpose, I create a series of d3 graphs and define a transition logic between graphs. Although I am new to js programming, I am very happy with my progress. However, my code is getting very bloated and repetitive. Therefore I am trying to find a better structure for my code going forward.
Current code structure
For each graph, I define a function that draws that graph from scratch. This function takes a html element as an argument and inserts the graph into the DOM as a child of this element. These functions are used to initialize the graph sequence and for resize events.
I also define the transition logic with another "family" of functions. Those take an existing graph and convert it into another one using d3 transitions.
Lastly, I define functions getCurrentGraph() and setCurrentGraph() so the resize logic knows which graph to draw. These functions are used inside all other functions. For example, transitionGraph1Graph2() calls setCurrentGraph("graph2").
// draw (or redraw) graphs
function drawGraph1(el) {};
function drawGraph2(el) {};
function drawGraph3(el) {};

// transition logic
function transitionGraph1Graph2(el, duration) {};
function transitionGraph2Graph3(el, duration) {};
function transitionGraph2Graph1(el, duration) {};
function transitionGraph3Graph2(el, duration) {};

// get/set a key for the current graph via the DOM
function getCurrentGraph() {};
function setCurrentGraph(graph = "graph1") {};

Then I use a closure to make sure that all functions are scoped to a single .js file. I only want to expose the transition logic to the global scope.
graphsequence.js
graphSequence = function(el = document.getElementById("graphContainer"),
                         duration = 1000) {
  // draw (or redraw) graphs
  function drawGraph1(el) {};
  function drawGraph2(el) {};
  function drawGraph3(el) {};

  // transition logic
  function transitionGraph1Graph2(el = el, duration = duration) {};
  function transitionGraph2Graph3(el = el, duration = duration) {};
  function transitionGraph2Graph1(el = el, duration = duration) {};
  function transitionGraph3Graph2(el = el, duration = duration) {};

  // get/set a key for the current graph via the DOM
  function getCurrentGraph() {};
  function setCurrentGraph(graph = "graph1") {};

  // handle resize events
  window.addEventListener("resize", function() {
    switch (getCurrentGraph()) {
      case "graph1": drawGraph1(el) [break;]
      case "graph2": drawGraph2(el) [break;]
      case "graph3": drawGraph3(el) [break;]
    }
  });

  // initialize the graph sequence
  drawGraph1(el, duration);

  // expose callbacks for transitioning to the global scope
  return {
    transitionGraph1Graph2: transitionGraph1Graph2,
    transitionGraph2Graph3: transitionGraph2Graph3,
    transitionGraph2Graph1: transitionGraph2Graph1,
    transitionGraph3Graph2: transitionGraph3Graph2
  }
}();

index.html

<button onclick="graphSequence.transitionGraph1Graph2()">Transition Graph!</button>

Questions
First, I want to emphasize that my current code works very well and I am not trying to resolve a bug. I am asking for advice on how to structure my code in order to keep the project maintainable in the long run.

*

*I feel the current implementation is very repetetive. Is there any way to DRY up this workflow
and define the logic in a more concise manner?

*The events that trigger the transitions are created with scrollama.js. Is there any "scrollytelling" library that has a special integration of D3 that could be used to make the code more structured?

*Is it a good idea to have all this logic in a single .js file or should I try to split up the code to make the project more modular?

*Currently, I am working without any javascript framework. I am also not familiar with any frameworks for that language. Does it make sense to start using a framework for a usecase like this? If so, which frameworks are recommended and why?


text:
Q: Unnesting structs in BigQuery What is the correct way to flatten a struct of two arrays in BigQuery? I have a dataset like the one pictured here (the struct.destination and struct.visitors arrays are ordered - i.e. the visitor counts correspond specifically to the destinations in the same row):

I want to reorganize the data so that I have a total visitor count for each unique combination of origins and destinations. Ideally, the end result will look like this:

I tried using UNNEST twice in a row - once on struct.destination and then on struct.visitors, but this produces the wrong result (each destination gets mapped to every value in the array of visitor counts when it should only get mapped to the value in the same row):
SELECT
  origin,
  unnested_destination,
  unnested_visitors
FROM
  dataset.table,
  UNNEST(struct.destination) AS unnested_destination,
  UNNEST(struct.visitors) AS unnested_visitors

A: You have one struct that is repeated.  So, I think you want:
SELECT origin,
       s.destination,
       s.visitors
FROM dataset.table t CROSS JOIN
     UNNEST(t.struct) s;

EDIT:
I see, you have a struct of two arrays.  You can do:
SELECT origin, d.destination, v.visitors
FROM dataset.table t CROSS JOIN
     UNNEST(struct.destination) s WITH OFFSET nd LEFT JOIN
     UNNEST(struct.visitors) v WITH OFFSET nv
     ON nd = nv

A: Difficult to test by not having the underlying data to test on, so I created my own query with your dataset. As far as I can tell destination|visitors is not in an ARRAY-format, but rather in a STRUCT-format, so you do not need UNNEST it. Also view this thread please :)
SELECT
  origin,
  COUNT(struct.destination),
  COUNT(struct.visitors)
FROM dataset.table
GROUP BY 1


text:
Q: Am I getting serverless function timeouts (error 504) on vercel because I set up next-auth wrong? Background
I've been working on a next.js project that is meant to handle scheduling events. I've been using next-auth for authentication with mongodb, because I need a database to store information about scheduled events anyway.
While testing locally, I didn't have any issues at all, but ever since deploying on vercel AND mongo Atlas, I've been getting 504 "serverless function timeouts" up the wazoo on page load. A lot of people have mentioned that this is likely due to not making a connection with the db, but I'm not sure how to fix this. The only function that I am calling inside of getServerSideProps is getSession() as it is called in the docs.
Steps I've tried

*

*I've followed the next-auth configuration steps located here for mongodb

*I've followed the mongodb guide for vercel best practices here

*I've tried connecting to the atlas from the mongosh shell, and it's always quick as can be.

Conclusion
I've seen some stuff around mentioning that other people have been getting some pretty wicked cold start times on their serverless function, so I've created a snippet that pings the home page of my app 10 times every 2 minutes. This works okay as far as I can personally test, but 4-5 of any 10 requests hang for 10+ seconds while the rest finish up in roughly 200ms or so.
What am I doing wrong? / What can I do better?
My code
home page:
export const Home = function (props) { ... } // this never gets ran

export async function getServerSideProps(context) {
  const session = await getSession(context);
  const props = { session };
  const redirect = {
    destination: '/login',
    permanent: false,
  };

  return (!session)
    ? { redirect }
    : { props };
}

export default Home;

The login page:
export async function getServerSideProps(context) {
  const session = await getSession(context);

  if (session) {
    return {
      redirect: {
        destination: '/home',
      },
    };
  }

  return {
    props: {
      providers: await getProviders(),
      session,
    },
  };
}

nextAuth config:
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import { MongoDBAdapter } from '@next-auth/mongodb-adapter';
import clientPromise from 'lib/database/mongodb';

export default NextAuth({
  adapter: MongoDBAdapter(clientPromise),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    }),
  ],
  secret: "pshhhh, it's a secret"
});


text:
Q: Why is Kylo Ren separated from the other Knights Of Ren? In the movie you just see a glimpse of the Knights Of Ren.
The question   Where were the Knights of Ren during the events of The Force Awakens? sort of answers where they are in The Force Awakens.
So why was he alone fighting for the First Order without the Knights Of Ren? Did Snoke order him to fight there?

A: According to Wookieepedia, "the Knights' true loyalty was to Sidious". Interestingly, though, the article also states that they helped overthrow Sidious previously, indicating that they have a rogue streak. The first detail would indicate that Sidious had them working on other things when he did not need them with Kylo Ren. The second would suggest that they were more independent of the First Order (as they served multiple masters and fought on various sides over the years), so they did not always go with Kylo (similar to how the Inquisitors did not always stay with Vader, but were technically his personal Jedi-hunting team).


text:
Q: MongoDB add custom field on collection Is it possible to add custom field when we create a collection.
Something like this:
db.createCollection("myCollection", {my_custom_field: "some value"})

The idea is, some users can create collections and add data. But I want to know which user the collection belongs to. So I need to add some metadata about the collection.

A: You could create something like an abstract type where the base class has the user_id and each document extends that type. Your document would look something like this:
{
  user_id: "id",
  my_custom_value: <object or value>
}

Essentially, just add your metadata to the root of the document and the user defined value under that. Doing it this way means you wouldn't have a collection per user, you would have a single collection that allows users to add custom values.
If you do really need a collection per user then you might be able to just append the user_id to the collection name, but this seems like an anti-pattern and I would recommend first trying to create a single collection that meets your requirements:
db.createCollection("myCollection_<user_id>", {my_custom_field: "some value"})


text:
Q: Macro to hide certain rows Column A will always have the date and time in the pictured format, in 1 minute intervals for a whole month.

My first goal is to hide any rows that have a number less than 50 in column B.

Sub HideRows()
Application.ScreenUpdating = False
Application.Calculation = xlManual

For Each c In Range("B:B")
    If c.Value < 50 And c.Value <> "" Then Rows(c.Row).Hidden = True
Next

Application.Calculation = xlAutomatic
Application.ScreenUpdating = True
End Sub

That Macro works.
Then, I would also like to hide any consecutive rows that are between the first row starting with a number higher than 50, and the last row higher than 50.

Essentially, it would give me a start and stop time in column A for the flows over 50 in column B.
I don't know enough about coding to hide the times in-between the start and stop times.
Any help/suggestions are greatly appreciated!

A: Not the most elegant solution, but try this out
Sub StartEnd()

Dim ws As Worksheet
Dim lRow As Long
Dim rng As Range
Dim c As Range
Dim cnt As Long
Dim cntTotal As Long

Set ws = ActiveSheet    'change sheet here if you want

    With ws

        lRow = .Cells(.Rows.Count, "A").End(xlUp).Row   'last row
        Set rng = .Range("B2:B" & lRow) 'excluding headers

        cntTotal = Application.CountIf(rng, ">50")  'total occurences >50

        For Each c In rng
            If IsNumeric(c.value) And c.value > 50 Then
                cnt = cnt + 1
                Select Case cnt
                    Case 1, cntTotal:   'do nothing if first or last occurence
                    Case Else: .Rows(c.Row).Hidden = True   'else hide row
                End Select
            Else
                .Rows(c.Row).Hidden = True  'hide row if <50
            End If
        Next

    End With

End Sub

A: Here's one way, just for the main logic you're looking for:
Dim in50Block As Boolean
in50Block = False

For Each c In Range("B2:B10000")
    If c.Value < 50 And c.Value <> "" Then
        Rows(c.Row).Hidden = True
        in50Block = False
    Else
        If in50Block = True And c.Offset(1, 0).Value >= 50 Then
            Rows(c.Row).Hidden = True
        Else
            in50Block = True
        End If
    End If
Next


text:
Q: Formatting index page references as "1 sq." without "sq." being part of a hyperlink By default, MakeIndex will format page references which are composed of two or three consecutive pages as (e.g.) "1, 2"/"1-3". With a suitable index style file, the formatting can be changed to "1 sq."/"1 sqq." (with "sq." standing for "sequens", "sqq." for "sequentes"). However, with the hyperref package loaded, "sq." and "sqq." will be part of the respective page reference hyperlinks. How can I limit those hyperlinks to the actual page numbers?
\documentclass{article}

\usepackage{makeidx}
\makeindex

\usepackage{hyperref}

\usepackage{filecontents}

\begin{filecontents}{\jobname.mst}
suffix_2p "~sq."
suffix_3p "~sqq."
\end{filecontents}

\begin{document}

Some text about foo\index{foo}.

\clearpage

Another text about foo\index{foo}.

\printindex

\end{document}

A: The answer to my question can be found in hyperref's README (not in the manual):

For hyperlink support in the index, hyperref inserts \hyperpage
  into the index macros. After processing with Makeindex, \hyperpage
  analyzes its argument to detect page ranges and page comma lists.
  However, only the standard settings are supported directly:
delim_r "--"
delim_n ", "

(See manual page/documentation of Makeindex that explains the keys
  that can be used in style files for Makeindex.) Customized versions of
delim_r, delim_n, suffix_2p, suffix_3p, suffix_mp

needs markup that \hyperpage can detect and knows that this stuff
  does not belong to a page number. Makro \nohyperpage serves as this
  markup. Put the customized code for these keys inside \nohyperpage,
  e.g.:
suffix_2p "\\nohyperpage{f.}"
suffix_3p "\\nohyperpage{ff.}"

(Depending on the typesetting tradition some space "\\," or "~" should
  be put before the first f inside \nohyperpage.)

In my case, the index style file must be modifield as follows:
suffix_2p "\\nohyperpage{~sq.}"
suffix_3p "\\nohyperpage{~sqq.}"

A: Using hyperref you can also manipulate the grouping mechanism.
Using makeindex means that the complete page number is formated with \command{...}
So you can simple add a }{ to your suffix declaration:
suffix_2p "}{~sq."

Here the complete code (I used imakeidx to simplify the compilation)
\documentclass{article}

\usepackage{imakeidx}
\makeindex

\usepackage{hyperref}

\usepackage{filecontents}

\begin{filecontents}{\jobname.mst}
suffix_2p "}{~sq."
suffix_3p "~sqq."
\end{filecontents}

\begin{document}

Some text about foo\index{foo}.

\clearpage

Another text about foo\index{foo}.

\printindex

\end{document}


text:
Q: webflow in grails application how can i redirect to the same state more than one time using web flow
ex:
on('submit'){
    def destinationInstance = Destination.get(params.destination)
    def destinationGroupsInstance = DestinationGroup.get(params.destinationGroups)
    def h = destinationInstance.addToDestinationGroups(destinationGroupsInstance)
}.to('flowList')

what i need is how to enter to this state more than one time until destinations ends
thx

A: Well, you'd probably have something like the following code, which is untested but may give you a general idea.
def destinationFlow = {

    initialize {
        action {
            flow.destination = Destination.get(params.id)
        }
        on('success').to 'destinationList'
    }

    destinationList {
        render(view: 'destinationList')
        on('addDestination') {
            def destinationGroup = DestinationGroup.get(params.destinationGroupId)
            flow.destination.addToDestinationGroups(destinationGroup)
        }.to 'destinationList'

        on('finish').to 'done'
    }

    done {
        flow.destination.save()
        redirect(...) // out of the flow
    }
}

You'll need buttons on your destinationList view that invoke the 'addDestination' or 'finish' actions. See the WebFlow documentation and Reference Guide.

A: on('submit'){
   def destinationInstance = Destination.get(params.destination)
   def destinationGroupsInstance = DestinationGroup.get(params.destinationGroups)
   def h = destinationInstance.addToDestinationGroups(destinationGroupsInstance)
}.to{
   (condition or while loop or for loop)
   if success then
      return "<state name>"
   else
      return "flowList"
}

Reference:
http://livesnippets.cloudfoundry.com/docs/guide/2.%20Grails%20webflow%20plugin.html


text:
Q: Rails sample_app sign-in page fails when accessed from Heroku I'm learning rails. I on chapter 7 of Michael Hartl's rails tutorial. I am trying to make a signup page where users can create an account. I can create users without problems when I run my app from a local environment (localhost:3000), however when I push the changes up to Heroku, pressing the sign-up button results in the error "We're sorry but something went wrong".
Checking the heroku logs I find:
Started GET "/signup" for [an ip address...] at 2012-08-27 21:36:15 +0000

Processing by UsersController#new as HTML

ActionView::Template::Error (Missing partial /shared/error_messages with
{:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder]}. Searched in:

* "/app/app/views"

Rendered users/new.html.erb within layouts/application (38.9ms)

6:     <%= form_for(@user) do |f| %>
Completed 500 Internal Server Error in 137ms

5:

):

4:

app/views/users/new.html.erb:6:in
  `_app_views_users_new_html_erb___3412900076253353202_33302880'

7:       <%= render '/shared/error_messages' %>

8:       <%= f.label :name %>
app/views/users/new.html.erb:7:in `block in
  _app_views_users_new_html_erb___3412900076253353202_33302880'

9:       <%= f.text_field :name %>

Now I've run:
$ heroku run rake db:migrate

and I've included 'pg', '0.12.2' in my gemfile.
I've also rolled back the heroku db using:
$ heroku pg:reset HEROKU_POSTGRESQL_WHITE

and then re-migrated it
$ heroku run rake db:migrate

to no avail. Any ideas? It is strange because everything other aspect of the webpage works, and the whole thing works in my local environment. Thanks.

A: Krule correctly identified the problem. I had named the directory sample_app/app/views/Shared, when it should be sample_app/app/views/shared.
it is worth noting that changed the case of a directory in git is a little challenging because git isn't case sensitive. I had to execute these commands

$ git mv Shared shared2
$ git mv shared2 shared
$ git commit -m "your message here"
$ git add -A
$ git push

then pushed to heroku:

$ git push heroku
$ heroku open

Thanks for the quick and accurate response!

A: You are missing a partial:
Missing partial /shared/error_messages with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder]

Check if it has been added to git.


text:
Q: Error The sourceLayer parameter must be provided for vector source types mapbox GL:  I got this error
Error: The sourceLayer parameter must be provided for vector source types.
What is wrong?

A: If the layer-source type = geojson,  the map.setFeatureState needs source, id,
if the layer-source type= vector(for example tilesets URL),
the map.setFeatureState needs source, id, and for vector sources sourceLayer properties.
sample vector source :
//var _mapbox_style = 'mapbox://styles/hoogw/cjusyfrn725qp1flhynv414z1';
var _mapbox_tileset = "mapbox://hoogw.77wjwdb4";

var _layer_name = "countries-1ay4zz";

map.addSource("_geojson_source", {
  type: "vector",
  url: _mapbox_tileset,
});

map.addLayer({
  id: ___id,

  type: "fill",
  //'type': 'line',

  source: "_geojson_source",

  // for vector-sourced-layer,here, must have "source-layer"
  // but for geojson-sourced-layer, no need "source-layer"
  "source-layer": _layer_name,
  layout: {},
  paint: {
    "fill-color": [
      "case",
      ["boolean", ["feature-state", "hover"], false],
      __stroke_color_highlight, // when hover   //"#FF0000",  // red
      __stroke_color, // when normal//  "#FFFF00" // yellow
    ],

    "fill-opacity": [
      "case",
      ["boolean", ["feature-state", "hover"], false],
      0.7, // when hover
      0, // when normal
    ],
  }, // paint
});

//=====================  end ========= add tileset layer =================================

// --------- line ---------------

map.on("mousemove", ___id, function (e) {
  if (e.features.length > 0) {
    if (hoveredFeatureId) {
      map.setFeatureState(
        {
          source: "_geojson_source",
          sourceLayer: _layer_name,
          id: hoveredFeatureId,
        },
        { hover: false }
      );
    }

    if (e.features[0].id) {
      // have feature.id ( converted from properties, OBJECTID)
      hoveredFeatureId = e.features[0].id;

      map.setFeatureState(
        {
          source: "_geojson_source",
          sourceLayer: _layer_name,
          id: hoveredFeatureId,
        },
        { hover: true }
      );
    } else {
      // missing feature.id, maybe because of feature properties - missing - ObjectID field.
      // hover effect will failed.
      console.log(
        "missing feature.id, maybe because of feature properties - missing - ObjectID field."
      );
      console.log(
        "hover effect will failed. feature.id ( converted from properties, OBJECTID)"
      );
    }

    //console.log('hoveredFeatureId = ',hoveredFeatureId)

    //********* show event.feature.properties  *********
    //console.log('e.features[0].properties #### ', e.features[0].properties)
    var _highlight_feature_properties = e.features[0].properties;
    show_info_outline_Tab(_highlight_feature_properties);

    //********* show event.feature.properties  *********
  } // if
}); // mousemove

map.on("mouseleave", ___id, function () {
  if (hoveredFeatureId) {
    map.setFeatureState(
      {
        source: "_geojson_source",
        sourceLayer: _layer_name,
        id: hoveredFeatureId,
      },
      { hover: false }
    );
  }
  hoveredFeatureId = null;

  empty_info_outline_Tab();
});

map.on("click", ___id, function (e) {
  //console.log('clicked')

  instance_tabs.select("list"); // open up locked tab

  if (e.features.length > 0) {
    if (clickedFeatureId) {
      map.setFeatureState(
        {
          source: "_geojson_source",
          sourceLayer: _layer_name,
          id: clickedFeatureId,
        },
        { click: false }
      );
    }

    if (e.features[0].id) {
      // have feature.id ( converted from properties, OBJECTID)
      clickedFeatureId = e.features[0].id;

      map.setFeatureState(
        {
          source: "_geojson_source",
          sourceLayer: _layer_name,
          id: clickedFeatureId,
        },
        { click: true }
      );
    } else {
      // missing feature.id, maybe because of feature properties - missing - ObjectID field.
      // hover effect will failed.
      console.log(
        "missing feature.id, maybe because of feature properties - missing - ObjectID field."
      );
      console.log(
        "hover effect will failed. feature.id ( converted from properties, OBJECTID)"
      );
    } // else

    //console.log('hoveredFeatureId = ',hoveredFeatureId)

    //********* show event.feature.properties  *********
    //console.log('e.features[0].properties #### ', e.features[0].properties)
    var _highlight_feature_properties = e.features[0].properties;
    //show_info_outline_Tab(_highlight_feature_properties)  // mouse over hover event
    show_listTab(_highlight_feature_properties); // click event
    //********* show event.feature.properties  *********
  } // if
}); // click

A: geojson source sample:
         map.addSource("_geojson_source", {
          "type": "geojson",
          "data": ___GeoJson
          });

        if ((geojson_feature_type.toLowerCase() == 'polygon')
         || (geojson_feature_type.toLowerCase() == 'multipolygon'))
        {

           //  ------------- polygon   -----------------------

              map.addLayer({
                  "id": "polygon-fills",
                  "type": "fill",
                  "source": "_geojson_source",
                  "layout": {},
                  "paint": {
                            "fill-color": [
                                              /*
                                                'case', ['<', ['to-number', ['get', 'Rank2019']],  16 ], '#FFFFFF',   // white

                                                        ['>', ['to-number', ['get', 'Rank2019']],  161 ], '#000000',  // black

                                                        // others
                                                        '#00FF00'

                                               */

                                              //https://materializecss.com/color.html

                                              "step",
                                                        ['to-number', ['get', 'Rank2019']],
                                                        '#FFFFFF',      // white
                                                        16,  '#e6ee9c',  // lime lighten-3
                                                        44,  '#009688',  //  teal
                                                        110, '#d84315', // deep-orange darken-3
                                                        162, '#000000'   // black

                                              ],

                            "fill-opacity": ["case",
                                                ["boolean", ["feature-state", "hover"], false],
                                                0,
                                                0.7
                                            ]
                            }
                  });

              map.addLayer({
                  "id": "polygon-borders-line",
                  "type": "line",
                  "source": "_geojson_source",
                  "layout": {},
                  "paint": {
                                    "line-color": ["case",
                                               /*
                                                ["boolean", ["feature-state", "hover"], false],
                                                 __stroke_color_highlight,  //"#FF0000",  // red
                                                 __stroke_color    //  "#FFFF00" // yellow
                                                */

                                                ["boolean", ["feature-state", "click"], false],
                                                __stroke_color_highlight_clicked,   // orange
                                                __stroke_color    //  "#FFFF00" // yellow

                                            ],

                                    "line-width": ["case",
                                              ["boolean", ["feature-state", "hover"], false],
                                              5,
                                              1
                                          ]
                            }// paint
                  });

                  // When the user moves their mouse over the state-fill layer, we'll update the
                  // feature state for the feature under the mouse.
                  map.on("mousemove", "polygon-fills", function(e) {
                    if (e.features.length > 0) {

                          if (hoveredFeatureId) {
                                   map.setFeatureState({source: '_geojson_source', id: hoveredFeatureId}, { hover: false});
                                         }

                          //console.log('hover event e.features[0].id  >>>', e.features[0].id)

                          if (e.features[0].id) {

                            // have feature.id ( converted from properties, OBJECTID or default feature-array-index-id)
                            hoveredFeatureId = e.features[0].id;

                            map.setFeatureState({source: '_geojson_source', id: hoveredFeatureId}, { hover: true});

                          } else {

                            // missing feature.id, maybe because of feature properties - missing - ObjectID field.
                            // hover effect will failed.
                            console.log('missing feature.id, maybe because of feature properties - missing - ObjectID field.')
                            console.log('hover effect will failed. feature.id ( converted from properties, OBJECTID)');
                          }

                          //console.log('hoveredFeatureId = ',hoveredFeatureId)

                                //********* show event.feature.properties  *********
                                  //console.log('e.features[0].properties #### ', e.features[0].properties)
                                  var _highlight_feature_properties = e.features[0].properties
                                  show_info_outline_Tab(_highlight_feature_properties)

                                //********* show event.feature.properties  *********

                     } // if
                  }); // mousemove

                  // When the mouse leaves the state-fill layer, update the feature state of the
                  // previously hovered feature.
                  map.on("mouseleave", "polygon-fills", function() {
                              if (hoveredFeatureId) {
                                              map.setFeatureState({source: '_geojson_source', id: hoveredFeatureId}, { hover: false});
                                              }
                              hoveredFeatureId =  null;

                              empty_info_outline_Tab()
                  });

                  map.on("click", "polygon-fills", function(e) {

                          //console.log('clicked')

                          instance_tabs.select('list');   // open up locked tab

                          if (e.features.length > 0)
                          {

                                if (clickedFeatureId)
                                {
                                                    map.setFeatureState({source: '_geojson_source', id: clickedFeatureId}, { click: false});
                                }

                                if (e.features[0].id)
                                {

                                  // have feature.id ( converted from properties, OBJECTID)
                                  clickedFeatureId = e.features[0].id;

                                  map.setFeatureState({source: '_geojson_source', id: clickedFeatureId}, { click: true});

                                } else {

                                  // missing feature.id, maybe because of feature properties - missing - ObjectID field.
                                  // hover effect will failed.
                                  console.log('missing feature.id, maybe because of feature properties - missing - ObjectID field.')
                                  console.log('hover effect will failed. feature.id ( converted from properties, OBJECTID)');

                                } // else

                                //console.log('hoveredFeatureId = ',hoveredFeatureId)

                                //********* show event.feature.properties  *********
                                  //console.log('e.features[0].properties #### ', e.features[0].properties)
                                  var _highlight_feature_properties = e.features[0].properties
                                  //show_info_outline_Tab(_highlight_feature_properties)  // mouse over hover event
                                  show_listTab(_highlight_feature_properties)  // click event
                                //********* show event.feature.properties  *********

                          } // if
                        }); // click

               // ---- end ---- polygon ----


text: Q: Windows Task Scheduler in MVC PHP application I need to run a daily call to a controller action in my MVC application (CakePHP framework) and I know Windows Server can run a PHP script as a daily task in the Scheduled Task Manager. How would I call the method in the Controller if I can call it as www.test.com/reports/import -this imports from a .csv to a MYSQL table. Or in the script how would I tell it to follow CakePHP's MVC "workflow", call controller and call model method.


text:
Q: Is it possible to repeat a specific operation twice but only on Mondays? I need help with the below macro.
I run a macro for my report on a daily basis. But only on Mondays, I need to repeat the below operations two times more(3 times altogether):
Range("B8").End(xlToRight).Offset(, 0).Select
Selection.Copy
ActiveCell.Offset(0, 1).Select
ActiveSheet.Paste

Range("B9").End(xlToRight).Offset(, 0).Select
Selection.Copy
ActiveCell.Offset(0, 1).Select
ActiveSheet.Paste

I'm guessing that I need to use the Weekday(Now()) = vbMonday statement but not 100% sure how to use it with the above code.
Thanks in advance!

A: There are at least two ways to do it. The first one is to make it a separate Sub and to call it explicitly 3 times on Monday.
Sub TestMe()

    If Weekday(Now()) = vbMonday Then
        SomeSelection
        SomeSelection
        SomeSelection
    End If

End Sub

Sub SomeSelection()
    'OP Code
End Sub

The second one is to make a loop and to make sure it repeats 3 times on Monday:
Sub TestMe()

    Dim repeater As Long: repeater = 1
    If Weekday(Now()) = vbMonday Then repeater = 3

    Dim counter As Long
    For counter = 1 To repeater
        Range("B8").End(xlToRight).Offset(, 0).Select
        'OP code...
        ActiveSheet.Paste
    Next

End Sub


text:
Q: Fetching in a summary table MIN, MAX, AVERAGE for a specific data and AVERAGE for another data present in each worksheet How do I reduce manual work in excel without VBA code - just use of functions formulas to fetch into a summary table the output of MIN, MAX, AVERAGE for a specific data set (and one more AVERAGE on another dataset) in consecutive worksheets of a workbook. The data will be different in each worksheet. The summary represents the cycle time minimum, maximum and averages (and yield% average) of rubber batches being produced in a factory over time. There are approximately 50 different rubber products, so 50 worksheets in the workbook. I have provided sample workbook alongwith the output desired in the link attached. https://docs.google.com/spreadsheets/d/1Cb9eFBIMxq6zyw7bPd1Zetdews7JlX9W/edit?usp=sharing&ouid=107602068659746725053&rtpof=true&sd=true

A: Do you want to get the Worksheet names with formula in the Table?
If yes, try this method:

*

*Open the Workbook- go to Formula- Name Manager- New- enter Sheetname and the formula =GET.WORKBOOK(1):

*Enter the formula to get the Worksheet Names:

=INDEX(MID(Sheetname,FIND("]",Sheetname)+1,30),ROW(A1))&T(NOW())


text:
Q: Operator overloading adding two objects error I have no idea why this code should work, but tell me what to do if i want to add two objects
together. please. while you are trying to answer please be more noob specific
sorry for my bad english, I am an Indian, here is my code.
#include<iostream>

using namespace std;

class time
{
private:
    int sec;
    int mint;
    int hours;
public:
    int Inputsec;
    int Inputmint;
    int Inputhours;
time(int Inputsec, int Inputmint, int Inputhours):sec(Inputsec), mint(Inputmint), hours(Inputhours){};
time operator+(time Inputobj)
{
    time blah (sec+Inputsec,mint+Inputmint,hours+Inputhours);
    return blah;
}

void DisplayCurrentTime()
{
    cout << "The Current Time Is"<<endl<< hours<<" hours"<<endl<<mint<<"minutes"<<endl<<sec<<"seconds"<<endl;
}
};

int main()
{
time now(11,13,3);
time after(13,31,11);
time then(now+after);
then.DisplayCurrentTime();
}

code is working fine but it is giving me horrible output.
Where is my mistake?

A: Your addition operator is using unitinitialized member Inputsec, Inputmint and Inputhours variables. It should look like this:
time operator+(time Inputobj)
{
    return time(sec+InputObj.sec, mint+InputObj.mint, hours+InputObj.hours);
}

or
time operator+(time Inputobj)
{
    InputObj.sec += sec;
    InputObj.mint += mint;
    InputObj.hours += hours;
    return InputObj;
}

Or, even better, implement time& operator+=(const time& rhs); and use it in a non-member addition operator:
time operator+(time lhs, const time& rhs)
{
  return lhs += rhs;
}

You have two sets of member variables representing the same thing. You do not need this duplication.
One final remark: there is something called std::time in header<ctime>. Having a class called time, and using namespace std is asking for trouble. You should avoid both if possible (avoiding the second is definitely possible).

A: You should rewrite your operator+ at least as follows:
time operator+(time Inputobj)
{
    time blah time(sec+InputObj.sec, mint+InputObj.mint, hours+InputObj.hours);
    return blah;
}

also I think you should use the % operator for getting the correct time results:
time operator+(time Inputobj){
    int s = (sec+InputObj.sec) % 60;
    int m = (sec+InputObj.sec) / 60 + (mint+InputObj.mint) % 60;
    int h = (mint+InputObj.mint) / 60 + (hours+InputObj.hours) % 24;
    return time(s,m,h);
}

A: Your operator overloading function is using uninitialized variables. Initialize variables inputsec, inputmint, Inputhours in your constructor.
Moreover, try this:
time operator+ (time Inputobj)
{
   time blah (sec+Inputobj.sec, mint+Inputobj.mint, hours+Inputobj.hours);
   return blah;
}

A: Your error is your publics members with the same name as the parameter constructor, which are unitialized.
Try this :
#include <iostream>
using namespace std;

class time
{
private:
    int sec;
    int mint;
    int hours;
public:
time(int Inputsec, int Inputmint, int Inputhours):sec(Inputsec), mint(Inputmint), hours(Inputhours)
{
};

time operator+(time Inputobj)
{
    time blah (sec+Inputobj.sec, mint+Inputobj.mint, hours+Inputobj.hours);
    return blah;
}

void DisplayCurrentTime()
{
    cout << "The Current Time Is"<<endl<< hours<<" hours"<<endl<<mint<<"minutes"<<endl<<sec<<"seconds"<<endl;
}
};

int main()
{
time now(11,13,3);
time after(13,31,11);
time then(now+after);
then.DisplayCurrentTime();
}


text:
Q: How can I calculate a perimeter around a lat, long coordinate in Objective-C? I need to know how to calculate some sort of perimeter around a lat/long coordinate (in a floating point number) in an "if" statement that looks somewhat like this:
if (lat != perimeterLat && long != perimeterLong) {
    // alert
}

If there is a better way of doing this (instead of using an "if" statement) please let me know.
Thanks,
Jacob Cross
UPDATE:
Ok. So I figured it out. What I am going to do is this:
- (void)locationChange:(CLLocation *)newLocation:(CLLocation *)oldLocation {
    CLLocationCoordinate2D newCoordinate = [newLocation coordinate];
    CLLocationCoordinate2D oldCoordinate = [oldLocation coordinate];

    CLLocationDistance meters = [newCoordinate distanceFromLocation:oldLocation];
}

And that is going to be how I figure out the distance away.
Found Answer Here
Thanks for everyone's help!

A: On a sphere you can use the haversine formula to calculate the great circle distance between two points.

A: Ok. So I figured it out. What I am going to do is this:
- (void)locationChange:(CLLocation *)newLocation:(CLLocation *)oldLocation {
    CLLocationCoordinate2D newCoordinate = [newLocation coordinate];
    CLLocationCoordinate2D oldCoordinate = [oldLocation coordinate];

    CLLocationDistance meters = [newCoordinate distanceFromLocation:oldCoordinate];
}

And that is going to be how I figure out the distance away.
Found Answer Here
Thanks for everyone's help!
Jacob


text:
Q: Exception thrown after customizing ehcache.xml in grails application In my quest to personalize ehcache in my grails app, I added the following xml to the config directory:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" >
<diskStore path="/path/to/store/data"/>
<cacheManagerEventListenerFactory class="" properties=""/>
<defaultCache
   maxEntriesLocalHeap="10000"
   eternal="false"
   timeToLiveSeconds="120">
   <persistence strategy="none"/>
</defaultCache>
<cache name="Book"
  maxEntriesLocalHeap="10000"
  timeToIdleSeconds="300"
   />
<cache name="org.hibernate.cache.UpdateTimestampsCache"
  maxEntriesLocalHeap="10000"
  timeToIdleSeconds="300"
   />
<cache name="org.hibernate.cache.StandardQueryCache"
  maxEntriesLocalHeap="10000"
  timeToIdleSeconds="300"
   />
</ehcache>

To my surprise, when started, the grails app stops with the exception:
Caused by: net.sf.ehcache.CacheException: Error configuring from input stream. Initial  cause was null:9: Element <defaultCache> does not allow attribute "maxEntriesLocalHeap".
at    net.sf.ehcache.config.ConfigurationFactory.parseConfiguration(ConfigurationFactory.java:152)
at net.sf.ehcache.config.ConfigurationFactory.parseConfiguration(ConfigurationFactory.java:99)
... 30 more

Any hints ? I'm using grails 1.3.9; thanks.

A: Got the same problem with Spring, maxEntriesLocalHeap and maxEntriesLocalDisk threw the same exception. What seemed to work for me was using maxElementsInMemory and maxElementsOnDisk instead. Found them from javadoc.
Now, based on them being deprecated, I assume there was an older version of EHCache going on with my conf, as well as yours.
Based on this table, maxEntriesLocalHeap came on EHCache 2.5. Before that it was maxElementsInMemory. When I had trouble, I had used ehcache-spring-annotations, and as of this writing it is on version 1.2.0, coming with ehcache 2.4.5 - thus not supporting these properties.
After going for pure Spring config and explicit dependency to EHCache 2.5, problem went away and I was able to use the properties I originally intended to.

A: Tags like 'maxEntriesLocalHeapEhcache' or inner elements as 'persistence' have been added in the most recent version of Ehcache (2.6.x).
I'd go for:
A) Use 'maxElementsInMemory' (instead of 'maxEntriesLocalHeap'); use 'overflowToDisk' and 'diskPersistent' attributes (instead of the 'persistence' element), ...
B) Try to get the latest version of the plugin or add the latest jars manually to your project.

A: If you to use Hibernate
The versions 4.3.5 or 4.3.7 have a  dependency of  Ehcache 2.4.7 that version don't have the properties  maxEntriesLocalHeap and maxEntriesLocalDisk .
Documentation about Ehcache 2.4.x: http://ehcache.org/files/documentation/EhcacheUserGuide.pdf
My example using hibernate 4.3.5:

<defaultCache maxElementsInMemory="10000"
              eternal="false"
              timeToIdleSeconds="300"
              timeToLiveSeconds="600"
              diskSpoolBufferSizeMB="30"
              maxElementsOnDisk="10000"
              diskExpiryThreadIntervalSeconds="120"
              memoryStoreEvictionPolicy="LRU" statistics="false">
</defaultCache>

<cache
        name="org.hibernate.cache.spi.UpdateTimestampsCache"
        maxElementsInMemory="10000"
        eternal="false">
</cache>

<cache
        name="org.hibernate.cache.internal.StandardQueryCache"
        maxElementsInMemory="10000"
        eternal="false"
        timeToLiveSeconds="300">
</cache>

<!--
If you are concerned about cpu utilisation and locking in the DiskStore, you can set the
diskExpiryThreadIntervalSeconds to a high number - say 1 day. Or you can effectively turn it off by
setting the diskExpiryThreadIntervalSeconds to a very large value
-->
<cache
        name="br.com.atlantico.toi.model.calc.Anomalia"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"/>

A: Just as eis said, Hibernate-ehcache internally use ehcache 2.4.3, but attribute not support on that verion. You need to use a higher version of ehcache.
Here just try to add more detailed configurations :
Firstly,add both hibernate-ehcache and ehcache-core to maven pom.
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-ehcache</artifactId>
    <version>${hibernate.version}</version>
</dependency>
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache-core</artifactId>
    <version>2.6.5</version>
</dependency>

Then, set property for session factory in your spring configuration. Use classes from org.hibernate., instead of from net.sf.ehcache.
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory </prop>

A: I have faced the similar issue and I resolved by using the following jars.

*

*ehcache.2.9.jar

*logback-core-1.0.13.jar

*logback-classic-1.0.13.jar

you add above jars in your project path.. it will work fine.


text:
Q: JSP and SQL Data insertion Currently I'm having a bugin my JSP while trying to insert data into a a Database. Im using Java class to do this to avoid the scriplets at all cost. Thing is that when I want to insert data into 3 different tables, only the first table gets fill while doing this in JSP. You know filling forms, sending data to class and there the database gets fill. YET if I do it stand alone Java App, all tables get filled up in only one function. JSP doesnt work, Java app does? What?
This is the java class:
public void fileDataToDB(String file1, String file2, String file3, String aPath, String operationUsed) {

        try {
        Class.forName("com.mysql.jdbc.Driver");
        connectMe = DriverManager.getConnection(url+dbName, userNameDB, passwordDB);

        String query = "INSERT INTO MatrixUsers.FilePath (idFilePath, LocationFiles) VALUES (?, ?)";
        String query2 = "INSERT INTO MatrixUsers.Sessions (idSessions, Matrix1, Matrix2, Result) VALUES (?, ?, ?, ?)";
        String query3 = "INSERT INTO MatrixUsers.Operations (idOperations, Operation) VALUES (?,?)";

        selectUsers = connectMe.prepareStatement(query2);

        selectUsers.setInt(1, id);
        selectUsers.setString(2, file1);
        selectUsers.setString(3, file2);
        selectUsers.setString(4, file3);
        selectUsers.executeUpdate();

        tip1 = "First table done!";

        if(aPath != null)
            contains = "Path is filled!";

        selectUsers.close();

        selectUsers = connectMe.prepareStatement(query);

        selectUsers.setInt(1, id);
        selectUsers.setString(2, aPath);

        selectUsers.executeUpdate();

        tip2 = "Second table done!";

        selectUsers.close();

        selectUsers = connectMe.prepareStatement(query3);

        selectUsers.setInt(1, id);
        selectUsers.setString(2, operationUsed);
        selectUsers.executeUpdate();

        tip3 = "Third table done!";

        selectUsers.close();

        connectMe.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

NOTE: I use this in the JSP and Java app and is the same. The TIPS variables are only used to know where does the code cut. In the JSP it cuts at first table, the others return null meaning the other queries never get executed. Also the container variable is to know if the aPath variable is fill and it returns that contains something. So I think those to doubts are out of question. Why does it cut like that? When this is exacly the same in the Java app.

A: SOLUTION: Row was smaller than the String aPath, changed row size from varchar(45) to varchar(255) and problem solved!
Thanks to dave823 and cigno5.5 for the info on the log file.


text:
Q: Dumping data into Excel from C# using set_Value throws an error I am trying to dump data into an Excel file. The following is the code we use.
Note: dt is a DataTable passed from another function.
        ApplicationClass xlsApp = new ApplicationClass();
        WorkbookClass xlsWb = null;
        Worksheet xlsWs = null;
        Range ExcelCellText;

        try
        {
            xlsWb = (WorkbookClass)xlsApp.Workbooks.Open(@"E:\WorkingFolder\Code\EnVazhi2.xls", 0, false, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlsWs = (Worksheet)xlsWb.Worksheets.get_Item(1);

            ExcelCellText = xlsWs.get_Range("A1", Missing.Value);
            ExcelCellText = ExcelCellText.get_Resize(dt.Rows.Count, dt.Columns.Count);
            string[,] myArray = new string[dt.Rows.Count, dt.Columns.Count];

            int iRow=0;

            foreach(DataRow dr in dt.Rows)
            {
                for (int iCol = 0; iCol < dt.Columns.Count; iCol++)
                {
                    myArray[iRow, iCol] = dr[iCol].ToString();
                }
                iRow++;
            }
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            ExcelCellText.set_Value(Missing.Value, myArray);
        }
        catch (Exception ex)
        {
            Console.Write(ex.Message);
        }

It throws the exception

Exception from HRESULT: 0x800A03EC

at the line
            ExcelCellText.set_Value(Missing.Value, myArray);

The Excel file is partly populated. The exception happens when it tries to copy this value from myArray into the Excel.

Enawvg Xnhe/Bcrengvbaf/Ubzr
  Bssvpr/ZnkArjLbexYvsr  10-02-2009
  09:39 NZ       Gb PPEC/Bcrengvbaf/Ubzr
  Bssvpr/ZnkArjLbexYvsr@ZnkArjLbexYvsr
  pp
Fhowrpg Sj: cyf vagvngr ershaq
Uv,
cyrnfr svaq gur pbeerpg cbyvpl ahzore
268538840
Enawvg Xnhe
----- Sbejneqrq ol Enawvg Xnhe/Bcrengvbaf/Ubzr
  Bssvpr/ZnkArjLbexYvsr ba 02/10/2009
  09:38 NZ ----- PPEC/Bcrengvbaf/Ubzr
  Bssvpr/ZnkArjLbexYvsr 02/09/2009 05:37
  CZ       Gb Enawvg
  Xnhe/Bcrengvbaf/Ubzr
  Bssvpr/ZnkArjLbexYvsr@ZnkArjLbexYvsr
  pp
Fhowrpg Er: cyf vagvngr ershaq
Uv
Gunax lbh sbe jevgvat gb Phfgbzre
  Freivprf ng Znk Arj Lbex Yvsr
  Vafhenapr.
Jr npxabjyrqtr gur erprvcg bs lbhe
  inyhnoyr srrqonpx naq bhe Phfgbzre
  Freivpr Rkrphgvir jvyy trg va gbhpu
  jvgu lbh va gur arkg 48 ubhef.
Cyrnfr abgr gung gur ersrerapr ahzore
  sbe lbhe srrqonpx ner
268538295 2141982 268598840 vapbeerpg
  ab.
Jr erdhrfg lbh gb dhbgr gur nobir
  ahzore va nyy shgher pbzzhavpngvba
  jvgu ZALY ercerfragngvirf.
Lbh znl nyfb trg va gbhpu jvgu bhe
  Phfgbzre Uryc Yvar ahzore 1800 180
  5577 (gbyy serr vs pnyyvat sebz ZGAY
  be OFAY argjbex) be 0124-2542001
Gunaxf naq Ertneqf Xnenz Fvatu
  Phfgbzre Freivprf Znk Arj Lbex Yvsr
  Vafhenapr Pb. Ygq. Bcrengvba Pragre,
  Cybg Ab. - 90 N Frpgbe - 18, Hqlbt
  Ivune Thetnba - 122002 Gry - 0124 -
  2542001 Gbyy Serr - 1800-180-5577 Snk
  ahzore -- 0124 - 4239683
Enawvg Xnhe/Bcrengvbaf/Ubzr
  Bssvpr/ZnkArjLbexYvsr  09-02-2009
  03:07 CZ       Gb PPEC/Bcrengvbaf/Ubzr
  Bssvpr/ZnkArjLbexYvsr@ZnkArjLbexYvsr
  pp
Fhowrpg cyf vagvngr ershaq
Uv,
cyf ybt n serfu pnfr
ershaq purdhr abg erprvirq
268538295 268598840
Enawvg Xnhe

Why does it throw an error? Is there a known issue with set_Value?
I tried the following two options described here at Link 1
Any suggestions or advice is greatly appreciated! Thanks!
EDIT
This code works perfectly fine when I use Microsoft Office Excel 2007 SP 2.
The version/SP of Microsoft Office Excel 2003 where it fails is this the Standard Release (with NO SP's installed).

A: It seems you have run up on a limitation of Excel itself. So the [unfortunate] answer to your question is yes - there is a known issue with set_value. The best workaround is to check to see if the user has a minimum version of Excel and react accordingly (don't run, truncate to 1000 chars, split the text across multiple fields, skip those cells, etc).
Probably not what you wanted to find out. I wrote this as an answer instead of continuing the comment trail but feel free to write and accept your own answer.


text:
Q: Filter mysql results based on checkboxes I am trying to filter mysql results based on checkboxes that have been ticked. My query works on the first check but returns nothing on the second filter. My checkbox array is $_POST['country'] which I implode in the GetSQLValueString function to create the comma separated values - (United Kingdom, France) etc. I am using the MySQL IN clause for the multiple selections.
I need it to filter multiple country selections
if (isset($_POST['country_submit']) && $_POST['country'] != '') {
    mysql_select_db($database_tub, $tub);
    $query_trade = sprintf("
SELECT u.user_id,
       u.contact_person,
       u.company,
       u.country,
       u.pic_small,
       u.website,
       SUM(u.trader_or_bond = %s
           AND t.user_id IS NOT NULL) AS count
FROM users u
LEFT JOIN trading t ON u.user_id = t.user_id
WHERE u.trader_or_bond = %s AND u.country IN(%s)
GROUP BY u.user_id
ORDER BY COUNT(t.user_id) DESC",
GetSQLValueString('trader', "text"),
GetSQLValueString('trader', "text"),
GetSQLValueString(implode(',', $_POST['country']), "text"));
    $trade = mysql_query($query_trade, $tub) or die(mysql_error());
}

A: I have come up with this but not sure if safe for MySQL injection plus its not as clean as I would like.
if (isset($_POST['country_submit']) && $_POST['country'] != '') {

$SingleQuotes = "'".implode("', '", array_map('mysql_real_escape_string', $_POST['country']))."'";
    mysql_select_db($database_tub, $tub);
    $query_trade = sprintf("
SELECT u.user_id,
       u.contact_person,
       u.company,
       u.country,
       u.pic_small,
       u.website,
       SUM(u.trader_or_bond = %s
           AND t.user_id IS NOT NULL) AS count
FROM users u
LEFT JOIN trading t ON u.user_id = t.user_id
WHERE u.trader_or_bond = %s AND u.country IN($SingleQuotes)
GROUP BY u.user_id
ORDER BY COUNT(t.user_id) DESC",
GetSQLValueString('trader', "text"),
GetSQLValueString('trader', "text"));
$trade = mysql_query($query_trade, $tub) or die(mysql_error());
}


text:
Q: Webpack doesn't recognize node I already add node to the types field in my tsconfig.json. Also, I did npm i @types/node. But webpack doesn't recognize node in webpack.config.ts.
Errors:

*

*Cannot find name 'require'. Do you need to install type definitions for node? Try npm i @types/node and then add node to the types field in your tsconfig.ts(2580)

*Cannot find name '__dirname'.ts(2304)

This is my tsconfig.json
{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": false,
    "esModuleInterop": true,
    "module": "commonjs",
    "target": "es2015",
    "jsx": "react",
    "baseUrl": "src",
    "typeRoots": ["/node_modules/@types", "@types"],
    "types": ["node"]
  },
  "include": ["./src/**/*.tsx", "./src/**/*.ts"],
  "exclude": ["./node_modules", "./**/*.spec.ts"]
}


text:
Q: How to pass omitted argument to the next function? In matlab I can omit arguments of a function, for example
function res = caller(a, b)
...

I can call it with
caller(12)

But how can I pass this absent argument further, for example:
function res = caller(a, b)
   callee(a, b)
   ...

How can I make that if caller is called without secong argument, then callee also called without second argument?
UPDATE
Suppose you have many functions calling each other
function res = caller01(a, b)
    ...

function res = caller02(a, b)
    ...

function res = caller03(a, b)
    ...

function res = caller04(a, b)
    ...

and you want to
1) make argument b optional
2) make it possible to delegate default to callee
As far as I understood, Matlab is incomplete here and requires me to wrap each call to callee into this scaffold:
if exist('b', 'var')
   callee(a, b);
else
   callee(a);
end

and this should be repeated in each caller.

A: There are different options here.
Option 1
function res = caller(varargin)
   callee(varargin{:})
   ...

Here we capture all input arguments in varargin, and pass them unchecked to callee.
Option 2
function res = caller(a, b)
   if nargin == 0
      callee()
   elseif nargin == 1
      callee(a)
   else if nargin == 2
      callee(a, b)
   end
   ...

Here we check the number of input arguments, and call callee with the arguments we were given.
Option 3
function res = caller(a, b)
   if nargin<1
      a = rand(10);
   end
   if nargin<2
      b = 'default value';
   end
   callee(a, b)
   ...

Here we check input arguments, and use default values for non-specified input arguments.

Edit: It is possible to do a hybrid here also. Say a is a required argument, and b is an optional one. We let MATLAB handle the required argument (it automatically generates the appropriate error messages when not provided), and put b into varargin, which we can use to call callee with the same number of input arguments we got, and also unpack to generate the local variables we need for further processing:
function res = caller(a,varargin)
   callee(a,varargin{:})
   if numel(varargin)>=1
      b = varargin{1};
   end
   ...

A: I usually do a simple 'if block', to my knowledge this is unavoidable if you want to preserve your caller(a,b) function in the form provided.
Something flexible I use often:
function res = caller(a, b)
  if exist('b','var')
    callee(a,b)
  else
    callee(a)
  end
end

alternatively you can use varargin and 'pipe' whatever arguments came in, directly into callee as already mentioned by Cris, and handle whatever varargin is within callee.
function res = caller(varargin)
  callee(varargin{:})
end


text:
Q: Python: Find the two prime factors of a number. how to make this code more efficiency?
My current code:
import math
def factorMe(value):
last = int(math.sqrt(value)+1)
for i in range(2,last):
    if value %i ==0:
        return (i,int(value/i))

My code can meet most test case; But if the input is 603091532958059
then the answer will be (24557917, 24557927); But it will take more than 1 second to finish (Time limit exceeded);
Any suggestion? Thank you!

A: To speed up your code you could use Fermat's factorization method, as @PM 2Ring told in comments. Try following code
import math
def factorMe(value):
    last = int(math.sqrt(value)+1)
    # check if value is even
    if value % 2 == 0:
        return (2, int(value / 2))
    # value is odd number
    a = int(math.sqrt(value)) + 1
    b2 = int(a * a - value)
    b = int(math.sqrt(b2))
    while b ** 2 != int(b2):
        a += 1
        b2 = a * a - value
        b = int(math.sqrt(b2))
    return (int(a - math.sqrt(b2)), int(a + math.sqrt(b2)))

v = 603091532958059
%timeit r = factorMe(v)
print(r)

100000 loops, best of 3: 2.15 µs per loop
(24557917, 24557927)


text:
Q: Почему в мобильной версии белые отступы по бокам? В версии для экранов 320px если открывать с телефона, то почему-то по бокам экрана белые отступы, что естественно быть не должно.
В чем здесь может быть причина?

A: У вас же в стилях прописано:
@media screen and (max-width: 840px)
.bestsellers-main>div {
    display: block;
    width: 290px;
    margin: 0 auto;
}

Ширина экрана 320px

A: Используй удаленную отладку https://developer.chrome.com/devtools/docs/remote-debugging и всё тайное стайнет явным. Вообще Remote Debugging это неотъемлемая часть при разработке под мобильные устройства.


text:
Q: ZSH: Behavior on Enter I realize, when I'm in my terminal, I would expect to press Enter on empty input to make a ls or a git status when I'm on a git repos.
How can I achieve that? I mean, have a custom behavior on Empty input -> Enter in zsh?

EDIT: Thanks for the help. Here's my take with preexec...
precmd() {
  echo $0;
  if ["${0}" -eq ""]; then
    if [ -d .git ]; then
      git status
    else
      ls
    fi;
  else
    $1
  fi;
}

A: On Enter zsh calls the accept-line widget, which causes the buffer to be executed as command.
You can write your own widget in order to implement the behaviour you want and rebind Enter:
my-accept-line () {
    # check if the buffer does not contain any words
    if [ ${#${(z)BUFFER}} -eq 0 ]; then
        # put newline so that the output does not start next
        # to the prompt
        echo
        # check if inside git repository
        if git rev-parse --git-dir > /dev/null 2>&1 ; then
            # if so, execute `git status'
            git status
        else
            # else run `ls'
            ls
        fi
    fi
    # in any case run the `accept-line' widget
    zle accept-line
}
# create a widget from `my-accept-line' with the same name
zle -N my-accept-line
# rebind Enter, usually this is `^M'
bindkey '^M' my-accept-line

While it would be sufficient to run zle accept-line only in cases where there actually was a command, zsh would not put a new prompt after the output. And while it is possible to redraw the prompt with zle redisplay, this will probably overwrite the last line(s) of the output if you are using multi-line prompts. (Of course there are workarounds for that, too, but nothing as simple as just using zle accept-line.
Warning: This redfines an (the most?) essential part of your shell. While there is nothing wrong with that per se (else I would not have posted it here), it has the very real chance to make your shell unusable if my-accept-line does not run flawlessly. For example, if zle accept-line were to be missing, you could not use Enter to confirm any command (e.g. to redefine my-accept-line or to start an editor). So please, test it before putting it into your ~/.zshrc.
Also, by default accept-line is bound to Ctrl+J, too. I would recommend to leave it that way, to have an easy way to run the default accept-line.

A: In my .zshrc I use a combination of precmd and preexec found here:
http://zsh.sourceforge.net/Doc/Release/Functions.html#Hook-Functions
I also find that the git-prompt is super useful:
https://github.com/olivierverdier/zsh-git-prompt


text:
Q: Subqueries in FROM clauses not working anymore with new wampserver version Using wampServer 3.0.6 + MySQL 5.7.14, none of my subqueries in a FROM clause is working anymore while using wampServer 2.5 + MySQL 5.6.17 on another pc, it is perfectly working.
Here are 2 examples of these queries among tens of them
( Please note that in reality, these examples are used as subqueries of larger ones but don't work individually either ) :
Query 1 :
    SELECT rnbr.*
    FROM
        (
            SELECT Rct_Pub_Mbr_Id,
                   COUNT(Rct_Id) AS Nbr
                   FROM recits
            WHERE Rct_Rct_Val_Id = 2 AND
                  Rct_Pub_Mbr_Id = 2
            GROUP BY Rct_Pub_Mbr_Id
        ) AS rnbr

Query 2
    SELECT base.*
    FROM
        (
          SELECT Mbr_Rel_CRel_Id,
                 Mbr_Rel_Mbr_Id_2
          FROM membres_relations
          WHERE Mbr_Rel_Mbr_Id_1 = 16 AND
                Mbr_Rel_Mbr_Id_2 = 2 AND
                Mbr_Rel_CRel_Id = "BLK"
        ) AS base

On top of that, writing theses queries in phpMyAdmin (4.6.4) SQL tab, I get the following errors ( examples taken from second query )  :
. on the line with "(" after the FROM clause :
    . An expression was expected ( close to ( )
    . Unexpected token ( close to ( )
. on the line with SELECT after the "(" :
    . this type of clause has already been analised ( close to SELECT )
. on the line with ") AS base" :
    . Unexpected token ( close to ) )
    . key word not recognized ( close to AS )
    . Unexpected token ( close to base )

None of these happens with the former/other versions.
As it is systematic, it is not due to the content of the queries it self but it looks more like something was "wrong" with the new configuration...
Does anyone have any idea of what could be done ?

A: I found the solution !
It was in fact a question of Wampserver, MySQL and phpMyadmin versions.
Here is what to do if it happens to you :

*

*Save the directory on wich your programs/sub-directories are
( c:/wamp/www/your directory )

*Export the full content of your database ( SQL mode )

*Uninstall wampserver and be sure the c:/wamp directory doesn't exist anymore

*Go to Secondary repository of Wampserver files.

*Load Wampserver 3.0.6 ( note that if you're loading the 64 bits version, you should change the proposed directoy to c:/wamp )

*Load Wampserver update 3.0.9

*Load MySQL 5.6.xx ( I loaded 5.6.37 )

*Load a former version of phpMyadmin ( I loaded version 4.1.14 wich is the one of my previous configuration )

*Launch Wampserver

*[left-click] on Wampserver in the taskbar - MySQL - Version - 5.6.37

*[left-click] on Wampserver in the taskbar - MySQL - Configuration - SQL mode - select "none"

*[right-click] on Wampserver in the taskbar - Parameters - Check "Alias sub-menus"

*To launch phpMyadmin, instead of clicling on "phpMyadmin", choose "your aliases" and then the phpMyadmin version you want to use

*Copy your saved directory ( point 1 ) onto c:/wamp/www/

*Import your tables and their content using the export SQL you did on point 2.

*Everything should work again !

I know it looks quite tricky but it works...
Good luck !


text:
Q: In R2\(axis X)the two nullhomotopic functions are not homotopic I want to prove that in space R2\X  the two functions f&g are not homotopic if we define g(x)=c1& f(x)=c2
c1 and c2 are two points one of the above axis X and the othe one is under it

A: Fix a point $p$ in the domain of $f$ and $g$ and suppose there is a homotopy $H \colon D \times I \to \mathbb{R}^2 - X $ between $f$ and $g$.  Then $H$ restricted to $\{p\} \times I $ is a path between $c_1$ and $c_2$, which is impossible since they lie in different path components of $\mathbb{R}^2 - X$.


text:
Q: What am I looking for to debug this elisp? I have an org-mode file that I'm trying to export to a Beamer LaTeX PDF through XeTeX. It was working fine last night on this machine, and just as well on another machine on which I edited it afterward. Both are running org-mode 8, Emacs 24, same export process (3 runs of XeLaTeX)
When I synced back to this machine and tried to export again, I got the error Wrong block type at a headline named "". I checked all my headlines and gave them all names, but still got the same result.
Thanks to the wonders of indexed searchable FLOSS code, I immediately found the snippet online:
(env-format
      (cond ((member environment '("column" "columns")) nil)
        ((assoc environment
            (append org-beamer-environments-extra
                org-beamer-environments-default)))
        (t (user-error "Wrong block type at a headline named \"%s\""
                   raw-title))))

I'm not really solid on elisp at all, though, and I don't know most of what's going on here. From this snippet, what would I do to start debugging? (I realize I can start the emacs debugger, but it's not a PKE meter, I can't just wave it around.)

A: IMHE the best way to figure out what's wrong when you've found the relevant snippet of code is to use Edebug.
You should read the documentation to learn more about it, but basically here is my procedure:

*

*identify the part of the code that crashes

*instrument the code with Edebug (C-uC-M-x)

*re-execute the code and go step by step to figure out what's going on (n)

*If the problem is in another function, jump to it GOTO 2.

Iterate until you've understood the code and find a way to fix it.

A: Posting this answer just so that the specific solution to the particular problem the error was flagging is understood.
Apparently the version of Beamer I have on the other machine has a "normal" Beamer environment that specifies an otherwise blank, unformatted block. This is not present in this machine's install, or at least org/XeLaTeX don't know about it.
My steps were:

*

*Search for all unnamed headings

*Name each of them uniquely

*Reproduce the error with the identifying string

*Check the block type property against the available type list given in org-beamer-mode

*Remove the offending type and replace it with another one

This is great and all, but I don't think it's the "best answer" because it involves no actual understanding of what the emacs interpreter was trying to tell me. If I didn't have a good idea of what was going on generally with the TeX, there's no way it would have worked. Dunno if this technique would impress anybody at an interview ;)


text:
Q: How get a resource in Java with a # (hashtag) in the file path? When there is a file called "#" in the resources directory and I execute getClass().getResource("/#");, it returns
file:/T:/IDEA/webfox/target/classes/%23
The # converted to a %23. How do I prevent this? These methods are not helping:

*

*toString(): file:/T:/IDEA/webfox/target/classes/%23

*toURI(): file:/T:/IDEA/webfox/target/classes/%23

*toExternalForm(): file:/T:/IDEA/webfox/target/classes/%23

*getFile(): /T:/IDEA/webfox/target/classes/%23

*getPath(): /T:/IDEA/webfox/target/classes/%23
My desired output would be: T:/IDEA/webfox/target/classes/#
This is needed because I use a TomCat application which file name is ROOT##1.1. Trying to save into resources ends up like this:


text:
Q: Object detection on raspberry pi I am trying to run the following project:
https://github.com/krishrustagi/Accident-Detection-System
I do not know what I am doing wrong.This project seems really interesting and I really want to learn more about it.
How do I get the github repository above to work.
Maybe a simple fix?
Here is the error code I get when executing the camera.py command:
(env) pi@raspberrypi:~/Project/Accident-Detection-System $ python3 camera.py    Traceback
(most recent call last):
File "/home/pi/Project/Accident-Detection-System/camera.py", line 6, in <module>
model = AccidentDetectionModel("model.json", 'model_weights.h5')
File "/home/pi/Project/Accident-Detection-System/detection.py", line 15, in __init__
self.loaded_model.load_weights(model_weights_file)
File "/home/pi/Project/Accident-Detection-System/env/lib/python3.9/site-
packages/keras/utils/traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/home/pi/Project/Accident-Detection-System/env/lib/python3.9/site-
packages/h5py/_hl/files.py", line 533, in __init__
fid = make_fid(name, mode, userblock_size, fapl, fcpl, swmr=swmr)
File "/home/pi/Project/Accident-Detection-System/env/lib/python3.9/site-
packages/h5py/_hl/files.py", line 226, in make_fid
fid = h5f.open(name, flags, fapl=fapl)
File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "h5py/h5f.pyx", line 106, in h5py.h5f.open
FileNotFoundError: [Errno 2] Unable to open file (unable to open file: name =
'model_weights.h5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags
= 0)

A: The error trace is telling you that the file model_weights.h5 does not exist anywhere in the project root directory.
After looking at the GitHub repo, it seems that model.json exists but model_weights.h5 does not, while both are supplied as arguments in camera.py Line 6:
model = AccidentDetectionModel("model.json", 'model_weights.h5')
The README mentioned this in Section 5:

accident-classification.ipynb: This is a jupyter notebook that generates a model to classify the above data. This file generates two important files model.json and model_weights.h5.

Hence you should run accident-classification.ipynb first before running camera.py.


text:
Q: Pyspark : Convert nested JSON struct to pyspark dataframe Is there an easy way to convert the below sample json into Pyspark dataframe ?
Input :
{
"user": {
  "1": {
    "name": "Joe",
    "age": 28
  },
  "2" :{
    "name": "Chris",
    "age": 14
  },
  "3" :{
    "name": "Hally",
    "age": 21
  }
}
}

Expected output (dataframe):
root
 |-- age: long (nullable = true)
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)

+---+---+-----+
|age|id |name |
+---+---+-----+
|28 |1  |Joe  |
|14 |2  |Chris|
|21 |3  |Hally|
+---+---+-----+

A: Read the JSON into dataframe, get the list of user IDs then create an array and explode it into multiple rows like this:
from pyspark.sql import functions as F

json_example = '{"user":{"1":{"name":"Joe","age":28},"2":{"name":"Chris","age":14},"3":{"name":"Hally","age":21}}}'
df = spark.read.json(spark.sparkContext.parallelize([json_example]))

result = df.select(F.array(*[
    F.struct(F.lit(i).alias("id"), F.col(f"user.{i}.name"), F.col(f"user.{i}.age"))
    for i in df.select("user.*").columns
]).alias("users")).selectExpr("inline(users)")

result.show()
#+---+-----+---+
#| id| name|age|
#+---+-----+---+
#|  1|  Joe| 28|
#|  2|Chris| 14|
#|  3|Hally| 21|
#+---+-----+---+

Or simply using stack expression:
from itertools import chain

df1 = df.select("user.*")

result = df1.selectExpr(
    f"stack({len(df1.columns)}," + ','.join(chain(*[(f"`{c}`", c) for c in df1.columns])) + ")"
).selectExpr("col1 as id", "col0.*")

A: You can just chain with DataFrame and apply Series
out = pd.DataFrame(input).user.apply(pd.Series).rename_axis('id').reset_index()
Out[110]:
  id   name  age
0  1    Joe   28
1  2  Chris   14
2  3  Hally   21


text:
Q: Is there a better way to use asynchronous TCP sockets in C++ rather than poll or select? I recently started writing some C++ code that uses sockets, which I'd like to be asynchronous. I've read many posts about how poll and select can be used to make my sockets asynchronous (using poll or select to wait for a send or recv buffer), but on my server side I have an array of struct pollfd, where every time the listening socket accepts a connection, it adds it to the array of struct pollfd so that it can monitor that socket's recv (POLLIN).
My problem is that if I have 5000 sockets connected to my listening socket on my server, then the array of struct pollfd would be of size 5000, since it would be monitoring all the connected sockets BUT the only way I know how to check if a recv for a socket is ready, is by looping through all the items in the array of struct pollfd to find the ones whose revents equals POLLIN. This just seems kind of inefficient, when the number of connected sockets because very large. Is there a better way to do this?
How does the boost::asio library handle async_accept, async_send, etc...? How should I handle it?

A: What the heck, I will go ahead and write up an answer.
I am going to ignore the "asynchronous" vs "non-blocking" terminology because I believe it is irrelevant to your question.
You are worried about performance when handling thousands of network clients, and you are right to be worried. You have rediscovered the C10K problem. Back when the Web was young, people saw a need for a small number of fast servers to handle a large number of (relatively) slow clients. The existing select/poll type interfaces require linear scans -- in both kernel and user space -- across all sockets to determine which are ready. If many sockets are often idle, your server can wind up spending more time figuring out what work to do than doing actual work.
Fast-forward to today, where we have basically two approaches for dealing with this problem:
1) Use one thread per socket and just issue blocking reads and writes. This is usually the simplest to code, in my opinion, and modern operating systems are quite good at letting idle threads sleep peacefully out of the way without imposing any significant performance overhead. In my experience, this approach works very well for hundreds of clients; I cannot personally say how it will work for thousands.
2) Use one of the platform-specific interfaces that were introduced to tackle the C10K problem. That means epoll (Linux), kqueue (BSD/Mac), or completion ports (Windows). (If you think epoll is the same as poll, look again.) All of these will only notify your application about sockets that are actually ready, avoiding the wasteful linear scan across idle connections. There are several libraries that make these platform-specific interfaces easier to use, including libevent, libev, and Boost.Asio. You will find that all of them ultimately invoke epoll on Linux, kqueue on BSD, and so on, whenever such interfaces are available.


text:
Q: SVD on TFIDF Matrix returns an odd shape The overarching problem:
I thought that running fit_transform on the model TruncatedSVD on SparseVectors from TfidfVectorizer would yield components with dimension (n_samples, n_components), as noted here (jump down to the fit_transform section).
However, I am getting back a matrix of shape (n_components, n_words).
Here is a trivial example to recreate the problem:
def build_tfidf_model(corpus):
    transformer = TfidfVectorizer(analyzer='word')
    matrix = transformer.fit_transform(corpus)
    return matrix

def svd_tfidf_matrix(matrix):
    svd = TruncatedSVD(n_components=3)
    svd.fit_transform(matrix)
    return svd.components_

corpus = ['sentence one', 'sentence two', 'another one', 'another sentence', 'two sentence', 'one sentence']
tfidf_model = build_tfidf_model(corpus)
reduced_vectors = svd_tfidf_matrix(matrix=tfidf_model)

So, tfidf_model.shape yields (6, 4). This makes sense to me. I have a corpus of six documents, which contain a total of 4 distinct words.
However, reduced_vectors.shape yields (3,4). I was expecting it to be of shape (6,3).
I must be misunderstanding what calling fit_transform is supposed to return. What can I call for SVD to get it to return a matrix where the rows are the documents and the columns are the features in the reduced space?

A: If you want the input represented in the transform space, then fit_transform will return that object. Currently youre calling it without assigning the result to a variable. The model.components_ attributes merely describe how you can transform the tfidf vector space to the svd space.
def svd_tfidf_matrix(matrix):
    svd = TruncatedSVD(n_components=3)
    return svd.fit_transform(matrix)