source
sequence
text
stringlengths
99
98.5k
[ "blender.stackexchange", "0000082310.txt" ]
Q: Shrinkwrap ngons face I have a ngon face (upper face of a sole): I would like to deform this face according to another mesh: So I thought to use a shrinkwrap (With project z>0). But as my face has only vertices "around" the sole, I cannot deform my face. So my idea was to use ALT + P to subdivide the face. But this solution only create a vertice, central point for all faces: So, when applying the shrinkwrap, only the outside vertices and this new vertice are moved. Do you have an idea to make an ngons face working with shrinkwrap? Thanks, Maxime A: As you have learned, ngons do not subdivide or deform well, and that is the very reason they should be avoided... Also, the quality of the deformation is directly related to the amount of subdivisions of your mesh so you need a lot more vertices and faces. A possible solution is to create a surface made out of quads. Delete all the faces and subdivide (W) that long edge on the left side: Make sure that you end up with an even number of vertices for the whole object Select all of the vertices ( A) Press the space bar and type Grid fill (note that if you have an odd number of vertices the grid fill operation will fail) Then play with the values for Span to get a nice distribution for the newly created quad faces. The mesh will deform much better now.
[ "stackoverflow", "0017469570.txt" ]
Q: jquery knob cursor width in percentage i am using jquery knob and in my use case I want the cursor width in percentage so that when the width is 100% cursor occupies the whole circle, however it only takes numeric value as input, what are my options ? $(function() { $(".dial1").knob({ 'bgColor': 'green', "skin":"tron", 'fgColor': 'red', 'cursor': '100' }); }); The cursor fills the whole circle if I give it a value of 320. A: I am using a workaround where in if I want x percentage to show and total is y then I am doing (x/y)*320 it gives the cursor width in percentage since x is dynamic the cursor keeps on filling the circle as this value increases. Since this is a very specific issue and I don't expect any other answer coming soon am marking this as the answer.
[ "stackoverflow", "0015158104.txt" ]
Q: Stretching one table row to the size of another I'm developing a yatzy game and the player get to choose where to put its score from a dialog. However I'm having a bit of trouble with making the layout doing what I want it to. I've splitted up the regular score card to avoid scrolling on smaller screens and placed the two parts in separate table layouts. These two table layouts contain a different amount of rows and have different heights. Can anyone tell me how to stretch the right table layouts rows in order to give them the same height? Here's a pic: And here's the layout xml: <LinearLayout android:id="@+id/tableLayoutHolder" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tvTitle" android:layout_centerHorizontal="true" android:baselineAligned="false" > <TableLayout android:id="@+id/tableLayoutLeft" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TableRow android:id="@+id/tableRow0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/dice_border_gray" android:src="@drawable/d1" /> <TextView android:id="@+id/tv0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <ImageView android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/dice_border_gray" android:src="@drawable/d2" /> <TextView android:id="@+id/tv1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <ImageView android:id="@+id/imageView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/dice_border_gray" android:src="@drawable/d3" /> <TextView android:id="@+id/tv2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <ImageView android:id="@+id/imageView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/dice_border_gray" android:src="@drawable/d4" /> <TextView android:id="@+id/tv3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <ImageView android:id="@+id/imageView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/dice_border_gray" android:src="@drawable/d5" /> <TextView android:id="@+id/tv4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <ImageView android:id="@+id/imageView6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/dice_border_gray" android:src="@drawable/d6" /> <TextView android:id="@+id/tv5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <TextView android:id="@+id/tvScUpperSum" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tv_black_right_border" android:text="@string/sum" /> <TextView android:id="@+id/tv6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow7" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <TextView android:id="@+id/tvScBonus" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tv_black_right_border" android:text="@string/bonus" /> <TextView android:id="@+id/tv7" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> </TableLayout> <TableLayout android:id="@+id/tableLayoutRight" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TableRow android:id="@+id/tableRow8" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <TextView android:id="@+id/tvSc1Pair" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tv_black_right_border" android:text="@string/OnePair" /> <TextView android:id="@+id/tv8" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" android:duplicateParentState="true" android:text="" /> </TableRow> <TableRow android:id="@+id/tableRow9" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <TextView android:id="@+id/tvSc2Pairs" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tv_black_right_border" android:text="@string/TwoPairs" /> <TextView android:id="@+id/tv9" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow10" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <TextView android:id="@+id/tvSc3ofaKind" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tv_black_right_border" android:text="@string/ThreeOfAKind" /> <TextView android:id="@+id/tv10" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow11" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <TextView android:id="@+id/tvSc4ofaKind" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tv_black_right_border" android:text="@string/FourOfAKind" /> <TextView android:id="@+id/tv11" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow12" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <TextView android:id="@+id/tvFullHouse" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tv_black_right_border" android:text="@string/fullHouse" /> <TextView android:id="@+id/tv12" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow13" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <TextView android:id="@+id/tvScSmallStr" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tv_black_right_border" android:text="@string/smallStr" /> <TextView android:id="@+id/tv13" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow14" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <TextView android:id="@+id/tvScLargeStr" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tv_black_right_border" android:text="@string/largeStr" /> <TextView android:id="@+id/tv14" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow15" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <TextView android:id="@+id/tvScChance" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tv_black_right_border" android:text="@string/chance" /> <TextView android:id="@+id/tv15" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow16" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <TextView android:id="@+id/tvScYatzy" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tv_black_right_border" android:text="@string/yatzy" /> <TextView android:id="@+id/tv16" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> <TableRow android:id="@+id/tableRow17" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/table_row_padding" > <TextView android:id="@+id/tvScSum" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tv_black_right_border" android:text="@string/sum" /> <TextView android:id="@+id/tv17" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" /> </TableRow> </TableLayout> </LinearLayout> A: I solved this by giving the right table layout the height "match_parent" and then adding weights on the table rows in it.
[ "tex.stackexchange", "0000101545.txt" ]
Q: Different vertical spacing (parskip) between concurrent section titles and paragraphs I'm trying to remove the spacing between section headings, but maintain the paragraph to section heading spacing. Even though I set titlespacing before and after to *0, there is still spacing - quite a bit more in the case of \section. I've tried a number of things, getting close with setting titlespacing{\<eachone>}{*0}{-5.8pt}, but it's not complete and has a number of problems. Removes vertical space to the first paragraph and section still has more space than expected. Here's what I have: And what I'm looking for: \documentclass{scrbook} \usepackage[letterpaper,asymmetric,left=108pt,right=54pt,top=41pt,bottom=41pt,headsep=13pt,headheight=14pt,footskip=23pt,marginparwidth=72pt]{geometry} \usepackage[compact,explicit,calcwidth]{titlesec} \usepackage{tikz,lipsum} \usetikzlibrary{calc} % \usepackage{setspace}\onehalfspacing % \setkomafont{sectioning}{\normalfont} % \pgfdeclarelayer{background} \pgfsetlayers{background,main} % \newlength\titlemarginwidth \setlength\titlemarginwidth{54pt} % \newcommand\boxedsection[6]{{% \usekomafont{sectioning}\usekomafont{#2}% \begin{tikzpicture}[inner sep=0, inner ysep=0.7ex, node distance=0]% \node[anchor=base west,rectangle,text width=\titlemarginwidth-\columnsep-1pt,color=#3] at (0,0) (numnode) {\vphantom{yZ}\hspace{1ex}#6};% \node[anchor=base west,rectangle,text width=\textwidth-.5pt] at ($(numnode.base east)+(\columnsep,0)$) (textnode) {\vphantom{yZ}#1};% \begin{pgfonlayer}{background}% \fill[color=#4] (0,0|-numnode.north) rectangle (numnode.south east|-textnode.south east);% \draw[#5,semithick] (0,0|-numnode.north) -- (textnode.north east);% \draw[#5,semithick] (0,0|-textnode.south west) -- (textnode.south east);% \end{pgfonlayer}% \end{tikzpicture}% }}% % \titlespacing*{\chapter}{-0.7\titlemarginwidth}{50pt}{40pt} \titleformat{\chapter}[display]% {\usekomafont{sectioning}\usekomafont{chapter}}% {\emph{\chaptertitlename\ \thechapter}}% {0em}% {\emph{#1}}% % \titlespacing*{\section}{-\titlemarginwidth}{*0}{*0} \titleformat{\section}[display] {\setstretch{1}}% {}{0pt}{\boxedsection{#1}{section}{white}{black}{black}{\thesection}}% % \titlespacing*{\subsection}{-\titlemarginwidth}{*0}{*0} \titleformat{\subsection}[display] {\setstretch{1}}% {}{0pt}{\boxedsection{#1}{subsection}{black}{gray!30}{black}{\thesubsection}}% % \titlespacing*{\subsubsection}{-\titlemarginwidth}{*0}{*0} \titleformat{\subsubsection}[display] {\setstretch{1}}% {}{0pt}{\boxedsection{#1}{subsubsection}{black}{white}{black}{\thesubsubsection}}% % \begin{document} \chapter{Test} \section{Section} \lipsum[2] \section{Section} \subsection{Subection} \subsubsection{Subsubection} \lipsum[2] \end{document} Possibly related question A: COMMENTS ON LATEST EDIT: In response to Mr. Clark's stipulation that he didn't like the \vskips, those have been successfully removed. Further, all spacings are issued through the titlesec package and are now specified in terms of \baselineskip, which should provide more flexigility for fontsize changes. Significant changes in this edit were several. First, changing the titlesec format from "display" to "hang" accomplished a great deal. However, the issue of \lineskiplimit proved to be decisive. The \boxedsection command created by Jeff was of a size not close to an even multiple of \baselineskip and so LaTeX kept adding a line to correct a perceived problem. Setting the line-skip-limit to a more negative value resolved the issue. And it allowed me to use just the titlesec parameters to achieve the result, without any vspaces. Nonetheless, there remained the issue of glue, to which I alluded in one of the comments. I was largely able to remedy it by setting \parskip to 0 and setting \textfloatsep so that it couldn't grow (I'm not wholly sure I'm using that command properly). However, a super-zoom on the flushed section headings can still occasionally perceive some glue-gap. Maybe there's another glue parameter that can help. COMMENTS ON AN EARLIER EDIT: In response to the comment that there probably needs to be no separate commands used for the flushed sub- and subsub-section headings, I have remedied that problem, with one proviso. The method works by counting how many \pars have been issued after the higher-level section invocation. It starts by assuming you have a flush-heading sub*section. Then it starts counting \pars. Once it reaches a critical number, it concludes that you have added text to the section , and changes the \sub*section heading for the next lower heading level. Therefore, the user must be consistent in how they add text to a section. Currently, the triggers are set up for the following structure \section{name} <blank line> text <blank line> \subsection{name} <blank line> text <blank line> \subsubsection{name} or for flush headings \section{name} <blank line> \subsection{name} <blank line> \subsubsection{name} Thus, there remains the requirement for the user to type his section headings consistently. And because of the feature of texexchange to squeeze blank lines out of listings, the needed blank lines in the body do not show up in the below listing. \documentclass{scrbook} \usepackage[letterpaper,asymmetric,left=108pt,right=54pt,top=41pt,bottom=41pt,headsep=13pt,headheight=14pt,footskip=23pt,marginparwidth=72pt]{geometry} \usepackage[compact,explicit,calcwidth]{titlesec} \usepackage{tikz,lipsum} \usetikzlibrary{calc} \usepackage{ifthen} % \usepackage{setspace}\onehalfspacing % \setkomafont{sectioning}{\normalfont} % \pgfdeclarelayer{background} \pgfsetlayers{background,main} % \newlength\titlemarginwidth \setlength\titlemarginwidth{54pt} % \newcommand\boxedsection[6]{{% \usekomafont{sectioning}\usekomafont{#2}% \begin{tikzpicture}[inner sep=0, inner ysep=0.7ex, node distance=0]% \node[anchor=base west,rectangle,text width=\titlemarginwidth-\columnsep-1pt,color=#3] at (0,0) (numnode) {\vphantom{yZ}\hspace{1ex}#6};% \node[anchor=base west,rectangle,text width=\textwidth-.5pt] at ($(numnode.base east)+(\columnsep,0)$) (textnode) {\vphantom{yZ}#1};% \begin{pgfonlayer}{background}% \fill[color=#4] (0,0|-numnode.north) rectangle (numnode.south east|-textnode.south east);% \draw[#5,semithick] (0,0|-numnode.north) -- (textnode.north east);% \draw[#5,semithick] (0,0|-textnode.south west) -- (textnode.south east);% \end{pgfonlayer}% \end{tikzpicture}% }}% \newcommand\flushboxedsection[6]{{% \usekomafont{sectioning}\usekomafont{#2}% \begin{tikzpicture}[inner sep=0, inner ysep=0.7ex, node distance=0]% \node[anchor=base west,rectangle,text width=\titlemarginwidth-\columnsep-1pt,color=#3] at (0,0) (numnode) {\vphantom{yZ}\hspace{1ex}#6};% \node[anchor=base west,rectangle,text width=\textwidth-.5pt] at ($(numnode.base east)+(\columnsep,0)$) (textnode) {\vphantom{yZ}#1};% \begin{pgfonlayer}{background}% \fill[color=#4] (0,0|-numnode.north) rectangle (numnode.south east|-textnode.south east);% \draw[#5,semithick] (0,0|-textnode.south west) -- (textnode.south east);% \end{pgfonlayer}% \end{tikzpicture}% }}% % \titlespacing*{\chapter}{-0.7\titlemarginwidth}{50pt}{40pt} \titleformat{\chapter}[hang]% {\usekomafont{sectioning}\usekomafont{chapter}}% {\emph{\chaptertitlename\ \thechapter}}% {0em}% {\emph{#1}}% \titlespacing*{\section}{-\titlemarginwidth}{.6\baselineskip}{*0}% \titleformat{\section}[hang]% {\setstretch{1.6}}% {}{0pt}{\boxedsection{#1}{section}{white}{black}{black}{\thesection}% } \def\tsubsectionbox{% \titlespacing*{\subsection}{-\titlemarginwidth}{.8\baselineskip}{*0}% \titleformat{\subsection}[hang]% {}% {}{0pt}{% \boxedsection{##1}{subsection}{black}{gray!30}{black}{\thesubsection}}% } % \def\fsubsectionbox{% \titlespacing*{\subsection}{-\titlemarginwidth}{*0}{.2\baselineskip}% \titleformat{\subsection}[hang]% {\setstretch{1.38}}% {}{0pt}{% \flushboxedsection{##1}{subsection}{black}{gray!30}{black}{\thesubsection}}% } % \newcounter{subparcounter} \let\savesection\section \def\section{\fsubsectionbox\setcounter{subparcounter}{0}\savesection} % \def\tsubsubsectionbox{% \titlespacing*{\subsubsection}{-\titlemarginwidth}{.8\baselineskip}{*0}% \titleformat{\subsubsection}[hang]% {}% {}{0pt}{% \boxedsection{##1}{subsubsection}{black}{white}{black}{\thesubsubsection}}% } % \def\fsubsubsectionbox{% \titlespacing*{\subsubsection}{-\titlemarginwidth}{*0}{0\baselineskip}% \titleformat{\subsubsection}[hang]% {\setstretch{1.1}}% {}{0pt}{% \flushboxedsection{##1}{subsubsection}{black}{white}{black}{\thesubsubsection}}% } % \newcounter{subsubparcounter} \let\savesubsection\subsection \def\subsection{\fsubsubsectionbox\setcounter{subsubparcounter}{0}% \savesubsection} % \let\savepar\par \def\par{% \savepar% \addtocounter{subsubparcounter}{1}% \addtocounter{subparcounter}{1}% \ifthenelse{5 = \value{subsubparcounter}}% {\tsubsubsectionbox}% {}% \ifthenelse{5 = \value{subparcounter}}% {\tsubsectionbox}% {}% }% % % SEE: http://www.tug.org/TUGboat/tb28-1/tb88bazargan.pdf \lineskiplimit = -12pt % <--MAY NEED TO BE MADE MORE NEGATIVE! \parskip 0ex \setlength{\textfloatsep}{20pt plus 0pt minus 4pt} % \begin{document} \chapter{Test} \section{Section} \lipsum[2] text \subsection{Subsection} Text \subsubsection{Subsubsection} Text \section{Section} \subsection{Subsection} \subsubsection{Subsubsection} Text \section{Section} Text \subsection{Subsection} Text \subsubsection{Subsubsection} Text \lipsum[2] \section{Section} \lipsum[2] text \subsection{Subsection} Text \subsubsection{Subsubsection} Text \section{Section} \subsection{Subsection} \subsubsection{Subsubsection} Text \section{Section} Text \subsection{Subsection} Text \subsubsection{Subsubsection} Text \lipsum[2] \section{Section} \lipsum[2] text \subsection{Subsection} Text \subsubsection{Subsubsection} Text \section{Section} \subsection{Subsection} \subsubsection{Subsubsection} Text \section{Section} \subsection{Subsection} Text \subsubsection{Subsubsection} Text \lipsum[2] \end{document}
[ "stackoverflow", "0032907692.txt" ]
Q: pg_search: ordering of "multisearchable" results I'm using Rails 4.2.4 with pg_search 1.0.5. class Advert < ActiveRecord::Base include PgSearch multisearchable :against => [:title, :body] end I would like to order the pg_search results by the :created_at date of my Advert records. Logically, it seems to me like the following could work (:asc): > @pgs = PgSearch.multisearch('55948189').order(created_at: :asc) PgSearch::Document Load (136.1ms) SELECT "pg_search_documents".* FROM "pg_search_documents" INNER JOIN (SELECT "pg_search_documents"."id" AS pg_search_id, (ts_rank((to_tsvector('simple', coalesce("pg_search_documents"."content"::text, ''))), (to_tsquery('simple', ''' ' || '55948189' || ' ''')), 0)) AS rank FROM "pg_search_documents" WHERE (((to_tsvector('simple', coalesce("pg_search_documents"."content"::text, ''))) @@ (to_tsquery('simple', ''' ' || '55948189' || ' '''))))) AS pg_search_ce9b9dd18c5c0023f2116f ON "pg_search_documents"."id" = pg_search_ce9b9dd18c5c0023f2116f.pg_search_id ORDER BY pg_search_ce9b9dd18c5c0023f2116f.rank DESC, "pg_search_documents"."id" ASC, "pg_search_documents"."created_at" ASC => #<ActiveRecord::Relation [ #<PgSearch::Document id: 3148, content: "Aleksandra | Tallinn | 55948189 Simpatichnaja i se...", searchable_id: 3148, searchable_type: "Advert", created_at: "2015-10-01 11:44:06", updated_at: "2015-10-01 11:44:30">, #<PgSearch::Document id: 3275, content: "Aleksandra | Tallinn | 55948189 Simpatichnaja i se...", searchable_id: 3275, searchable_type: "Advert", created_at: "2015-10-02 11:05:49", updated_at: "2015-10-02 11:28:48">]> But then the opposite order (:desc) produces the same results: > @pgs = PgSearch.multisearch('55948189').order(created_at: :desc) PgSearch::Document Load (108.4ms) SELECT "pg_search_documents".* FROM "pg_search_documents" INNER JOIN (SELECT "pg_search_documents"."id" AS pg_search_id, (ts_rank((to_tsvector('simple', coalesce("pg_search_documents"."content"::text, ''))), (to_tsquery('simple', ''' ' || '55948189' || ' ''')), 0)) AS rank FROM "pg_search_documents" WHERE (((to_tsvector('simple', coalesce("pg_search_documents"."content"::text, ''))) @@ (to_tsquery('simple', ''' ' || '55948189' || ' '''))))) AS pg_search_ce9b9dd18c5c0023f2116f ON "pg_search_documents"."id" = pg_search_ce9b9dd18c5c0023f2116f.pg_search_id ORDER BY pg_search_ce9b9dd18c5c0023f2116f.rank DESC, "pg_search_documents"."id" ASC, "pg_search_documents"."created_at" DESC => #<ActiveRecord::Relation [ #<PgSearch::Document id: 3148, content: "Aleksandra | Tallinn | 55948189 Simpatichnaja i se...", searchable_id: 3148, searchable_type: "Advert", created_at: "2015-10-01 11:44:06", updated_at: "2015-10-01 11:44:30">, #<PgSearch::Document id: 3275, content: "Aleksandra | Tallinn | 55948189 Simpatichnaja i se...", searchable_id: 3275, searchable_type: "Advert", created_at: "2015-10-02 11:05:49", updated_at: "2015-10-02 11:28:48">]> Could anybody explain how I can order my search results by the :created_at date? UPDATE 1: Is it possible that the order of the results is fixed by pg_search and there isn't any way to order by 'created_at`? I am reading the documentation more carefully now and found this statement: "By default, pg_search ranks results based on the :tsearch similarity between the searchable text and the query. To use a different ranking algorithm, you can pass a :ranked_by option to pg_search_scope." (see https://github.com/Casecommons/pg_search) A: There is a simple answer but it does not work with "multisearchable". First, I needed to change from "multisearchable" (which works with multiple models) to "pg_search_scope" (searches in a single model only). Second, I needed to use :order_within_rank. Since the results are all 100% matches of the search term, they have the same ranking according to pg_search. :order_within_rank gives a secondary rank as a tiebreaker. class Advert < ActiveRecord::Base include PgSearch pg_search_scope :search_by_full_advert, :against => [:title, :body], :order_within_rank => "adverts.created_at DESC" end
[ "stackoverflow", "0058750824.txt" ]
Q: Preferred File Location for Static Files in Maven WAR Project I am trying to access some WSDLs and XMLs files from WebApp which i built in Maven as a WAR. Now I knew that the resources folder was the default location for these types of files, but when I checked the war package, I found that the files ended up inside the /WEB-INF folder, which is of not much use. Just wanted to know where do I put these files so that I can access them via URL: https://server:port/Context/File_Path I tried to make a folder inside webapp but outside WEB-INF, it did seem to do the trick. But just wanted to know if that the right approach. A: Maven has a concept of standard directory layout So, yes, in order to work with something that can be packaged into WAR with maven-war-plugin you should follow the convention and place the files into the relevant folders (of course you can change these defaults if you wish). When it comes to the static resources, indeed there is a special src/main/webapp folder. So you're right
[ "stackoverflow", "0022578985.txt" ]
Q: JPA, GeneratedValue autoincrement with 50 I'm using JPA and when I insert data into the database my ID is autoincremented with 50. I'm using persistence.GeneratedValue to autoincrement it: This is how my model/entity class looks like (Entity to be inserted): ..imports @Entity public class Example extends Identifiable { .. } Identifiable : ..imports @MappedSuperclass public abstract class Identifiable { @Id @GeneratedValue protected long id; .. } Database: # ID NAME ... 1 701 a 2 751 b 3 801 c Anyone have an Idea what the problem is? A: Default value for GeneratedValue.strategy is GenerationType.AUTO. What this means is spelled out nicely in JPA 2 specification: The AUTO value indicates that the persistence provider should pick an appropriate strategy for the particular database. The AUTO generation strategy may expect a database resource to exist, or it may attempt to create one. A vendor may provide documentation on how to create such resources in the event that it does not support schema generation or cannot create the schema resource at runtime. For both TableGenerator and SequenceGenerator default value of allocationSize is 50. This means that chunk of 50 values is reserved. In shutdown there reserved values will be gone. If application is shutdown after only one is used, values from 2 to 50 are gone and next time 51 to 100 will be reserved. Strategy other than auto should be used if more control over identifier generation is needed. That can be done for example as follows: @TableGenerator( name = "yourTableGenerator" allocationSize = 1, initialValue = 1) @Id @GeneratedValue( strategy=GenerationType.TABLE, generator="yourTableGenerator") or: @SequenceGenerator(name="yourSequenceGenerator", allocationSize=1) @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="yourSequenceGenerator")
[ "stackoverflow", "0036503593.txt" ]
Q: Custom Action in Wix to manipulate string and set property Hi I am using Wix to create an Installer that has to write a registry value with the path of the file that the installer copies on the user's system. The problem is that the registry entry should be written in this format file:///C:/Program Files/.... In the Wix code project I have the INSTALLFOLDER Directory Id which points to C:\Program Files\.... I am really struggling to convert the latter notation into former. I created a Custom Action hoping to set a property so that I can use that. Following is the code Custom Action (separate DLL for now, can it be inlined?) public class CustomActions { [CustomAction] public static ActionResult CustomAction1(Session session) { session.Log("Begin CustomAction1"); string origValue = session["INSTALLFOLDER"]; MessageBox.Show(origValue); string retVal = origValue.Replace("\\", "//"); MessageBox.Show(retVal); session["Custom_Prop"] = retVal; return ActionResult.Success; } } And the Product.wxs <?xml version="1.0" encoding="UTF-8"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Product Id="*" Name="SetupProject1" Language="1033" Version="1.2.0.0" Manufacturer="nik" UpgradeCode="4a74ff86-49a9-4011-9794-e1c18077172f"> <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" /> <MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." /> <MediaTemplate /> <Feature Id="ProductFeature" Title="SetupProject1" Level="1"> <ComponentGroupRef Id="ProductComponents" /> </Feature> <InstallExecuteSequence> <Custom Action='FooAction' Before='InstallFinalize'>NOT Installed</Custom> </InstallExecuteSequence> </Product> <Fragment> <CustomAction Id='FooAction' BinaryKey='FooBinary' DllEntry='CustomAction1' Execute='immediate' Return='check'/> <Binary Id='FooBinary' SourceFile='MyCustomAction.CA.dll'/> </Fragment> <Fragment> <Directory Id="TARGETDIR" Name="SourceDir"> <Directory Id="ProgramFilesFolder"> <Directory Id="INSTALLFOLDER" Name="SetupProject1" /> </Directory> </Directory> </Fragment> <Fragment> <Property Id="Custom_Prop" Value="[ProgramFilesFolder]"></Property> <ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER"> <!-- TODO: Remove the comments around this Component element and the ComponentRef below in order to add resources to this installer. --> <!-- <Component Id="ProductComponent"> --> <!-- TODO: Insert files, registry keys, and other resources here. --> <!-- </Component> --> <Component Id="cmp_Add_Mainfest_To_Registry" Guid="955A3A76-F010-4FCB-BCAF-B297AFD1C05B"> <RegistryKey Root="HKCU" Key="SOFTWARE\company"> <RegistryValue Name="LoadBehavior" Value="3" Type="integer" Action="write" /> <RegistryValue Name="Manifest" Value="[Custom_Prop]" Type="string" Action="write" KeyPath="yes"/> </RegistryKey> </Component> </ComponentGroup> </Fragment> </Wix> However when I run this setup the value written in the registry is the literal string [ProgramFolder] and not its evaluation into either C:\ or C:/ Can someone help? A: The reason why my code wasn't working was this line <InstallExecuteSequence> <Custom Action='FooAction' Before='InstallFinalize'>NOT Installed</Custom> </InstallExecuteSequence> On changing the value of Before attribute as below made this work <InstallExecuteSequence> <Custom Action='FooAction' Before='CostFinalize'>NOT Installed</Custom> </InstallExecuteSequence> However given my needs were very simple I decided to not have a separate DLL for CustomAction and instead went ahead with a Custom Action in vbscript within the Wix Project. So now the code looks like <?xml version="1.0" encoding="UTF-8"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Product Id="*" Name="SetupProject1" Language="1033" Version="1.3.1.0" Manufacturer="nik" UpgradeCode="4a74ff86-49a9-4011-9794-e1c18077172f"> <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" /> <MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." /> <MediaTemplate /> <Feature Id="ProductFeature" Title="SetupProject1" Level="1"> <ComponentGroupRef Id="ProductComponents" /> </Feature> <InstallExecuteSequence> <Custom Action="VBScriptCommand" After="CostFinalize">NOT REMOVE</Custom> </InstallExecuteSequence> </Product> <Fragment> <CustomAction Id="VBScriptCommand" Script="vbscript"> <![CDATA[ value = Session.Property("INSTALLFOLDER") origPath=Session.Property("INSTALLFOLDER") If Right(webdir, 1) = "\" Then value = Left(value, Len(value) - 1) End If Session.Property("SOME_PROPERTY") = Replace(origPath,"\","//") ]]> </CustomAction> </Fragment> <Fragment> <Directory Id="TARGETDIR" Name="SourceDir"> <Directory Id="ProgramFilesFolder"> <Directory Id="INSTALLFOLDER" Name="SetupProject1" /> </Directory> </Directory> </Fragment> <Fragment> <Property Id="Custom_Prop" Value="[ProgramFilesFolder]"></Property> <ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER"> <Component Id="cmp_Add_Mainfest_To_Registry" Guid="955A3A76-F010-4FCB-BCAF-B297AFD1C05B"> <RegistryKey Root="HKCU" Key="SOFTWARE\something"> <RegistryValue Name="LoadBehavior" Value="3" Type="integer" Action="write" /> <!--<RegistryValue Name="Manifest" Value="[#FILE_VstoManifest]|vstolocal" Type="string" Action="write" />--> <RegistryValue Name="Manifest" Value="file:///[SOME_PROPERTY]" Type="string" Action="write" KeyPath="yes"/> </RegistryKey> </Component> </ComponentGroup> </Fragment> </Wix> Perhaps the purists won't like this but why use a Shot gun to kill a fly?
[ "stackoverflow", "0043292494.txt" ]
Q: Android: Is there anything good about giving id to all the views? I'm studying Android by looking at open source projects code, and what I noticed was that, in many cases, they give ids to almost all the views, even if they don't actually use those ids in code. For example, they give ids to LinearLayout, RelativeLayout and so on, but they don't really use those ids in code. Is there any reason why they do that? Because I think giving ids to all the views only makes me confused about what id was what view. Is it just a bad practice? Thank you in advance! A: Is there any reason why they do that? No. Technically there is no reason to do that if you are not going to use the id anywhere (either in Java or in the XML file). For eg it could be a personal choice, just like naming variables or naming class depending on its purpose (here note that this could be a personal choice). From the developer API guides: Defining IDs for view objects is important when creating a RelativeLayout. In a relative layout, sibling views can define their layout relative to another sibling view, which is referenced by the unique ID. Again, Because I think giving ids to all the views only makes me confused about what id was what view. You can easily sort out the confusion thing if you give proper name to the id's. Like: btn_create for Buttons tv_mobile_number for TextViews ll_main_activity for LinearLayouts rl_details_fragment for RelativeLayouts and so on. Is it just a bad practice? Technically not. But it may save you from the pain of typing id's for each and every view and may even save some time for you as well. As a side note, I usually prefer giving id's only when needed. Hope this will help you. Cheers!
[ "stackoverflow", "0047622433.txt" ]
Q: How can i multiply 2 curl outputs together I have the outputs of 2 APIs with this Bash Json Parser curl 'APIxyz' | sed -e 's/[{}]/''/g' |\ awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' |\ grep -w "total_hash" | cut -c14-100 After using cut I have the correct numbers (like 15.25), but how can I use 2 times curl and multiply it together, would prefer using not an extra SH script, is this even possible in bash? And if how? A: You can store the results of the two curl commands in variables, and then multiply them: v1=$(curl ...) v2=$(curl ...) bc <<< "$v1 * $v2" You could write in one line if you really really really need: bc <<< "$(curl ...) * $(curl ...)"
[ "stackoverflow", "0055791645.txt" ]
Q: Is there any code for get original Distance travelled in my car via OBDII in case of DTC Code clean-up now at i use o1 31 PID to get Distance travelled but this give only Distance traveled since codes cleared-up not total travelled KM A: Unfortunately OBD2 does not specify any standard PIDs to get this information. That said, you might be able to gather this via vendor-specific extensions or by dropping down to a lower level (using direct CAN commands), but this is not portable between vehicles and thus discouraged.
[ "stackoverflow", "0034201244.txt" ]
Q: Integrating a Maven project into Laravel application I have a form in Laravel 5.1, I want to send my query to a maven based project and return the results back to my L5 app. The maven project is written in Scala. So, how can I integrate maven project into my Laravel app? Any idea is welcomed, Thanks, A: I used curl to send my query to Scala API and sent the retrieved data to my View. There are couple of custom libraries to do this in Laravel in my case I used ixudra/curl.
[ "stackoverflow", "0016896541.txt" ]
Q: Neo4J - Cypher example I got a bit of interest in graph databases, but I have some doubts. I did some superficial research (reading) which did not cleared things (I am familiar with graphs and graphs algorithms). Please excuse my laziness...but if you have time please give a shot to this question. How can the following SQL query be translated to Neo4J Cypher: Give all customers which have orders where each order amount exceeds $100 and the number of products per order is grater than 3. Can such scenario be modeled in Neo4J? A: Some 2.0 Cypher for a hypothetical model: match c:Customer-[:ordered]->o:Order-[:contains]->p:Product where o.total > 100.00 with c, o, count(p) as pcount where pcount > 3 return distinct c;
[ "stackoverflow", "0054173860.txt" ]
Q: Passing parameters with react router v4 and using them in url's I'm having problems with passing my parameters, but my way of thinking is probably wrong so: My App.js with routes class App extends Component { render() { return ( <Router> <div className="container"> (...) <Route path="/product/:id" component={ProductPage} ></Route> (...) </div> </Router> ); } } and my review section with array of comments class ReviewSection extends Component { constructor(props) { super(props); this.state = {rates:[]}; } componentDidMount() { axios.get('http://oceneo-api.herokuapp.com/api/products/1/rates') .then(res => { console.log(res) const rates = res.data; this.setState({rates}) }) .catch(error => console.log(error)) } render(){ return( <div className="container products"> {this.state.rates.map(rate => <div className="row" key={rate.id}> (...) The main problem for me is to change the api link with something like localhost:3001/product/2 which would give desired /api/products/2/rates instead of /api/products/1/rates. A: Route component is passing parameters to the rendered component so when you check props of ProductPage component you will see match prop and it contains key named params. Here is an example https://codesandbox.io/s/1y773j6kk4
[ "math.stackexchange", "0002015604.txt" ]
Q: Order the following propositions from the strongest to the weakest: A, B, A β†’ B? So I was recently given a number of questions in class but this one in particular, despite scouring my notes and the internet, has escaped me. "Given formal statements P and Q, P is said to be stronger than Q if P =β‡’ Q (In other words, P =β‡’ Q is a tautology). Answer the following: a) Order the following propositions from the strongest to the weakest: (i) A (ii) B (iii) A β†’ B (Hint: It is possible that a proposition may not be stronger or weaker than another proposition. In that case, they are at the same level. Truth tables can be used to derive the relationships between any two of the above statements individually.) b) Prove that A ∧ B is stronger than A. c) Is A ∧ B stronger or weaker than A β‡’ B? Justify your answer." I just cannot wrap my head around this. I've done out truth tables which I can show you if it helps explain it to me; but overall I can't understand how to fully explain why one of these is stronger than the other except to say one has more Truths than another. As a whole I'm not sure how to correctly evaluate the strengths. I was directed here via StackOverflow as they believed it was more relevant. A: $A\to B$ is not a tautology, and neither is $B\to A$, so $A$ and $B$ are at the same level: neither is stronger than the other. On the other hand, $B\to(A\to B)$ is a tautology, as we can see from the following truth table: $$\begin{array}{c|c|c} A&B&A\to B&B\to(A\to B)\\ \hline T&T&T&T\\ T&F&F&T\\ F&T&T&T\\ F&F&T&T \end{array}$$ Thus, $B$ is stronger than $A\to B$. That leaves only $A$ and $A\to B$ to compare. Neither $A\to(A\to B)$ nor $(A\to B)\to A$ is a tautology, so these two propositions are at the same level. To summarize, $B$ is stronger than $A\to B$, and this is the only such relationship amongst the three propositions $A,B$, and $A\to B$.
[ "stackoverflow", "0006774632.txt" ]
Q: Is the Azure role host actually restarted when a role crashes or is restarted via management API? Suppose my Azure role somehow exhausts system-wide resources. For example it spawns many processes and all those processes hang and consume all virtual memory in the system. Or it creates a gazillion of Windows API event objects and fails to release them and no more such object can be created. I mean anything except trashing the filesystem. Now the changes I describe are cancelled out once normal Windows machine restarts - processes are terminated, virtual memory is "recycled", events and other similar objects are "recycled" and so on. Yet there's a concern. What if the host is not actually restarted, but goes through some other process when I hit "reboot" or "stop", then "start"? Is the host actually rebooted when I restart a role or reboot an instance? A: When you reboot the instance, the VM is actually rebooted. When you stop and start, the VM is not rebooted, but the process is restarted.
[ "stackoverflow", "0046968874.txt" ]
Q: How to insert JSON strings without ID property? I have a class. I will insert converted JSON classes without the ID property. While I insert that JSON string, an error occured because the ID was not inserted. public class myClass { public int ID{ get; set; } public string name{ get; set; } public string surname{ get; set; } public myClass(int Id, string Name, string Surname) { this.ID= Id; this.name= Name; this.surname=Surname; } } What I get now: { "ID": "1", "name": "serial", "surname": "Fast" } What I want it to look like: { "name": "Serial", "surname": "Fast" } A: Try to ignore that class using ScriptIgnore. using System; using System.Web.Script.Serialization; public class myClass { // The JavaScriptSerializer ignores this field. [ScriptIgnore] public int ID{ get; set; } // The JavaScriptSerializer serializes this field. public string name{ get; set; } public string surname{ get; set; } } link here
[ "stackoverflow", "0043305081.txt" ]
Q: angular js: reload a page after and ng-click I'm using spring boot for my backend and angular for front. In my back, I have a restful service which fetching an sorting data when the user call a defined route, then send the result to the front. In angular, I made a service on this defined route and i'm parsing result to render them to the view. Everything works fine, except I want to reload the page after the user click on the button wich start my batch. On this button I already have an ng-click which works and start my batch. But I don't know how to reload the page after clicking this button. Maybe I shouldn't use another function in ng-click ? my service : (function() { 'use strict'; angular .module('pfja') .factory('Publication', Publication); Publication.$inject = ['$http']; function Publication ($http) { var urlOpeFlexFactureValide = 'api/invoice/valid-invoice'; var getAllValidInvoice= function(){ return $http.get(urlValidInvoice).then( function(result){ return result.data; } ); }; return { getAllValidInvoice: getAllValidInvoice }; } })(); my state.js : parent: 'app', url: '/publication?page&sort&search', data: { authorities: ['ROLE_USER'], pageTitle: 'home' }, views: { 'content@': { templateUrl: 'app/batch/publication/publication.html', controller: 'PublicationController', controllerAs: 'vm' } }, params: { page: { value: '1', squash: true }, sort: { value: 'id,asc', squash: true }, search: null }, resolve: { .... validInvoiceList: ['Publication', '$q', function(Publication, $q){ return Publication.getAllValidinvoice(); }] my controller : (function() { 'use strict'; angular .module('pfja') .controller('PublicationController', PublicationController); PublicationController.$inject = ['$scope',... 'Publication', 'validInvoiceList']; function PublicationController ($scope, ..., Publication, validInvoiceList) { var vm = this; ... vm.validInvoiceList = validInvoiceList; function runPublicationBatch(){ var invoice = new Array(); if (vm.validInvoiceList) { vm.validInvoiceList.forEach(function(inv) { if (inv.selected) { invoice.push(inv); } }); } ManualBatch.runPublicationBatch(invoice); }; my html : <button ng-click="vm.runPublicationBatch()" class="btn btn-primary btn-md"> <span class="glyphicon glyphicon-play-circle"></span> Start </span> </button> //my ng-repeat with vm.validInvoice... A: You first need to inject service $window than you can use $window.location.reload(); function runPublicationBatch(){ $window.location.reload(); var invoice = new Array(); if (vm.validInvoiceList) { vm.validInvoiceList.forEach(function(inv) { if (inv.selected) { invoice.push(inv); } }); } ManualBatch.runPublicationBatch(invoice); }; Or when you want to reload the page. you can reload with $route , $state service here
[ "gardening.meta.stackexchange", "0000000114.txt" ]
Q: Should good answers contain references? One of my advice questions was answered without references given, and I can only assume it's anecdotal. Is it expecting too much on this site to ask/expect people to provide references to back up their answers? To answer my own question to some extent, I think that the answers containing reliable references (articles at university horticultural extensions/research studies, etc.) will indicate higher answer quality and will help improve the quality of the site. That's not to say that people should be discouraged from answering from anecdotal experience, because sometimes it may be the only information available. A: To begin, a related question exists to evaluate claims' authority, any input here would very likely inform any decisions over there. As to 'should answers need sources?', the answer is a mixed one. Gardening is a blend of prior knowledge mixed with the experience gained through improvising. In some cases, the personal experimentation is what will give the edge to a great answer. In other cases, it can result in unfortunate consequences. Here I would draw an analogy with cooking a fantastic tasting meal, but inadvertantly downing everyone at the table with food poisoning. There are three ways to break this up: Questions requiring expertise and experience, but that are unlikely to carry unintended consequences Questions requiring expertise and experience, but whose unforeseen/unlikely unintended consequences are not incredibly substantial Questions requiring expertise and experience, and are likely to carry unintended, serious consequences In the first case, I would cite my response to how to keep critters away; put up a statue of an owl. This has worked for me, maybe it won't for you or the pests you're dealing with, but at the end of the day no plants or persons will be any more or less harmed as a result of following the advice. Anecdotal answers are fine, backing them up is a plus. In the second case, I would cite my response to how to keep critters off your irrigation; spray hot pepper oil on the equipment. In most cases I cannot see how this would carry consequences, but perhaps the oil eats through some cheap plastic tubing. No plants or people are really that harmed, no expensive equipment was really damaged. Anecdotal answers work, but some fact-checking and thinking about the possible unintended consequences (and probably voicing them in the answer) is a bit requisite for a thorough answer. In the last case where the consequences might be severe, I would cite the question about making compost tea while avoiding e. coli. While I am glad it has one source. As a question-asker, I personally would not trust that source or consider the answer to be authoritative (particularly, because it cites only one source to assuage the concerns of someone worried about food poisoning). It has nothing to do with their credentials, it is because these questions voice a concern about bacteria and other pathogens. Similarly, while losing a random basil sprout isn't a big deal, losing an incredibly rare flower or heirloom variety of tomato (perhaps imported by your great grandfather from Italy) would certainly change the weight of any given answer. [Here I would refer to the list offered through Aaronut] on Cooking.se3. While I don't believe it is necessary to make every answer conform to the authority criteria, I think it is typically in everyone's best interest to first evaluate the type of question (and the possible consequences of implementing a given answer). If the question falls into that third category, and I asked it, I am unlikely to accept any answer that doesn't at least try to show it's work. If you have been making compost tea the same way for 30 years and have never contracted a food-bourne illness, that's fantastic; but please be very thorough in explaining what you do, and reference other guides to really explain it so that I don't try to follow your method and screw up. The only problem is trying to diagnose where exactly the question falls. I think another question should be asked to address the scope of the site in this regard. For instance, although food safety guidelines are an important aspect of Cooking.se, asking about nutrition is considered out of scope. I am not sure this exact concept comports, but a similar consideration might be fruitful. A: Well, while there might be references online, most people who are knowledgable in this area might not even be aware of them. For them, their knowledge mostly comes from experience and hanging around folks who are more experienced. In my opinion, expecting/forcing them to provide a reference for every single claim will only turn this into skeptics.SE and make people disinterested in participating. At some level, you rely on trust. How do you know if the random article that was linked to is actually scientific or some dude jotting down his anecdotal advice? You don't go to Shirlock Homes on DIY.SE and say "umm dude, you got a reference for using screws instead of nails?" No. You trust that people are here to give their honest advice. Sometimes that advice might be wrong, but there will always be someone who comes by and says that it is wrong and corrects them, or fills in missing info. This would not happen if there were no experts. Moreover, you should only take the answers here as a guidance. If you want solid references, you ought to try to find them yourself based on the pointers given in the answers. A: +1 to what mfg said. I would also add, if you're trying to get answers with authoritative references: The more specific the question, the more likely you are to get references. Your question "Is it possible to indefinitely limit growth of trees, hedges, and shrubs?" could be improved to provide us with information on the species you're trying to limit. You've asked a general question and gotten some general advice. The truly authoritative answer to your question is, "it depends". Some species tolerate pruning better than others. If you had asked "Is it possible to indefinitely limit the height and width of my arborvitae hedge?" it would be easier to quote chapter and verse from a book that one of us has on doing exactly what you want. If you substitute a different species, the answer might simply be "No, that tree will not tolerate pruning". Unsure of the species? Post a question with pictures, your location, and some description and someone here will probably know exactly what you've got.
[ "stackoverflow", "0062033512.txt" ]
Q: Why is it not undefined behavior that `std::uninitialized_copy` typically dereferences an iterator to uninitialized memory? I'm aware that dereferencing a pointer or iterator that points to uninitialized memory is illegal, unless it's a special iterator such as std::raw_storage_iterator. It then seems strange to me that the std::uninitialized_ family of algorithms seem to do this? E.g. The Equivalent behaviour for std::uninitialized_copy under Β§ 23.10.10.4 of the C++17 standard is stated as this: template <class InputIterator, class ForwardIterator> ForwardIterator uninitialized_copy(InputIterator first, InputIterator last, ForwardIterator result); Effects: As if by: for (; first != last; ++d_first, (void) ++first) ::new (static_cast<void*>(addressof(*result))) typename iterator_traits<ForwardIt>::value_type(*first); Where result is a ForwardIterator to a range of uninitialized memory. Similarly, en.cppreference's example and GCC 7.5 (line 83) do this. I must be missing something; why is this legal? I'm specifically referring to: static_cast<void*>(addressof(*result)) A: I'm aware that dereferencing a pointer or iterator that points to uninitialized memory is illegal Not quite. The indirection alone is not illegal. Behaviour is only undefined in case of performing operations such as those that depend on the value. std::addressof does not access the value of referred object. It only takes its address. This is something that is allowed on objects before and after their lifetime while their storage has been allocated. Even if this wasn't true due to some technicality in the rules, standard library implementation is not necessarily limited by the rules of the language. Standard quotes (latest draft): [basic.life] Before the lifetime of an object has started but after the storage which the object will occupy has been allocated ... any pointer that represents the address of the storage location where the object will be ... located may be used but only in limited ways. For an object under construction or destruction, see [class.cdtor]. Otherwise, such a pointer refers to allocated storage ([basic.stc.dynamic.allocation]), and using the pointer as if the pointer were of type void* is well-defined. Indirection through such a pointer is permitted but the resulting lvalue may only be used in limited ways, as described below. The program has undefined behavior if: (no cases that apply here) Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated ... any glvalue that refers to the original object may be used but only in limited ways. For an object under construction or destruction, see [class.cdtor]. Otherwise, such a glvalue refers to allocated storage ([basic.stc.dynamic.allocation]), and using the properties of the glvalue that do not depend on its value is well-defined. The program has undefined behavior if: (no cases that apply here)
[ "stackoverflow", "0021713054.txt" ]
Q: What adapter use for listview and database? I'm new in Android(Java) programming. I have a database activity: public class DataBase { public static final String DB_NAME = "appdb"; public static final int DB_VERSION = 1; static final String TABLE_NAME = "passtab"; final String LOG_TAG = "myLogs"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_TITLE = "title_enter"; public static final String COLUMN_LOGIN = "login_enter"; public static final String COLUMN_PASSWORD = "password_enter"; public static final String COLUMN_URL = "link_enter"; public static final String COLUMN_COMMENT = "comment_enter"; public static final String COLUMN_DATE = "date_enter"; public String results; private DBHelper phdb; private static Context pcontext; private SQLiteDatabase pdb; private static final String DB_CREATE = "create table " + TABLE_NAME + "(" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_TITLE + " VARCHAR(255), " + COLUMN_LOGIN + " VARCHAR(255), " + COLUMN_PASSWORD + " VARCHAR(255), " + COLUMN_URL + " VARCHAR(255), " + COLUMN_COMMENT + " text, " + COLUMN_DATE + " VARCHAR(255)" + ");"; public class DBHelper extends SQLiteOpenHelper{ public DBHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(DB_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } public DataBase(Context c) { pcontext = c; } public DataBase open() throws SQLiteException { phdb = new DBHelper(pcontext); pdb = phdb.getWritableDatabase(); return this; } public SQLiteDatabase getDatabase() { return pdb; } public void close() { pdb.close(); } public long createEntry(String tt, String lg, String ps, String ul, String cm, String dt) { ContentValues cv = new ContentValues(); cv.put(COLUMN_TITLE, tt); cv.put(COLUMN_LOGIN, lg); cv.put(COLUMN_PASSWORD, ps); cv.put(COLUMN_URL, ul); cv.put(COLUMN_COMMENT, cm); cv.put(COLUMN_DATE, dt); return pdb.insert(TABLE_NAME, null, cv); } } And MainScreen activity where will be showed listview (which contains custom list row xml). MainScreen Activity: public class MainScreen extends FragmentActivity implements OnClickListener { ListView listViewMain; SQLiteDatabase db; DataBase DB; DBHelper dbH; Cursor cursor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_screen); listViewMain = (ListView) findViewById(R.id.listViewMain); ???? } And list row custom xml: <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/titleView" android:text="" /> <TextView android:id="@+id/dateView" android:text="" /> </RelativeLayout> What adapter I should use to receive data (COLUMN_TITLE and COLUMN_DATE) from database and fill with them listview row item (textview = titleView, textview = dateView)? If can please write a sample of code. P.S. Thank you! A: SimpleCursorAdapter would suit your needs, since you're only using textviews in your view. This post gives a decent explanation on how to use it.
[ "stackoverflow", "0058117323.txt" ]
Q: How to use "||" on select query laravel I need help about my code. I tried to make a code like that $selectint = \DB::table('forums')->where([['category', '=', $f]])->orderByRaw('id ASC')->get(); but i'm need to make || function example in mysqli: SELECT * FROM forums WHERE category = ? && (community = ? || community = ?) ORDER BY forum_id ASC Please.Help A: || is an OR, so you could formulate it like SELECT * FROM forums WHERE category = ? AND community IN (?, ?) ORDER BY forum_id ASC In Eloquent (Laravel's ORM) it would be something like: $selectInt = \DB::table('forums') ->where('category', '=', $whatever) ->andWhereIn('community', [...]) ->orderByRaw('id ASC') ->get(); Check out the official Laravel documentation about QueryBuilders: https://laravel.com/docs/5.8/queries
[ "salesforce.stackexchange", "0000012585.txt" ]
Q: display page in Tab, but avoid hard coded link Is it possible to get the Id(tabName) of a tab by its Name e.g. to avoid hard coded links like this: <apex:outputLink value="/apex/testPage?sfdc.tabName=01ri0000000QgAK">Test Page</apex:outputLink> A: If I'm correct in assuming you're passing in the tab name to your visualforce page to determine which tab is displayed in you actually don't need to do this. Instead use the apex:page tabstyle attribute to set your tab. For example <apex:page tabStyle="Account"> <!-- For Standard Object Tab --> <apex:page tabStyle="MyObj__c"> <!-- For Custom Object Tab --> <apex:page tabStyle="Custom__Tab"> <!-- For Custom Web/VF Tabs --> An important caveat is you have to use a literal value for tabStyle. So If you want different tab styles in some cases in others you'll need to create a visualforce page for both. To stay DRY you'll want to use apex:include or a component to encapsulate the core of the page and reference that in the pages for the different tab styles. Alternatively if you were trying to link to an object based tab you can use the $Action for it. I'm not aware of a simliar approach for custom web or visualforce tabs (although it's really not needed for visualforce since you can set the tab on the page. <a href="{!URLFOR($Action.Account.Tab)}"/> <!-- Standard Object Tab --> <a href="{!URLFOR($Action.MyObj__c.Tab)}"/> <!-- Custom Object Tab --> Unfortunately the ID for the tab is not available to APEX. It available with the Metadata API and ANT. See this answer for a discussion on getting the ids for custom fields for more details. Bear in mind that the ID will be different for tabs created in sandbox and later migrated to production. However, ids for tabs present in production prior to a sandbox refresh will be the same. Finally, if they ever migrate your org to a different instance all the IDs will change.
[ "stackoverflow", "0013912449.txt" ]
Q: getting file absolute path from BufferedWriter instance Is there any way to get the absolute path from BufferedWriter ? From the spec it seems that it is not possible but I am asking just in case anybody aware of some kind of trick... A: AFAIK, the closest you can get in Unix is to, use reflection to find file descriptor. examine the /proc/self/fd/{fid} to get the inode of the file and possibly the device to determine which file you are accessing. do a search of the device to find which filename(s) which are linked to that file.
[ "gaming.meta.stackexchange", "0000001108.txt" ]
Q: Can we have a "show only favorite tags" option? On Stack Overflow, there is no option to show only favorite tags. The reason for that is given here: We believe that browsing by tag, and tag combination, should be sufficient. The bleedthrough and forced exposure to other topics is intentional; we believe programmers have more in common across languages and disciplines than they think they do. We don't want to create more "ghettos" where programmers only care about or look at certain pet topics. Good programmers are well-rounded, and are aware of the world outside their "special preferred" tag. That reasoning doesn't hold up so well on Gaming. If I'm really into, say, Fallout: New Vegas, it's not going to help me "develop my craft" to see questions about World of Warcraft. It'll be a lot easier for me β€” and, I think, everyone else β€” to list a few games I am interested in than to list every single game I'm not interested in. Fortunately, since we tag with game names here, this comes down to a tag handling tweak. Can we get a "show only favorite tags" feature to supplement the "hide ignored tags" feature? And yes, I know, as an engine-related question, this really belongs on Meta Stack Overflow, but I thought I'd gauge interest here before I brought it up there. A: If you add the following lines to a user style sheet for this site, you should see only questions in your tags. .question-summary { display: none; } .tagged-interesting { display: block; } Note that they'll need to appear in that order so that the later rule supersedes the earlier one. (You could also add !important to the tagged-interesting rule.) Of course, this won't change the question counts, and you may actually see some pages with no questions at all, but you should be able to page back and forth as you normally would. This also won't affect questions in the sidebar; those have no identifying characteristics (other than question number) and thus can't be filtered in a similar fashion client-side.
[ "webmasters.stackexchange", "0000061807.txt" ]
Q: Unwanted hyperlinks containing 'msocom1' inserted into my WordPress content I have found several unwanted nonsensical hyperlinks inserted into unpublished content on my website (self-hosted WordPress). Four of these are to "#_msocom_1". Googling on "#_msocom_1" returns 519 results; Googling on "msocom1" returns 602 results. I've checked a sample and all seem to be similar to my situation - they are nonsensical text inserted in the content (whether or not as a hyperlink). Unfortunately I can't find any explanation of why/how they occur. Question: Have others noticed these nonsensical hyperlinks? Is there a known explanation? Does 'msocom1' actually mean something? Note: I have not mis-spelled this term. It is 'msocom1'; it is NOT 'mscomm1'. Addendum#1: there are/were other nonsensical hyperlinks. For example the words "content in" were turned into a hyperlink to 'http://content.in'. There are another 22 of these nonsensical hyperlinks. A: As mentioned in comments, this would seem to be the result of pasting content from Microsoft Word. Perhaps where the original document contained embedded comments - "msocom" - MicroSOft COMment. Comments in this WordPress ticket/thread would seem to suggest that MSWord tries to convert the comments into linked footnotes in the resulting HTML. There is an example of pasted content and the resulting HTML which contains #_msocom_1. Also discussed in the linked document is a recent update to WordPress/TinyMCE to "fix" issues of pasting content from Word. A lot of users do seem to paste content from Word (which has historically always been problematic), so this could go a long way to explaining why there are "so many unexplained examples on the net".
[ "stackoverflow", "0051739812.txt" ]
Q: Startup script not running on GCP Compute Engine windows server with autoscaling turned on I have a Managed Group in Computer engine on GCP. Autoscaling is set up and running but when a new server comes on or if I do a "Rolling Replace" the start up script is not being run. It is a very simple script that makes sure the latest code is running on the website. This is a screenshot from the "Template" that is used to create the new VMs If I RDP into the box and run the exact same two lines of code, it works fine. Is there something that I need to do before or after the script to make sure that the VM is fully up and ready for the command? Or something else that needs to be done. A: When using a Startup Script in Windows, you need to use a specific key depending on what type of startup up script you would like to run. In your case, you are running cmd commands so in this case you have to replace the key "startup-script" with "windows-startup-script-cmd" within the Template as described here.
[ "askubuntu", "0000086996.txt" ]
Q: Can I use this laptop in Ubuntu 11.10? ASUS A53SV-SX538V Technical: Processor: Intel Core i7-2670QM (4x2, 20 GHz / 6 MB cache). Display / Resolution: 15.6 "Glossy / 1366x768. RAM / HDD: 4 GB DDR3 RAM / 500 GB (5400 rpm). Graphics Card: nVidia GT 540M with 2 GB DDR3 (dedicated). Dimensions / Weight: 378x253x28, 3 to 34.9 mm / 2.60 kg The graph that integrates a dedicated nVidia GeForce GT 540m 2 GB of DDR3 memory, with which we can take current games with games at medium-high quality depending on the requirements of each title, you can look at a list of the games most prominent and of how to play with this chart here. Includes Optimus technology will allow us to save energy, thus extending the battery life if you do not need much graphics horsepower. With CUDA instructions will help the processor complex calculations provided that the programs that implement them. Regards, thanks. A: You cant choose between the IGP and the discrete card. You either work with both with buggy bumblebee or disable the discrete card. Optimus tecnology doesnt allow you to choose between both of them. The IGP is the one displaying the video, the discrete cards only is turned on when is required (heavy load scenario), but the IGP is the one displaying the video on the screen always. Nvidia is not interested in bringing Optimus to Linux, due a lot of work needed in the X and the few percentage of us using Linux. My advice is if you are gonna buy a Sandy Bridge, buy a laptop without a discrete card and save some money, or at least, an ATI card. Linux Hybrid Graphics with ATI via vgaswitcheroo works better, but is far from perfect. Is a NVIDIA GeForce with Optimus Technology supported by Ubuntu?
[ "stackoverflow", "0026561571.txt" ]
Q: Xcode C++ : Build in Debug but not Release I am coding in Xcode 6, c++. I can build and run fine my program in debug, but I somehow can't compile in Release mode. The error I see is : Apple LLVM 6.0 Error Could not read profile: No such file or directory I don't really know what this means... ( I still get this after reducing the main.cpp file to a usual "Hello World" program) I have tried, as suggested in Xcode builds on Debug but not on Release to clean my project, close it, close Xcode restart and rebuild, or even deleting Derived Data but I still have the same problem. Does anyone know how to fix this? Many thx T A: I found out the answer to my question. You have to specify : "Use Optimisation Profile" to false
[ "stackoverflow", "0047755534.txt" ]
Q: dplyr rename - Error: `new_name` = old_name must be a symbol or a string, not formula I am trying to rename a column with dplyr::rename() and R is returning this error that I am unable to find anywhere online. Error: `new_name` = old_name must be a symbol or a string, not formula Reproducible example with a 2 column data frame: library(dplyr) df <- data.frame(old_name = seq(1:10), x = seq(1:10)) df %>% dplyr::rename(new_name = old_name) Session info: > sessionInfo() R version 3.4.3 (2017-11-30) Platform: x86_64-apple-darwin17.2.0 (64-bit) Running under: macOS High Sierra 10.13.1 Matrix products: default BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib LAPACK: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libLAPACK.dylib locale: [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] dplyr_0.7.4 loaded via a namespace (and not attached): [1] compiler_3.4.3 magrittr_1.5 assertthat_0.2.0 R6_2.2.2 [5] bindrcpp_0.2 glue_1.2.0 tibble_1.3.4 Rcpp_0.12.14.3 [9] pkgconfig_2.0.1 rlang_0.1.4.9000 bindr_0.1 > I expect this new simple data frame to have the first column renamed to new_name. This also does not work with rename_(). Current R version is 3.4.3 and dplyr version is 0.7.4. I was unable to replicate this on R version 3.3.3, but was able to replicate it on R version 3.4.0. This was tested on a completely clean R session. My current solution is to rewrite part of my code with plyr::rename as that still works, but this is not ideal because it requires me to rewrite a lot of code. Working example with plyr(): library(plyr) df <- data.frame(old_name = seq(1:10), x = seq(1:10)) df %>% plyr::rename(replace = c('old_name' = 'new_name')) A: As @aosmith commented, this is a result of using the dev version of the rlang package (from GitHub) with the released version of dplyr (from CRAN). Full discussion is here: https://github.com/tidyverse/dplyr/issues/3252 Both packages should be from CRAN or both from GitHub; the mismatch is the problem. To fix this, you can update your dplyr to the dev version with devtools::install_github("tidyverse/dplyr") or revert your rlang install back to the current CRAN version. A: I had the same problem. After updating all packages just in case, it works (see sessionInfo() below. Fix Switch rename to select (which was working for some reason) df <- data.frame(old_name = seq(1:10), x = seq(1:10)) ## df %>% dplyr::rename(new_name = old_name) # error df %>% dplyr::select(new_name = old_name, everything()) That might be easier than the plyr strat, and if updating doesn't fix it. > sessionInfo() R version 3.4.0 (2017-04-21) Platform: x86_64-apple-darwin15.6.0 (64-bit) Running under: macOS 10.13.2 Matrix products: default BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib locale: [1] en_CA.UTF-8/en_CA.UTF-8/en_CA.UTF-8/C/en_CA.UTF-8/en_CA.UTF-8 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] rlang_0.1.6 dplyr_0.7.4 loaded via a namespace (and not attached): [1] compiler_3.4.0 magrittr_1.5 assertthat_0.2.0 R6_2.2.2 [5] tools_3.4.0 bindrcpp_0.2 glue_1.2.0 tibble_1.3.4 [9] yaml_2.1.16 Rcpp_0.12.14 pkgconfig_2.0.1 bindr_0.1
[ "stackoverflow", "0017918686.txt" ]
Q: How can I deserialize integer number to int, not to long? I'm using Json.NET to deserialize requests on the server-side. There is something like public object[] Values I need to put in values like 30.0, 27, 54.002, and they need to be double's and int's. Json.NET has a deserialization property called FloatParseHandling, but there is no option like IntParseHandling. So the question is how can I deserialize integers to int? A: Your best bet is to deserialize into a typed model where the model expresses that Values is an int / int[] / etc. In the case of something that has to be object / object[] (presumably because the type is not well-known in advance, or it is an array of heterogeneous items), then it is not unreasonable for JSON.NET to default to long, since that will cause the least confusion when there are a mixture of big and small values in the array. Besides which, it has no way of knowing what the value was on the way in (3L (a long), when serialized in JSON, looks identical to 3 (an int)). You could simply post-process Values and look for any that are long and in the int range: for(int i = 0 ; i < Values.Length ; i++) { if(Values[i] is long) { long l = (long)Values[i]; if(l >= int.MinValue && l <= int.MaxValue) Values[i] = (int)l; } }
[ "stackoverflow", "0060447892.txt" ]
Q: Nodejs - how to track after errors? Yesterday I deployed my first nodejs app everything was fine, I woke up today and I saw the server stoped because error with some package. How can I track after all the errors, and make the server not to go down even there is some error? A: You can use PM2 as a process manager npm install pm2 -g Good practice is generate a ecosystem config pm2 ecosystem ecosystem.config.ts apps: [ { name: 'My application', script: 'npm', args: 'start', autorestart: true, instance_var: 'my-app', out_file: '/path/to/out.log', log_file: '/path/to/global.log', error_file: '/path/to/error.log' } ] }; Also you can use npx instead of globally install pm2. You can start you app with pm2 start ecosystem.config.js (or npx pm2 start ecosystem.config.js if you like). To see list of started processes and its statuses use pm2 list or npx pm2 list
[ "stackoverflow", "0027868026.txt" ]
Q: SQL Server Integrated Authentication on Weblogic Server I'm developing a web application that accesses data on MS SQL Server 2012. My company's production environment already has connections to the database set up using SQL Server Authentication. My Active Directory account does not include SQL Server authentication, and we use Integrated Authentication when we are developing on our local machines. I am testing my application by deploying it to a local instance of Weblogic 10.3.4. I am receiving this exception when attempting to create the connection pool on the Administration Console: <Error> <Console> <BEA-240003> <Console encountered the following error com.microsoft.sqlserver.jdbc.SQLServerException: This driver is not configured for integrated authentication. I've added sqljdbc_auth.dll to the classpath on the server, and added: -Djava.library.path=C:\programdata\Oracle\WebLogicServer\10.3.4\user_projects\domains\JDEV\lib to my server start arguments in the Environment -> Server Start tab on the management console, but there is still something wrong. Any help will be greatly appreciated! A: I found the problem. I believe that I did not have the sqljdbc_auth.dll in the correct location. It belongs in: %path%\WebLogicServer\10.3.4\wlserver_10.3\server\native\win\x64 Once I put this file in the correct location, the configuration worked right away. It is also important to note that the version number on these files is very important. Make sure that your sqljdbc4.jar and sqljdbc_auth.dll versions are exactly the same, otherwise the container will blow up and you'll end up being frustrated like me.
[ "codegolf.stackexchange", "0000201134.txt" ]
Q: Quotes around sequence of chars Challenge Your goal is to write a function that puts quotes around a sequence of capital letters in a string. So some examples (everything on the left (before function) and right (after function) are STRINGS): Hello the name's John Cena -> "H"ello the name's "J"ohn "C"ena I got BIG OLD truck -> "I" got "BIG" "OLD" truck [OLD, joe, SMOE] ->["OLD", joe, "SMOE"] 'BIG') -> '"BIG"') fOOd -> f"OO"d "78176&@*#dd09)*@(&#*@9a0YOYOYOYOYOYOOYOYOYOY28#@e -> "78176&@*#dd09)*@(&#*@9a0"YOYOYOYOYOYOOYOYOYOY"28#@e Assumptions and Clarifications The sequence of capital letters can have a length of one (e.g. a string containing one character: H -> "H") You can assume there will be only a string inputted. Winning Criteria Code golf, fewest bytes wins. A: 05AB1E, 13 bytes 0.ø.γ.u}'"ý¦¨ Try it online! 0.ø # surround input string with 0s .γ } # group characters by: .u # is uppercase? '"ý # join groups with quotes ¦¨ # remove the first and last characters (0s) A: Perl 5, 15 bytes s/[A-Z]+/"$&"/g Try it online! A: JavaScript (ES6),  32  30 bytes Using a reference to the last match Version suggested by @Grimmy Saved 2 bytes thanks to @Shaggy s=>s.replace(/[A-Z]+/g,'"$&"') Try it online! JavaScript (ES6), 35 bytes With a callback function s=>s.replace(/[A-Z]+/g,s=>`"${s}"`) Try it online!
[ "stats.stackexchange", "0000067938.txt" ]
Q: How to handle categorical predictors with too many levels? I think it may be a problem if we directly use dummy variable for a categorical predictor having hundreds of levels. I have found one solution from the book 'Elements of Statistical Learning' (p.329). The solution is mentioned in classification tree sections. Specifically, the solution orders the levels of the categorical predictor by the number of occurrence of each level in one class, and then treats the predictor as an ordered predictors. I wonder for models other than classification tree, such as linear regression, what would be proper ways of handling categorical predictors with too many levels. I found an old post asking similar questions, but no answers have been posted: Categorical logit Predictor with too many different levels A: I can't see that ordering the levels by frequency creates an ordinal variable. Shrinkage is necessary to deal with this problem, either by using penalized maximum likelihood estimation (e.g., R rms package's ols and lrm functions for quadratic (ridge) L2 penalty) or using random effects. You can get predictions for individual levels easily using penalized maximum likelihood estimation, or by using BLUPS in the mixed effects modeling context.
[ "math.stackexchange", "0003220273.txt" ]
Q: Why are parallelograms defined as quadrilaterals? What term would encompass polygons with greater than two parallel pairs? It seems the definition of a parallelogram is locked to quadrilaterals for some reason. Is there a reason for this? Why couldn't a parallelogram (given the way the word seems rather than as a mathematical/geometric construct) contain greater than two pairs of parallel sides? In a hexagon for example, all six sides are parallel to their opposing side. Is there a term for this kind of object? It seems to me there must be some value in describing a polygon with even numbers of sides in which the opposing sides are parallel to each other. While a hexagon, octagon, decagon, etc. all match this rule, you could have polygons with unequal sides as well. Edit 1: Object described by Mark Fischler Zonogon: A: Interesting question. Parallelograms are quadrilaterals for historical reasons. They could have been defined to include your examples, but weren't. Now the meaning is so common that it can't be changed. I don't think there is a name for your class of polygons. The reason is in this: It seems to me there must be some value in describing a polygon with even numbers of sides in which the opposing sides are parallel to each other. If there were some value - if these polygons came up often in geometry - then someone would have named them. If you have interesting things to say about them and publish your thoughts you'll invent a name in your paper. If it's widely read the name will stick. I thought parallelogon would be a good possibility, but that name is taken: https://en.wikipedia.org/wiki/Parallelogon . The convex polygons whose sides come in equal parallel pairs are zonogons: https://en.wikipedia.org/wiki/Zonogon . Your polygons have zonogons as nontrivial Minkowski summands. A: I'm going to propose, out of the blue, terms like "hexaparallelogram", "octaparallelogram", and so forth. I'm wondering whether, for more than $4$ sides, you would like your definition of hexaparallelogram to be restricted to having 3 pairs of parallel and pairwise equal sides (as in your picture - evidently these have a name, zonogon), or would you include a hexagon with vertices at $\{(0,0), (12,0), (16,6), (4,12), (0,12), (-6,3)\}$ which has three pairs of parallel sides but no two sides of equal length? Euclid, in proposition 34, introduces the term (Ο€Ξ±ΟΞ±Ξ»Ξ»Ξ·Ξ»ΟŒΞ³ΟΞ±ΞΌΞΌΞ± χωρία) which we can translate to "parallelogrammic area." So much for the etymology sites that trace the word only to Middle French. Euclid himself restricted the word to just four-sided figures. Proclus credits Euclid with having introduced the term "parallelogram," as opposed to bringing down that term from earlier works. So that tells us who to blame.
[ "stackoverflow", "0006453034.txt" ]
Q: android how to set time for progressdialog In my app i have a processDialog (using AsyncTask) and at doInbackground it fetches data from server. all are working perfectly. But I want if Internet is slow then it gives an warning alert that "problem with ur internet connection" so for that i want to know how much time the progressDialog takes upto dismiss. so that i can put a condition that if time > 5imns then that alert will come. How can i get how much time it takes or how to set time for dialog. plz anybody answer me. thank you in advance below my code is there, public class InfoActivity extends Activity { private TextView tvRestroName, tvRestroAddr, tvRestroArea, tvRestroCity, tvRestroPhone, tvRestroRating, tvRestroCuisines, tvRestroAttr; private ImageView imgRestro; private ImageAdapter coverImageAdapter = new ImageAdapter(this); private ScrollView sv; static Bitmap restroBitmap, selectedImage; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); // This activity has two different views so to bind two views // LinearLayout is used here // from two views one is xml and another is coverflow class LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); LayoutInflater inflater = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.info, null); // adding one view as xml ll.addView(view); CoverFlow coverFlow; coverFlow = new CoverFlow(this); coverFlow.setAdapter(new ImageAdapter(this)); // set Imageadapter which is define within InfoActivity class coverFlow.setAdapter(coverImageAdapter); coverFlow.setSpacing(-25); coverFlow.setSelection(4, true); coverFlow.setAnimationDuration(1000); // and another view as class ll.addView(coverFlow); sv = new ScrollView(this); sv.addView(ll); // To add all views to InfoActivity setContentView(sv); // to initialize all variables like textview and imageview setupViews(); // for progress dialog new DownloadTask().execute(this); // click event of images within imageadapter coverFlow.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { Toast.makeText(InfoActivity.this, "" + (position + 1), Toast.LENGTH_SHORT).show(); // imageView.setImageResource(mImageIds[arg2]); String slImg = TabHostActivity.galleryArray[position]; selectedImage = loadBitmap(slImg); Intent i = new Intent(InfoActivity.this, PostCommentActivity.class); startActivity(i); } }); } // to initialize all variables like textview and imageview private void setupViews() { imgRestro = (ImageView) findViewById(R.id.imageResturant); tvRestroName = (TextView) findViewById(R.id.tvRestroName); tvRestroAddr = (TextView) findViewById(R.id.tvRestroAddr); tvRestroArea = (TextView) findViewById(R.id.tvRestroArea); tvRestroCity = (TextView) findViewById(R.id.tvRestroCity); tvRestroPhone = (TextView) findViewById(R.id.tvRestroPhone); tvRestroRating = (TextView) findViewById(R.id.tvRestroRating); tvRestroCuisines = (TextView) findViewById(R.id.tvRestroCuisines); tvRestroAttr = (TextView) findViewById(R.id.tvRestroAttributes); } // set values to all fields private void setupValues() { tvRestroName.setText("Restaurant " + TabHostActivity.restroName); //Bitmap bmp = loadBitmap(TabHostActivity.restroImageurl); System.out.println("str ;" + TabHostActivity.restroImageurl); imgRestro.setImageBitmap(Bitmap.createScaledBitmap(restroBitmap, 300, 300, true)); System.out.println("Image seted"); tvRestroAddr.setText("Address: " + TabHostActivity.addr); tvRestroArea.setText("Area: " + TabHostActivity.area); tvRestroCity.setText("City:" + TabHostActivity.city); String phones = "Phones: "; for (int i = 0; i < TabHostActivity.phoneArray.length; i++) phones += TabHostActivity.phoneArray[i] + ", "; tvRestroPhone.setText(phones.substring(0, phones.length() - 2)); tvRestroRating.setText("Rating: " + TabHostActivity.rating); String cuisines = "Cuisines: "; for (int i = 0; i < TabHostActivity.cuisinesArray.length; i++) cuisines += TabHostActivity.cuisinesArray[i] + ", "; tvRestroCuisines.setText(cuisines.substring(0, cuisines.length() - 2)); String attr = "Attributes: "; for (int i = 0; i < TabHostActivity.attributesArray.length; i++) attr += TabHostActivity.attributesArray[i] + ", "; tvRestroAttr.setText(attr.substring(0, attr.length() - 2)); } // to get image from url in form of bitmap private static Bitmap loadBitmap(String url) { URL myFileUrl = null; InputStream is = null; try { myFileUrl = new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) myFileUrl .openConnection(); conn.setDoInput(true); conn.connect(); is = conn.getInputStream(); Log.i("i m connected", "Download in info for main image"); } catch (IOException e) { e.printStackTrace(); } Log.i("i m connected", "Download in info for main image"); return BitmapFactory.decodeStream(is); } // for progressdialog private class DownloadTask extends AsyncTask<Context, Integer, Void> { private ProgressDialog Dialog = new ProgressDialog(InfoActivity.this); @Override protected void onPreExecute() { System.out.println("In onPreExecute "); Dialog.setTitle("Loading"); Dialog.setMessage("Please wait for few seconds..."); //Dialog.setMax(100); //Dialog.setProgress(0); Dialog.show(); } @Override protected Void doInBackground(Context... params) { System.out.println("In doInBackground "); //examineJSONFile(); restroBitmap= loadBitmap(TabHostActivity.restroImageurl); System.out.println("conversion of bitmap done"); int i = 0; System.out.println("In doInBackground "); Dialog.dismiss(); //Dialog.cancel(); for (i = 0; i < 10; i++) System.out.println("In doInBackground " + i); Bitmap bitmap = null; for (i = 0; i < TabHostActivity.galleryArray.length; i++) { try { publishProgress(i); } catch (Exception e) { Log.i("in while", e.getMessage()); } bitmap = loadBitmap(TabHostActivity.galleryArray[i]); TabHostActivity.bitmapHash.remove(TabHostActivity.galleryArray[i]); TabHostActivity.bitmapHash.put(TabHostActivity.galleryArray[i], bitmap); } return null; } @Override protected void onProgressUpdate(Integer... progress) { if (progress[0]==0) { setupValues(); System.out.println("setupvalues"); } else { System.out.println("In progress "); coverImageAdapter.setnotify(); } } @Override protected void onPostExecute(Void arg) { System.out.println("In onPostExecute "); } } public class ImageAdapter extends BaseAdapter { int mGalleryItemBackground; private Context mContext; private BitmapDrawable drawable; private FileInputStream fis; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return TabHostActivity.galleryArray.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public void setnotify() { notifyDataSetChanged(); } public View getView(int position, View convertView, ViewGroup parent) { ImageView i = new ImageView(mContext); fetchDummy(TabHostActivity.galleryArray[position], i); i.setLayoutParams(new CoverFlow.LayoutParams(200, 200)); i.setScaleType(ImageView.ScaleType.CENTER_INSIDE); // Make sure we set anti-aliasing otherwise we get jaggies drawable = (BitmapDrawable) i.getDrawable(); try { drawable.setAntiAlias(true); } catch (Exception e) { System.out.println("Exception in getview :" + e); } return i; // return mImages[position]; } /** * Returns the size (0.0f to 1.0f) of the views depending on the * 'offset' to the center. */ public float getScale(boolean focused, int offset) { /* Formula: 1 / (2 ^ offset) */ return Math.max(1, 2.0f / (float) Math.pow(2, Math.abs(offset))); } private void fetchDummy(String urlString, ImageView i) { if (TabHostActivity.bitmapHash.containsKey(urlString)) { i.setImageBitmap(TabHostActivity.bitmapHash.get(urlString)); } } } A: Just track the start time when you create the async task (either in the class creation, or in the onPreExecute()). Then every onProgressUpdate() check how long has occurred, and do your appropriate timeout logic. If you're only using a simple spinner dialog for progress and not calling onProgressUpdate(), then you're going to have to redesign your doInBackground to periodically call it, as you can only show UI changes in the onProgressUpdate() and not in the background thread. Edit: Comments on your uploaded code. Using BitmapFactory.decodeStream(is) means you're not able to check the internet slowness easily. You could change this to load the stream into a byte[] in a read loop, and monitor the time it takes there, and then throw a timeout exception to the donInBackground() method if it's going too slow. The doInBackground() can then trap the exception return an appropriate code to the onPostExecute(). The onPostExecute() needs to take an int param, and decide what to do there, e.g. if you pass a code 0, it can assume everything was ok, and close the dialog. If it gets 1, then assume there was a timeout and close the dialog, followed by showing a "Your connection timed out" message. Roughly speaking the code would be (I haven't tried this out): // ... conn.setDoInput(true); conn.connect(); is = conn.getInputStream(); Log.i("i m connected", "Download in info for main image"); } catch (IOException e) { e.printStackTrace(); } Log.i("i m connected", "Download in info for main image"); // read the InputStream into an array long startTime = System.currentTimeMillis(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); if ((System.currentTimeMillis() - startTime) > 60000) { is.close(); throw new MyTimeoutException(); } } return BitmapFactory.decodeByteArray(buffer.toByteArray()); } @Override protected Integer doInBackground(Context... params) { // ... Bitmap bitmap = null; for (i = 0; i < TabHostActivity.galleryArray.length; i++) { try { publishProgress(i); } catch (Exception e) { Log.i("in while", e.getMessage()); } try { bitmap = loadBitmap(TabHostActivity.galleryArray[i]); } catch (MyTimeoutException e) { return RESULT_TIMEOUT; } TabHostActivity.bitmapHash.remove(TabHostActivity.galleryArray[i]); TabHostActivity.bitmapHash.put(TabHostActivity.galleryArray[i], bitmap); } return RESULT_OK; } @Override protected void onPostExecute(Integer resultCode) { if (resultCode == RESULT_OK) { // ... things were good, close dialog etc } else { // ... close spinner and show a "timeout" dialog } }
[ "stackoverflow", "0041645172.txt" ]
Q: How to remove all inferred implicits in a macro? I need to really untypecheck the trees that are emitted by my macro. That means not only removing inferred types and all that, but also removing the implicit arguments that are inferred by the compiler. Not even resetAllAttrs seems to take care of that. Symbols appear to have a method isSynthetic that indicates whether code was generated by the compiler, but apparently that flag is only set for things like autogenerated getters and setters, not for implicit values that the compiler inserts. I could of course manually look for all implicit argument lists and remove them, but then I will also remove the ones that were explicitly provided by the user of my macro. So ideally for the following code scala> def foo(a: Int)(implicit e: DummyImplicit) = a foo: (a: Int)(implicit e: DummyImplicit)Int scala> myMacro{ foo(4); foo(2)(DummyImplicit.dummyImplicit) } myMacro would emit the tree { foo(4); foo(2)(Predef.this.DummyImplicit.dummyImplicit) } that is then typechecked again and compiled. But I'm afraid this can't be done... A: They have internal API to detect the implicitly supplied args, but it is commented as unstable. (They'll use a tree attachment instead of a subtype of Apply.) $ scala Welcome to Scala 2.12.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_111). Type in expressions for evaluation. Or try :help. scala> import language.experimental.macros import language.experimental.macros scala> import reflect.macros.blackbox.Context import reflect.macros.blackbox.Context scala> def fImpl(c: Context)(block: c.Expr[Any]): c.Expr[Boolean] = c.Expr { import c._, universe._ | val trees = universe.asInstanceOf[reflect.internal.Trees] | block.tree match { | case t@Apply(_,_) => Literal(Constant(t.isInstanceOf[trees.ApplyToImplicitArgs])) | case _ => Literal(Constant(false)) }} fImpl: (c: scala.reflect.macros.blackbox.Context)(block: c.Expr[Any])c.Expr[Boolean] scala> def f(block: Any): Boolean = macro fImpl defined term macro f: (block: Any)Boolean scala> def g(implicit d: DummyImplicit) = 42 g: (implicit d: DummyImplicit)Int scala> f(println("")) res0: Boolean = false scala> f(g) res1: Boolean = true scala> f(g(new DummyImplicit)) res2: Boolean = false
[ "stackoverflow", "0005624366.txt" ]
Q: dynamically load external JS and write response to a div I'm embedding a delicious feed into my page. When I just add the script tags inside the div it obviously loads before the rest of my JS (at the bottom of the page). I'd like to load this script into the specified div dynamically after all other js has loaded. I've tried the getscript function, but it definitely breaks the page when I use it with .html(): $('#delicious').html(function(){ $.getScript("http://feeds.delicious.com/v2/js/bayonnebridge?title=My%20Delicious%20Bookmarks&icon=m&count=5&sort=date&tags&extended&name&showadd"); }); I can't seem to wrap my head around how I can print the results of that file into the #delicious div. A: If you want to display the script in the div, shouldn't it be something like this, making use of the callback function? $.getScript("http://feeds.delicious.com/v2/js/bayonnebridge?title=My%20Delicious%20Bookmarks&icon=m&count=5&sort=date&tags&extended&name&showadd", function(data){ $('#delicious').html(data); }); The result of $.getScript() is the XMLHTTPRequest object and it seems like you want the response text instead. Also, it looks like the response from the URL you've given attempts to write the script into the document, thus overwriting all your page content. It that is your problem you might consider using an iframe and setting this URL as it's source. I also seem to get different behaviour depending on whether the script is being loaded cross-domain or from the same domain - I'm not quite sure what to make of that since getScript() is supposed to work cross-domain.
[ "stackoverflow", "0022422178.txt" ]
Q: mongodb remove all dates less than specified I have the following data. { deviceID: 186, date: "2014-3-15" } { deviceID: 186, date: "2014-3-14" } { deviceID: 186, date: "2014-3-13" } And some lower dates, like 2014-3-9 , 8 ,7 ,6 etc. When doing a db.coll.remove({date:{$lte:"2014-3-5"}}) Mongo removes the 15,14,13 aswell, but keeps single digit day dates. Is this maybe due to the date is a string? I dont know how else to format the date so I can remove all dates below a certain date. It is supposed to be a cleaning process, removing all documents with a date lower than specified. A: Its because the date field you are querying on is a string filed and not a Date(). In your mongo documents instead of a custom date string, insert javascript date objects into date field. like { deviceID: 186,,"date": new Date(2012, 7, 14) } and when you execute the remove do it like db.coll.remove({date:{$lte:new Date(2012, 7, 14)}})
[ "stackoverflow", "0048469486.txt" ]
Q: How to Access Views for Appointment entity in CRM 2013 using SQL? I would like to see the list of views existing for an Appointment entity like "All Appointments", "My Appointments","Appointments Associated view". I tried the following query but it is returning some 2454 records where Appointment has only 3 views. SELECT s.Name FROM dbo.SavedQuery s INNER JOIN dbo.EntityView LV ON LV.EntityId = EntityId WHERE LV.Name = 'Appointment' Please correct me where I am making mistake. A: To get the list of public views for any entity from onpremise CRM database, use the query like below: SELECT Name FROM SavedQuery WHERE ReturnedTypeCode = '<entity logical name>' For Appointment, it should be WHERE ReturnedTypeCode = 'appointment' Update: I don't have access to on-premise to query the SQL, but MSDN says like below: SavedQuery.ReturnedTypeCode: Matches the logical name of the entity. Try 4201 for appointment & see if it results.
[ "math.stackexchange", "0001109062.txt" ]
Q: probability - What is the distribution of this descrete random variable? We have $N$ balls in the bag, numbered from $1$ to $N$. we pop balls with no returning them to the bag. let $X$ be "the number of the ball that we poped first", andy $Y$ is the second ball that we poped. So, i understand that $X\:~\:U\left(1,N\right)$, but i don't get what is the distribution of $Y$, because its realy depends on $X$. I saw somewhere that it also $Y\:~\:U\left(1,N\right)$ but i dont understand why..can someone prove me? tnx a lot! A: It is clear that $Y$ can take up $N-1$ possible values. $P(Y=y)=\sum_{x=1}^NP(Y=y|X=x)P(X=x)$ Now $X\in U(1,N)$ hence $P(X=x)=\dfrac{1}{N}$ for all $x\in\{1,2,...,N\}$. Note that in the above sentence in finding $P(Y=y)$ the component $P(Y=y|X=y)P(X=y)=0$ as you are considering Without Replacement sampling. So there are $N-1$ terms in the sum on the R.H.S. Now given that we know which ball has been already popped, there are $N-1$ choices for $Y$. $\therefore P(Y=y)=P(Y=1|X=x)P(X=x)+...+P(Y=y|X=x-1)P(X=x-1)+P(Y=y|X=x+1)P(X=x+1)+...+P(Y=y|X=n)P(X=n)=\dfrac{1}{N}(\dfrac{1}{N-1}+\dfrac{1}{N-1}+...+\dfrac{1}{N-1})=\dfrac{1}{N}$ Thus, $Y\in U(1,N)$.
[ "stackoverflow", "0023621045.txt" ]
Q: Can't get SQL code working on Visual Studio With the exception of a little HTML/Javascript, I've always used C++ on Visual Studio C++ 2010. I have an internship next week that will involve the use of SQL and .Net. I'm currently reading a book on SQL and it instructs us to go to its website to download code so that we can practice. The website is here: http://forta.com/books/0672336073/ I downloaded the one labeled "Microsoft SQL Server" which is basically two .sql files. One creates a simple database and the other one populates it. However, for the life of me I cant figure out how to do it on Visual Studio 2010 or 2013 (I downloaded the full version of 2010). If anyone knows how to get these file to run on either VS version I would be very happy. I'm used to just hitting the green arrow button in Visual Studio C++ 2010, which I believe is execute. Obviously it isnt working for my sql code. On VS 2013 I created a new "SQL Server Database Project". I then added two new "Application Role" items for the two .sql files. Now after clicking the "SQL" tab and "Execute" I get error messages about duplicate objects/keys, which I assume means the database is already created...but how do I view it? At one instance I mustve hit the right combination of buttons because I was able to view my database in a table format. Thanks for any suggestions! A: In visual studio go to view and select sql server, (see image) then click the + symbol and connect to the server installed on your machine (if its not yet listed)
[ "stackoverflow", "0035444214.txt" ]
Q: SMS Forwarding with Phone ringer Looking for some advice. My relative is deaf. She has a Mi Band on iOS that will vibrate on incoming calls - but no one phones a deaf person! What she needs is it to vibrate when she gets an SMS - which is not supported on iOS. So I'd like to know how I might setup a cheap SMS number to issue to her friends. When this number receives an SMS it should forward it intact AND ring her mobile and hang up. This will vibrate the band. Can Twilio do this? Would I need a server to implement it or can it been done via config within the Twilio service? Thanks for all ideas, Matt A: Twilio developer evangelist here. You could absolutely do this with Twilio. You would need a server with a small application running on it though, I'll explain the flow you would need. The application would need to be available at a URL that you could setup as the messaging request URL when you purchase the Twilio number. Then, when a message was sent to the number, Twilio will make an HTTP request to the URL. Your application would have to do two things in response to that request. To initiate the call, it would need to make a request to the Twilio API. In Ruby you could do the following: require "twilio-ruby" client = Twilio::REST::Client.new("YOUR_TWILIO_ACCOUNT_SID", "YOUR_TWILIO_AUTH_TOKEN") client.calls.create( :to => "YOUR_RELATIVES_NUMBER", :from => "YOUR_TWILIO_NUMBER", :url => "http://your-url.com/hangup" ) To forward the message you would need to return some XML, known as TwiML, to tell Twilio to forward the message to your relative's number too. That XML would look like: <Response> <Message to="YOUR_RELATIVES_NUMBER" from="YOUR_TWILIO_NUMBER">params["Body"]</Message> </Response> You'd need one other endpoint for your application, that would hangup the call when answered. That would return some very simple TwiML like this: <Response> <Hangup/> </Response> All together, using Sinatra as the web framework this would look like: require 'twilio-ruby' require 'sinatra' post '/messages' do client = Twilio::REST::Client.new("YOUR_TWILIO_ACCOUNT_SID", "YOUR_TWILIO_AUTH_TOKEN") client.calls.create( :to => "YOUR_RELATIVES_NUMBER", :from => "YOUR_TWILIO_NUMBER", :url => "http://your-url.com/hangup" ) twiml = Twilio::TwiML::Response.new do |r| r.Message params["Body"], :to => "YOUR_RELATIVES_NUMBER", :from => "YOUR_TWILIO_NUMBER" end return twiml.to_xml end post '/hangup' do twiml = Twilio::TwiML::Response.new do |r| r.Hangup end return twiml.to_xml end The only downside would be that all the messages would appear to come from the Twilio number, as Twilio doesn't allow number spoofing for SMS messages. I noticed that you answered a question on StackOverflow with the C# tag. I'm no C# developer, thus the Ruby examples, but the documentation, which I've linked throughout above, has examples in C# too. Let me know if this helps at all.
[ "stackoverflow", "0038338221.txt" ]
Q: Defining colors of Matplotlib 3D bar plot I can't figure out the right way to set a cmap (or colors) for a 3d bar plot in matplotlib in my iPython notebook. I can setup my chart correctly (28 x 7 labels) in the X and Y plane, with some random Z values. The graph is hard to interpret, and one reason is that the default colors for the x_data labels [1,2,3,4,5] are all the same. Here is the code: %matplotlib inline from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as npfig = plt.figure(figsize=(18,12)) ax = fig.add_subplot(111, projection='3d') x_data, y_data = np.meshgrid(np.arange(5),np.arange(3)) z_data = np.random.rand(3,5).flatten() ax.bar3d(x_data.flatten(), y_data.flatten(),np.zeros(len(z_data)),1,1,z_data,alpha=0.10) Which produces the following chart: I don't want to define the colors manually for the labels x_data. How can I set up different 'random' cmap colors for each of the labels in x_data, still keeping the ax.bar3d parameter? Below is a variation using ax.bar and different colors, but what I need is ax.bar3d. A: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=(18,12)) ax = fig.add_subplot(111, projection='3d') x_data, y_data = np.meshgrid(np.arange(5),np.arange(3)) z_data = np.random.rand(3,5) colors = ['r','g','b'] # colors for every line of y # plot colored 3d bars for i in xrange(3): # cycle though y # I multiply one color by len of x (it is 5) to set one color for y line ax.bar3d(x_data[i], y_data[i], z_data[i], 1, 1, z_data[i], alpha=0.1, color=colors[i]*5) # or use random colors # ax.bar3d(x_data[i], y_data[i], z_data[i], 1, 1, z_data[i], alpha=0.1, color=[np.random.rand(3,1),]*5) plt.show() Result:
[ "stackoverflow", "0060426804.txt" ]
Q: Jest: Cannot spy the property because it is not a function; undefined given instead I'm trying to write a Jest test for a simple React component to confirm that a function has been called when I simulate a click. However, when I use spyOn method, I keep getting TypeError: Cannot read property 'validateOnSave' of undefined. My code looks like this: OptionsView.js class OptionsView extends React.Component { constructor(props) { super(props); this.state = { reasonCode: null, remarkCode: null, otherCode: null, codeSelectionIsInvalid: [false, false, false], }; this.validateOnSave = this.validateOnSave.bind(this); this.saveOptions = this.saveOptions.bind(this); validateOnSave() { const copy = this.state.codeSelectionIsInvalid; copy[0] = !this.state.reasonCode; copy[1] = !this.state.remarkCode; copy[2] = !this.state.otherCode; this.setState({ codeSelectionIsInvalid: copy }); if (!copy[0] && !copy[1] && !copy[2]) { this.saveOptions(); } } saveOptions() { const { saveCallback } = this.props; if (saveCallback !== undefined) { saveCallback({ reasonCode: this.state.reasonCode, remarkCode: this.state.remarkCode, otherCode: this.state.otherCode, }); } } render() { const cx = classNames.bind(styles); const reasonCodes = this.props.reasonCodeset.map(reasonCode => ( <Select.Option value={reasonCode.objectIdentifier} key={reasonCode.objectIdentifier} display={`${reasonCode.name}`} /> )); const remarkCodes = this.props.remarkCodeset.map(remarkCode => ( <Select.Option value={remarkCode.objectIdentifier} key={remarkCode.objectIdentifier} display={`${remarkCode.name}`} /> )); const otherCodes = this.props.otherCodeset.map(otherCode => ( <Select.Option value={otherCode.objectIdentifier} key={otherCode.objectIdentifier} display={`${otherCode.name}`} /> )); return ( <ContentContainer fill> <Spacer marginTop="none" marginBottom="large+1" marginLeft="none" marginRight="none" paddingTop="large+2" paddingBottom="none" paddingLeft="large+2" paddingRight="large+2"> <Fieldset legend="Code sets"> <Grid> <Grid.Row> <Grid.Column tiny={3}> <SelectField selectId="reasons" required placeholder="Select" label="Reasons:" error="Required field is missing" value={this.state.reasonCode} onChange={this.updateReasonCode} isInvalid={this.state.codeSelectionIsInvalid[0]}> {reasonCodes} </SelectField> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column tiny={3}> <SelectField selectId="remarks" required placeholder="Select" label="Remarks:" error="Required field is missing" value={this.state.remarkCode} onChange={this.updateRemarkCode} isInvalid={this.state.codeSelectionIsInvalid[1]}> {remarkCodes} </SelectField> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column tiny={3}> <SelectField selectId="other-codes" required placeholder="Select" label="Other Codes:" error="Required field is missing" value={this.state.otherCode} onChange={this.updateOtherCode} isInvalid={this.state.codeSelectionIsInvalid[2]}> {otherCodes} </SelectField> </Grid.Column> </Grid.Row> </Grid> </Fieldset> </Spacer> <ActionFooter className={cx(['action-header-footer-color'])} end={( <React.Fragment> <Spacer isInlineBlock marginRight="medium"> <Button text="Save" onClick={this.validateOnSave} /> </Spacer> </React.Fragment> )} /> </ContentContainer> ); } } OptionsView.propTypes = propTypes; export default injectIntl(OptionsView); OptionsView.test describe('RemittanceOptions View', () => { let defaultProps = {...defined...} beforeAll(() => { Object.defineProperty(window, "matchMedia", { value: jest.fn(() => { return { matches: true, addEventListener: jest.fn(), removeEventListener: jest.fn(), addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(), } }) }); }); it('should validate remit codes on save', () => { const wrapper = mountWithIntl(<OptionsView {...defaultProps} />); const instance = wrapper.instance(); const spy = jest.spyOn(instance, "validateOnSave"); wrapper.setState({ reasonCode: 84, remarkCode: 10, otherCode: null }); console.log(wrapper.find('Button[text="Save"]').debug()); const button = wrapper.find('Button[text="Save"]').at(0); expect(button.length).toBe(1); button.simulate('click'); expect(spy).toHaveBeenCalled(); expect(wrapper.state('codeSelectionIsInvalid')).toEqual([false,false,true]); }); }); Ultimate goal is to test two cases when save is clicked: When state.codeSelectionIsInvalid: [false,false,true] When state.codeSelectionIsInvalid: [false,false,false] Where am I going wrong here. Any help is appreciated! A: After hours of debugging, found out that the instance didn't have any methods bound. Since it is a connected component, using shallowWithIntl() and dive() resolved the error. it('should validate remit codes on save', () => { const wrapper = shallowWithIntl(<RemitOptionsView {...testProps} />); const button = wrapper.dive().find('Button[text="Save"]'); //Not finding the button const instance = wrapper.dive().instance(); const spy = jest.spyOn(instance, 'validateOnSave'); instance.validateOnSave(); });
[ "gis.stackexchange", "0000030694.txt" ]
Q: OpenLayers Vector KML draw black when change the style I am trying to change the style of an OpenLayers.Vector using radio buttons and redraw it, but the result is a black vector. I tried own build OpenLayers11 and 12, beside api openlayers hosted. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>See kml data</title> <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> <meta http-equiv="Content-Style-Type" content="text/css"> <script type="text/javascript" language="javascript" src="http://openlayers.org/api/OpenLayers.js"></script> <script type="text/javascript"> var osm var eu; var Heatmap = new OpenLayers.Style({ id: 1, name: 'heatmap', fill: true, fillColor: '#FF0000', fillOpacity: 0.5, strokeWidth: 4, strokeColor: 'white' }); var RG = new OpenLayers.StyleMap({ "default": new OpenLayers.Style({ id: 2, name: 'rg', fill: true, fillColor: '#00FF00', fillOpacity: 0.5, strokeColor: 'white' }) }); var RW = new OpenLayers.Style({ id: 3, name: 'rw', fill: true, fillColor: '#FFFF00', fillOpacity: 0.5, strokeColor: 'white' }); function init() { var bounds = new OpenLayers.Bounds( -1177646.439, 4104612.325, 3850226.548, 11465970.640 ); map = new OpenLayers.Map("map", { //allOverlays: true, maxExtent: bounds, //restrictedExtent: bounds }); //osm =new OpenLayers.Layer.WMS( "Open Street Map", //"http://vmap0.tiles.osgeo.org/wms/vmap0", //{ //layers: 'basic', //isBaseLayer: true, //maxExtent: bounds, // sphericalMercator: true, //visibility: false //} //); kml = new OpenLayers.Layer.Vector("KML", { //style: Heatmap, isFixed: false, strategies: [new OpenLayers.Strategy.BBOX()], protocol: new OpenLayers.Protocol.HTTP({ url: "europe.kml", format: new OpenLayers.Format.KML({ extractStyles: false, extractAttributes: false }) }) }); //kml = new OpenLayers.Layer.GML('KML', //"europe.kml", //{ //visibility: true, //format: OpenLayers.Format.KML, //style: Heatmap, //projection: map.displayProjection, //strategies: [new OpenLayers.Strategy.BBOX()] //} //); map.addLayers([osm, kml]); map.addControl(new OpenLayers.Control.Scale($('scale'))); map.addControl(new OpenLayers.Control.MousePosition({ prefix:"long", suffix:"lat", numDigits:4, granularity:true, displayProjection:(new OpenLayers.Projection("EPSG:4326")) })); map.addControl(new OpenLayers.Control.LayerSwitcher()); map.addControl(new OpenLayers.Control.KeyboardDefaults()); map.addControl(new OpenLayers.Control.ScaleLine()); map.zoomToExtent(bounds); } </head> <body onload="init()"> <div id="wrap"> <div id="header"><h1>See kml data with user styling</h1> </div> <div id="main"> <div id="map"></div> </div> <div id="sidebar"><h1>Select style</h1> <form name="styleform"> <input name="iStyle1" type="radio" value="heatmap.kml" id="Heatmap" onclick="choosestyle(this.form)">Heatmap</input> <input name="iStyle2" type="radio" value="RG" id="RG" onclick="choosestyle(this.form)">Red to Green</input> <input name="iStyle3" type="radio" value="RW" id="RW" onclick="choosestyle(this.form)">Red to White</input> </form> </div> <div id="footer"></div> </body> <script type="text/javascript"> function choosestyle(userstyles) { //alert(userstyles.elements[0].value); //var userstyle = document.forms[0].elements[iStyle]; //alert(userstyle.length); for(var i = 0; i < userstyles.length; i++) { if (userstyles[i].checked) { kml.style = userstyles[i].value; kml.redraw(); userstyles[i].checked = false; } } } </script> </html> I tried beside an Openlayers.Vector, Openlayers.GML. I tried beside simple OpenLayers.Style, OpenLayers.StyleMap and server hosted kml style. The results are shown bellow: Any clue would help! Mihai Edit of the choosestyle(userstyles) function which on the alert returns a style object (checked with Firebug DOM): function choosestyle(userstyles) { //alert(userstyles.elements[0].value); //var userstyle = document.forms[0].elements[iStyle]; //alert(userstyle.length); for(var i = 0; i < userstyles.length; i++) { if (userstyles[i].checked) { kml.style = userstyles[i].value; kml.redraw(); alert(kml.style); userstyles[i].checked = false; } } } But the map has the same black color. A: There is working example of your application: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>See kml data</title> <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> <script src="http://openlayers.org/api/OpenLayers.js"></script> <script> var Heatmap = { fill: true, fillColor: '#FF0000', fillOpacity: 0.5, strokeWidth: 4, strokeColor: 'white' }; var RG = { fill: true, fillColor: '#00FF00', fillOpacity: 0.5, strokeColor: 'white' }; var RW = { fill: true, fillColor: '#FFFF00', fillOpacity: 0.5, strokeColor: 'white' }; var styles = {"RW": RW, "RG": RG, "Heatmap": Heatmap}; function choosestyle(userstyles) { for (var i = 0; i < userstyles.length; i++) { if (userstyles[i].checked) { kml.style = styles[userstyles[i].value]; kml.redraw(); userstyles[i].checked = false; } } } function init() { var bounds = new OpenLayers.Bounds(-1177646.439, 4104612.325, 3850226.548, 11465970.640); map = new OpenLayers.Map("map", {maxExtent: bounds}); osm =new OpenLayers.Layer.OSM("Open Street Map"); kml = new OpenLayers.Layer.Vector("KML", { isFixed: false, strategies: [new OpenLayers.Strategy.Fixed()], protocol: new OpenLayers.Protocol.HTTP({ url: "europe.kml", format: new OpenLayers.Format.KML({ extractStyles: false, extractAttributes: false }) }) }); map.addLayers([osm, kml]); map.zoomToExtent(bounds); } </script> </head> <body onload="init()"> <div id="wrap"> <div id="header"><h1>See kml data with user styling</h1> </div> <div id="main"> <div id="map" style="width:640px; height:480px;"></div> </div> <div id="sidebar"><h1>Select style</h1> <form name="styleform"> <input name="iStyle1" type="radio" value="Heatmap" id="Heatmap" onclick="choosestyle(this.form)">Heatmap</input> <input name="iStyle2" type="radio" value="RG" id="RG" onclick="choosestyle(this.form)">Red to Green</input> <input name="iStyle3" type="radio" value="RW" id="RW" onclick="choosestyle(this.form)">Red to White</input> </form> </div> <div id="footer"></div> </body> </html> There are some mistakes in original code: OpenLayers.Layer.Vector.style is symbolizer object, not OpenLayers.StyleMap; userstyles[i].value returns string, not symbolizer, so you need lookup object {"RW": RW, "RG": RG, "Heatmap": Heatmap}; Value of input iStyle1 should be Heatmap.
[ "stackoverflow", "0005079009.txt" ]
Q: "initWithTarget" a variable twice I have a viewController showing some content. In header file, I defined an instance variable named _clientRequest, which is a ClassA object. ClassA deals with downloading Json from server. For different users, there are 1 or 2 places using ClassA in the controller. Currently my codes are like this, // 1st request. every user will do this. _clientRequest = [ClassA alloc] initWithTarget......]; [_clientRequest download]; ... // 2nd request. some user will do this. _clientRequest = [ClassA alloc] initWithTarget......]; [_clientRequest upload]; you may notice that _clientRequest "alloc" and "initWithTarget" twice. In the future, server request may be much more in this controller. So I don't want to declare 1 variable for 1 request. Is anything wrong in above codes? if a variable is alloc and initialized, how about re-alloc and re-initialize it? I run the app and no crash happens. I am a newbie in obj-c. And English is not my native language. Hope you can understand. Thanks in advance! A: This will leak memory because you are allocing ClassA to _clientRequest, then allocing another instance of it without calling release on the first one. When you allocate data in this way, you must release it yourself. You should call [_clientRequest release]; before your second call to [ClassA alloc]...
[ "stackoverflow", "0015546966.txt" ]
Q: open excel file on the above folder with watir/Ruby At moment I am open an Excel file like this excel = WIN32OLE::new("excel.Application") workbook = excel.Workbooks.Open('T:\\PointOfSale\\Projects\\Automated Testing\\MasterFile.xls') worksheet = workbook.WorkSheets(1) # Get first workbook site = worksheet.Range('A2').Value # Get the value at cell in worksheet. and its fine but when i move the scrip to a server i am getting an error message that the Path/file cannot be found. So i decide to user a generic way like when i open a text files excel = WIN32OLE::new("excel.Application") workbook = excel.Workbooks.Open('../../../../Automated Testing/MasterFile.xls') worksheet = workbook.WorkSheets(1) # Get first workbook site = worksheet.Range('A2').Value # Get the value at cell in worksheet. but i get an error message: T:/PointOfSale/Projects/Automated Testing/CSA/Branch_Test/Res Processing/CancelRes/Canc_BE.rb:23:in method_missing': (in OLE methodOpen': ) (WIN32OLERuntimeError) OLE error code:800A03EC in Microsoft Excel '../../../../Automated Testing/MasterFile.xls' could not be found. Check the spelling of the file name, and verify that the file location is correct. If you are trying to open the file from your list of most recently used files, make sure that the file has not been renamed, moved, or deleted. HRESULT error code:0x80020009 Exception occurred. Do you have any idea? A: You need the relative position to your scriptfile itself, something like path = "#{File.dirname(__FILE__)}/../../Automated Testing/MasterFile.xls" workbook = excel.Workbooks.Open(path) I can't be sure where your script file resides so you need to adapt the number of /../ references.
[ "stackoverflow", "0028674432.txt" ]
Q: How to update widget with pjax in modal window in yii2 I have two ActiveForms in a modal window and after submitting first form, I need to update second one and stay in modal. As I understand pjax can handle that, but can't get it to work properly. In _form.php I have ActiveForm with widget which should be updated: <?php $form = ActiveForm::begin([ 'id'=>'form', 'enableAjaxValidation'=>true, ]); ?> <?= Html::activeHiddenInput($riskModel, 'id', ['value' => $riskModel->id]) ?> <?php Pjax::begin([ 'id' => 'solutionItems', ]) ?> //need to update this widget <?= $form->field($riskModel, 'solutions_order')->widget(SortableInput::classname(), [ 'items' => $riskModel->getSolutionList(), 'hideInput' => false, 'options' => ['class'=>'form-control', 'readonly'=>false] ]); ?> <?php Pjax::end() ?> <div class="form-group"> <?= Html::submitButton($riskModel->isNewRecord ? 'Create' : 'Update', ['class' => $riskModel->isNewRecord ? 'btn btn-success' : 'btn btn-primary', 'onclick' => 'return isConnected()']) ?> </div> <?php ActiveForm::end(); ?> And then I have Ajax request which returns success if new solution is created: $.ajax({ url: form.attr('action'), type: 'post', data: form.serialize(), success: function (data) { if (data && data.result == 1) { $.pjax.reload({container:'#solutionItems'}); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { $("#error").html("Kļūda! Neizdevās pievienot ierakstu.").fadeIn('highlight','', 2000, callbackError()); $("#solutions-solution").val(""); } }); But $.pjax.reload({container:'#solutionItems'}); closes the modal. If I put the returned value in a div, then ajax works properly and the modal is not closing. A: Managed without $.pjax, just added this $("#risks-solutions_order-sortable").append('<li data-id="'+data.id+'" data-key="'+data.id+'" draggable="true">'+data.solution+'</li>'); $("ul[id$='sortable'").trigger('sortupdate'); $('#risks-solutions_order-sortable').sortable( "refreshPositions" ); in ajax success and everything is ok! :)
[ "stackoverflow", "0055617475.txt" ]
Q: Xamarin - android: no resource found Executing project, a no resource found error appea in file: <?xml version="1.0" encoding="UTF-8" ?> <animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false"> <item android:drawable="@drawable/spinner/load0.png" android:duration="100" /> <item android:drawable="@drawable/spinner/load1.png" android:duration="100" /> </animation-list> My drawable png images are on folder Resource->drawable->spinner->load0, load1. Where is y fault? A: You cannot add folders in the Drawable folder, Since the ResourceDesigner takes care of all this and Android does not allow user-specific folders in the Resource Folder, Try moving them out of the Spinner folder directly in the resources and use them. For more details check these Can the Android drawable directory contain subdirectories? Possible to create subfolders in drawable folder in Android Studio? The folders that are allowed by Android can be found here https://developer.android.com/guide/topics/resources/providing-resources
[ "stackoverflow", "0054866261.txt" ]
Q: How to get elements from a list that is returned from sapply I have a list that contains different values that represent the occurrence of an event. For example, assume the list occValsList is like: X1=4 X2=11 X3=7 X4=13 X5=2 I would like to get only the values that are higher than 10. To do that, I did the following: which(sapply(occValsList, function(y) y > 10)) But this returns the index of the elements rather than the values: X2 X4 2 4 What I want to return is: X2 X4 11 13 How can I do that? A: Given this list l <- list( X1 = 4, X2 = 11, X3 = 7, X4 = 13, X5 = 2 ) you can do unlist(l[l > 10]) which gives this result X2 X4 11 13
[ "math.stackexchange", "0002632646.txt" ]
Q: $T$ has an eigenvalue of $3$ or $-3$. Given a Linear operator $T$ satisfying $Tv = 3w$ and $Tw = 3v$ for some non-zero vectors $v$ and $w$ i am required to show that $T$ has an eigen value of either $3$ or $-3$. Is it sufficient then to say that because $T(u+v) = Tu+Tv = 3w+3v = 3(v+w)$. $3$ is an eigenvalue of $T$. A: No, it is not sufficient, because $u+v$ might be equal to $0$. You should always suspect that there's something wrong with a proof when it proves more than what is being asked. You are asked to prove that $3$ or $-3$ is an eigenvalue and your proof, if correct, would prove that $3$ is an eigenvalue.
[ "salesforce.stackexchange", "0000217867.txt" ]
Q: Cometd not working in summer 18 We have been using cometd with pushTopic. But we facing an issue an issue in summer 18 org that handshake with cometd is failing in lightning component. if we use lightning component directly in lightning page cometd is working. But if we use a visual force(ltng:outApp) page to display component cometd is not working. In spring 18 it used to work in both classic and lightning. Here is sample code for that is working in spring 18 but not in summer 18. TestPage.vf <apex:page sidebar="false"> <apex:includeLightning /> <div id="lightning" /> <script> $Lightning.use("c:TestApp", function() { $Lightning.createComponent("c:TestComp",{},"lightning",function(cmp) {}); }); </script> </apex:page> TestController.cls public class TestController { @auraEnabled public static String fetchSessionId() { return UserInfo.getSessionId(); } } TestApp.app <aura:application extends ="ltng:outApp"> <aura:dependency resource="markup://c:TestComp"/> </aura:application> TestComp.cmp <aura:component controller="TestController" implements="force:hasRecordId,force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,forceCommunity:availableForAllPageTypes,force:lightningQuickAction"> <aura:attribute name="isPushTopicWorking" type="Boolean" default="false"/> <ltng:require scripts="{!join(',', $Resource.<staticResouceName> + '/cometd.js', $Resource.<staticResouceName> + '/jquery_1_5_1.js', $Resource.<staticResouceName> + '/json2.js', $Resource.<staticResouceName> + '/jquery_cometd.js')}" afterScriptsLoaded="{!c.afterScriptsLoaded}" /> isPushTopicWorking = {!v.isPushTopicWorking} </aura:component> Testcontroller.js ({ afterScriptsLoaded : function(component, event, helper) { var action = component.get('c.fetchSessionId'); action.setCallback(this, function (response) { var sessionId = response.getReturnValue(); helper.setupCometd(component, helper, sessionId); }); $A.enqueueAction(action); }, }) Helper.js ({ setupCometd : function(component, helper, sessionId) { console.log($.cometd); $.cometd.init({ url: window.location.protocol+'//'+window.location.hostname+'/cometd/24.0/', requestHeaders: { Authorization:'OAuth '+sessionId} }); $.cometd.addListener('/meta/handshake', function(message) { console.log(message.successful); }); $.cometd.subscribe('/topic/pustopicname', $A.getCallback(function(message) { component.set('v.isPushTopicWorking',true); })); } }) In summer 18 org we can see error is console log There is no documentation in release notes for change in cometd. What can be causing this issue. A: I don't know if this is the right answer but I'm gonna drop the possibility here... Locker Service defines a few trusted origin domains. Take a look at this commit: https://github.com/forcedotcom/aura/commit/495eaccdc3292a6cf2dcd2c2347c0329c06339e0#diff-7029ab74270f2b05e936f8a47738b1a7 In the code base as of Spring 18's release date, we see (https://github.com/forcedotcom/aura/blob/259fe052729103f069e453978a18ae24f747f6dc/aura-resources/src/main/resources/aura/resources/lockerservice/aura-locker.js): // for relative urls enable sending credentials if (scriptUrl.indexOf('/') === 0) { xhr.withCredentials = true; } In other words, it used to be that any XHR made to a relative URL would be made with credentials. In a more recent commit (prior to the current one), we see: const TRUSTED_CORS_DOMAINS = /(\.lightning\.(.*\.)?force|\.salesforce)\.com$/; /* many lines skipped */ if (normalized.hostname.match(TRUSTED_DOMAINS)) { xhr.withCredentials = true; } In the current code base we see: const TRUSTED_DOMAINS = /\.(force|salesforce)\.com$/; /* many lines skipped */ if (normalized.hostname.match(TRUSTED_DOMAINS)) { xhr.withCredentials = true; } But... if you're running Lightning inside Visualforce via Lightning Out, your Lightning is in fact being served from the Visualforce domain. And if you have enabled the update "Remove Instance Names from URLs for Visualforce, Community Builder, Site.com Studio, and Content Files" then your VF domain name changes from mydomain--c.naXX.visual.force.com to mydomain--c.visualforce.com which does NOT match the regexes above. So I wonder if the Lightning Locker team neglected to consider this possibility?
[ "stackoverflow", "0019992637.txt" ]
Q: Angularjs multiple ajax requests optimization I am still learning Angular JS and have this controller which is making two ajax requests to the lastfm api using different parameters. I want to know when each request has been finished, so that I can display a loading indicator for both requests. I have researched it and read about promises and the $q service but cant get my head around how to incorporate it into this. Is there a better way to set this up? and how can I know when each request is done. Thanks. angular.module('lastfm') .controller('ProfileCtrl', function ($scope, ajaxData, usersSharedInformation, $routeParams) { var username = $routeParams.user; //Get Recent tracks ajaxData.get({ method: 'user.getrecenttracks', api_key: 'key would go here', limit: 20, user: username, format: 'json' }) .then(function (response) { //Check reponse for error message if (response.data.message) { $scope.error = response.data.message; } else { $scope.songs = response.data.recenttracks.track; } }); //Get user info ajaxData.get({ method: 'user.getInfo', api_key: 'key would go here', limit: 20, user: username, format: 'json' }) .then(function (response) { //Check reponse for error message if (response.data.message) { $scope.error = response.data.message; } else { $scope.user = response.data.user; } }); }); I have this factory which handles all the requests angular.module('lastfm') .factory('ajaxData', function ($http, $q) { return { get: function (params) { return $http.get('http://ws.audioscrobbler.com/2.0/', { params : params }); } } }); A: Quite easy using $q.all(). $http itself returns a promise and $q.all() won't resolve until an array of promises are resolved var ajax1=ajaxData.get(....).then(....); var ajax2=ajaxData.get(....).then(....); $q.all([ajax1,ajax2]).then(function(){ /* all done, hide loader*/ })
[ "dba.stackexchange", "0000080550.txt" ]
Q: Additional space required for INDEX REORGANIZE MSDN states: ALTER INDEX REORGANIZE; however, log space is required. The database recovery mode is Simple, does that implies the log space is actually NOT required ?. A: To answer more concisely than the existing answers: REORGANIZE produces the same amount of log with SIMPLE and FULL. It's just that SIMPLE almost immediately makes that space available again. Except if something is preventing log truncation such as an open transaction (unrelated to the session the REORGANIZE runs in).
[ "engineering.stackexchange", "0000016684.txt" ]
Q: How do I denote someone weight How do I say my weight? In which SI units? I see people are using Kg as a unit of denoting weight from my childhood. Answer this question "What's your weight?". A: Weight is a force and is expressed in Newton (N). Mass is expressed in kilogram (kg). However, in informal (non-scientific) language, people often express weight in kg, although this is not correct strictly speaking. The relation between the two is $F=mg$, with $F$ the weight (N), $m$ the mass (kg) and $g$ earth's gravity constant. See also here.
[ "stackoverflow", "0062851250.txt" ]
Q: TinyMCE HTMLField and Django TextField don't show up in production When I visit my Modelform in the admin of my localhost development server all of the fields are shown just fine. However, once I go to the admin on my web-app in production, both the HTMLField and TextField don't show any inputfields. If it would just be the TinyMCE HTMLField it would be less confusing, but having the common TextField bugged as well is weird. What do I miss? urls.py urlpatterns = [ [...] # tinymce url(r'^tinymce/', include('tinymce.urls')), ] settings.py TINYMCE_DEFAULT_CONFIG = { 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'width': 1200, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats | link image', 'menubar': True, 'statusbar': True, } forms.py from django import forms from tinymce import TinyMCE from django.contrib.admin.widgets import AdminDateWidget from .models import Post, Comment class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class PostForm(forms.ModelForm): # Add Tiny MCE Widget to Admin Interface content = forms.CharField( widget=TinyMCEWidget( attrs={'required': False, 'cols': 30, 'rows': 10} ) ), # Add DateTime Picker Widget to Admin Interface publish_date = forms.DateField(widget=AdminDateWidget()) class Meta: model = Post fields = ('title', 'overview', 'content', 'thumbnail', 'categories', 'publish_date') models.py from django.db import models from django.contrib.auth import get_user_model from tinymce.models import HTMLField # Post Model class Post(models.Model): title = models.CharField(max_length=28, blank=False) stock_name = models.CharField(max_length=35, blank=False) stock_website = models.CharField(max_length=60, blank=False) overview = models.TextField(max_length=140, blank=False) # doesn't show up in production content = HTMLField() # doesn't show up in production [...] This is how it looks like in Production: vs development having the very same code on each side: A: After a painful night, I finally got it run. Check the following: TinyMCE v4.x doesn't support the modern theme, however, it works in development for whatever reason So if you are on v4.x make sure to change the theme to silver respectively, reboot your production server and it should work just fine: TINYMCE_DEFAULT_CONFIG = { 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'width': 1200, 'selector': 'textarea', 'theme': 'silver', # Magic here [...] } Alternatively, if you want to keep the modern theme, you have to upgrade to v5.x If it then still doesn't work, it is probably due to missing static files path. Go ahead and ensure that you defined it correctly like so: TINYMCE_JS_URL = os.path.join(STATIC_URL, "tinymce/tinymce.min.js") TINYMCE_JS_ROOT = os.path.join(STATIC_URL, "tinymce/") The official docu suggests the defaults for the statics files which in my case didn't match. I still don't know why the common Django Textfield was affected as well, but it probably has something to do with the TinyMCE settings, weird.
[ "physics.stackexchange", "0000316460.txt" ]
Q: Volume of hypothetical closed universe Consider a physical universe with a beginning in time and space, with a finite amount of mass without the complications of dark energy that we have in the presently open curvature universe, so that the omegas (vacuum and mass) values create a closed universe, a universe with positive curvature. In this way, there will be a maximum (spatial) size that this universe could attain.I am not sure whether the concepts of (spatial) volume or radius would be applicable to this size, but if so, is there a way to calculate what it would be depending on the other variables? Which variables would be necessary -- the omegas, I presume, and what else? Is there a rough rule-of-thumb formula one could use? A: The radius of curvature is $$\rm r=\frac{c}{H \sqrt{\Omega_t-1}}$$ where $\rm H$ is the Hubble parameter and $\rm \Omega_t$ the sum of all energy contributions: $$\rm \Omega_t=\Omega_r+\Omega_m+\Omega_{\lambda}$$ so the circumference where a straight line closes in on itself is $$\rm U=2 \pi r$$ The volume of the 3dimensional curved space is the surface area of the corresponding 4D hypercube: $$\rm A=2 \pi^2 r^3$$ For the general equations for an arbitrary number of spatial dimensions see here.
[ "stackoverflow", "0000232271.txt" ]
Q: OpenGL textures with multiple display contexts I have an undefined number of display context and each will display a texture. When I call glGenTextures I get the same name returned across all display contexts. Will this work? Even though they have the same name will they still store and display different textures? If not what should do to get around this? A: Getting the same name from glGenTexture and having the same texture displayed is not the same thing. Texture names are just integers at a context's discretion, usually starting with 1, and incrementing with every glGenTexture, but not necessarily so. An implementation is not required to work like that (although most do). However, you could in theory also get any more or less "random" number, such for example an integer that increments for any kind of object (i.e. not just textures, but also buffers and shaders), or even a 32 bit pointer address in the driver's address space, or some other esotheric thing. There is no requirement that a name must be something specific. In legacy OpenGL, you could even make up your own names instead of using glGenTexture, but that is no longer legal now. I'm not sure what they thought when that was allowed, but anyway... :) The same number (name) in a different context will usually be a different texture, or possibly no texture at all. So, if you do see the same texture in different context with the same texture name, then you either have shared contexts, or the driver is buggy. Note that if you use wglCreateContextAttribsARB, the second parameter is the handle of an already existing context (or null). If you supply a context handle here, you will have shared contexts even without explicitly calling glShareLists. Maybe that is what happened by accident.
[ "stackoverflow", "0055156286.txt" ]
Q: crash while try store value using dependency inversion I want to implemented dependency inversion In app delegate in my app as my rootController is my UITabBarController but when I want to try it there is an error Fatal error: Unexpectedly found nil while unwrapping optional value This is my code in my appDelagate let exploreStore = ExploreStore() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let rootController = (window?.rootViewController as? UITabBarController)?.children.first as? ExploreViewController // Inject Data rootController?.exploreStore = exploreStore return true } This is my explore class class ExploreStore { fileprivate var allItems = [ExploreItem]() func fetch() { for data in loadData() { allItems.append(ExploreItem(dict: data)) } } func numberOfItem() -> Int { return allItems.count } func explore(at index: IndexPath) -> ExploreItem { return allItems[index.item] } fileprivate func loadData() -> [[String: AnyObject]] { guard let path = Bundle.main.path(forResource: "ExploreData", ofType: "plist"), let items = NSArray(contentsOfFile: path) else { return [[:]] } return items as! [[String: AnyObject]] } } This is my exlporeViewController var exploreStore: ExploreStore! override func viewDidLoad() { super.viewDidLoad() // This is where the error found nil exploreStore.fetch() } Actually the code work if I don't use dependency inversion, like my explore view controller not use force unwrapping like this var exploreStore = ExploreStore() but since I want gain knowledge and learn S.O.L.I.D principle using dependency inversion, I want to stick with this principle. A: If I understood your question correctly you want to initialise your class at AppDelegate class and then you want to pass it to your UITabBarController's first children and for that you need to make some modifications into your didFinishLaunchingWithOptions method like shown below: func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let vc = storyBoard.instantiateViewController(withIdentifier: "tabBar") self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = vc let myTabBar = self.window?.rootViewController as! UITabBarController let firstViewController = myTabBar.children.first as? FirstViewController firstViewController?.exploreStore = exploreStore self.window?.makeKeyAndVisible() return true } Here I have made some modification's because I am retrieving Info.plist from Bundle and your ExploreStore will look like: class ExploreStore { var allItems = [ExploreItem]() func fetch() { if let dataObjectFromPlist = loadData() { allItems.append(ExploreItem(dict: dataObjectFromPlist)) } } func numberOfItem() -> Int { return allItems.count } func explore(at index: IndexPath) -> ExploreItem { return allItems[index.item] } fileprivate func loadData() -> [String: AnyObject]? { var resourceFileDictionary: [String: AnyObject]? if let path = Bundle.main.path(forResource: "Info", ofType: "plist") { if let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject> { resourceFileDictionary = dict } } return resourceFileDictionary } } Then in my FirstViewController I can fetch the data from ExploreStore class with exploreStore.fetch() and my code for that UIViewController is class FirstViewController: UIViewController { var exploreStore: ExploreStore! override func viewDidLoad() { super.viewDidLoad() exploreStore.fetch() print(exploreStore.allItems[0].data) } } Here exploreStore.allItems[0].data will print my whole info.plist file. You can try it by your self with THIS demo project and check if that's the correct behaviour. EDIT You need to update didFinishLaunchingWithOptions method like: func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. setupDefaultColors() let exploreStoryBoard = UIStoryboard(name: "Explore", bundle:nil) let navigationController = exploreStoryBoard.instantiateViewController(withIdentifier: "ExploreViewControllerNavigation") as! UINavigationController if let exploreViewController = navigationController.children.first as? ExploreViewController { exploreViewController.store = ExploreStore() self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = exploreViewController self.window?.makeKeyAndVisible() } return true } And you also need to update ExploreStore class as shown below: class ExploreStore { var allItems = [ExploreItem]() func fetch() { if let dataObjectFromPlist = loadData() { allItems.append(ExploreItem(dict: dataObjectFromPlist)) } } func numberOfItem() -> Int { return allItems.count } func explore(at index: IndexPath) -> ExploreItem { return allItems[index.item] } fileprivate func loadData() -> [String: AnyObject]? { var resourceFileDictionary: [String: AnyObject]? if let path = Bundle.main.path(forResource: "ExploreData", ofType: "plist") { if let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject> { resourceFileDictionary = dict } } return resourceFileDictionary } } Because from plist you will get Dictionary<String, AnyObject> type object. And you will still not get data from plist file because its added into subfolder. So you need find correct path first for your plist. You also needs to assign respective identifiers to navigation controller and tab bar controller. Here is your demo project.
[ "stackoverflow", "0014611454.txt" ]
Q: How do i load scripts with a specified times Possible Duplicate: How to execute PHP code periodically in an automatic way I am trying to find a way in PHP to load specified script in a specified time, For example if the apache server can execute a specified script, Or mabye there is an option inside the php.ini so i can add files to load in a specified times. For example: I want to load the script example.php this file can be found inside the root directory at the location X/Y/example.php, What i want is that the Php engine/Apache Server will execute this script at 12:00, If anyone know a way doing so i will be very thankful, Thank you all and have a nice day. A: Use cron Cron is a daemon that executes scheduled commands. Cron is started automatically from /etc/init.d on entering multi-user runlevels. Cron searches its spool area (/var/spool/cron/crontabs) for crontab files (which are named after accounts in /etc/passwd); crontabs found are loaded into memory. Note that crontabs in this directory should not be accessed directly - the crontab command should be used to access and update them. For more info: croninfo.html Wiki
[ "math.stackexchange", "0001250278.txt" ]
Q: Is group of units of a polynomial ring only constant polynomial which is involved in R Let R be a integral domain(or maybe field) edit : Let R be a field. The group of units of R[x] is $$ a_n x^n + a_{n-1} x^{n-1} + a_{n-2} x^{n-2} + \cdots+ a_2 x^2 + a_1 x + a_0 $$(or infinity) such that $$ a_0 ∈ R^* $$ Some say, the unit group of R[x] is the unit group of R. What I'm confused is that the second sentence seems to show its unit is constant polynomial only which is involved in unit group of R and first one is all the polynomial but the constant is unit group of R. Which one is correct and what I missed the point? Thanks. A: The following is true: $$R^\times=(R[X])^\times$$ Proof: Let $a\in R^\times\subseteq R$. Then the inverse of $a\in R$ is just the inverse of $a$ in $R[X]$. Conversely if $f\in (R[X])^\times$ with the inverse $f^{-1}$ then $$0=deg(1)=deg(f\cdot f^{-1})=deg(f)+deg(f^{-1})\tag{1}$$ Hence $deg(f)=deg(f^{-1})=0$. Thus $f$ and $f^{-1}$ are invertible elements of $R$ Note: The third equality holds if and only if $R$ is an integral domain.
[ "stackoverflow", "0003762329.txt" ]
Q: Refresh the parent window from the child window in javascript I have looked for awhile and cannot find an answer that fits my needs. I have a page that pops a window (window.open), logs the user in (creates a cookie, set session) then redirects to another page. While the modal is redirecting, I would like to refresh the parent page, so all the good stuff that I just did will be recognized by the parent. I have tried window.opener and stuff like that. Can someone help me out a little? Thanks A: window.opener in the popup will refer to the window object of the opening window, so of course you should be able to call window.opener.location.reload();. Provided you don't run afoul of the Same Origin Policy, the popup window can call scripts and manipulate properties on the parent window object just like code in the parent can. Here's a live example demonstrating the child calling back to a function on the parent, and also manipulating the parent directly. The full code for this is quoted below. But that example didn't do exactly what you said, so I've done this one as well, which has the child refreshing the parent page via window.opener.location.reload(). Parent code of first live example: <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>Parent Window</title> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <style> article, aside, figure, footer, header, hgroup, menu, nav, section { display: block; } </style> </head> <body> <input type='button' id='btnOpen' value='Open Window'> <div id='display'></div> </body> <script type='text/javascript'> (function() { var btnOpen = document.getElementById('btnOpen'); btnOpen.onclick = btnOpenClick; function btnOpenClick() { window.open('http://jsbin.com/ehupo4/2'); } // Make the callback function available on our // `window` object. I'm doing this explicitly // here because I prefer to export any globals // I'm going to create explicitly, but if you // just declare a function in a script block // and *not* inside another function, that will // automatically become a property of `window` window.callback = childCallback; function childCallback() { document.getElementById('display').innerHTML = 'Got callback from child window at ' + new Date(); } })(); </script> </html>​ (You don't have to use a scoping function as I did above, but it's useful to keep your globals contained.) Child code of first live example: <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>Child Window</title> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <style> article, aside, figure, footer, header, hgroup, menu, nav, section { display: block; } </style> </head> <body> <p>I'm the child window</p> </body> <script type='text/javascript'> if (window.opener) { // Call the provided callback window.opener.callback(); // Do something directly var p = window.opener.document.createElement('p'); p.innerHTML = "I was added by the child directly."; window.opener.document.body.appendChild(p); } </script> </html>​
[ "stackoverflow", "0034248895.txt" ]
Q: how to stop frame animation when mediaplayer completes playback? I have a frame animation (Animation Drawable) that is supposed to run in sync with an audio (MediaPlayer). I pause the audio (mediaplayer.pause()) and stop the animation (as I am not able to find a way to pause it) when I pause my Activity class (e.g. When I press the home button of my device). when I resume my Activity, I call mediaplayer.start() and it starts where it was paused. Then, I call frameAnimation.start and it again starts from the beginning and goes on to complete the cycle even after the mediaplayer has completed playback. As a result, the frameAnimation and mediaPlayer get out of sync. What do I do? I am new to android programming. Please help. My frame animation xml is similar to android:id="@+id/selected" android:oneshot="true"> <item android:drawable="@drawable/bird1" android:duration="750"/> <item android:drawable="@drawable/bird2" android:duration="750"/> And my onResume() is protected void onResume() { mediaplayer.start(); frameAnimation.start(); If(!mediaplayer.isPlaying()&&frameAnimation.isRunnng()){ frameAnimation.stop(); } Clearly, the if statement never gets executed as the mediaplayer is playing then. What else can I do? I am at a total loss. A: You should set a MediaPlayer.OnCompletionListener with setOnCompletionListener(): then you'll get a callback when the MediaPlayer finishes and you can stop your animation.
[ "superuser", "0000376028.txt" ]
Q: Lenvo B450 won't boot on battery only? We bought a Lenovo B450 laptop almost a year ago. It comes with a NVIDIA GEFORCE with CUDA graphics and so the battery life is terrible. It will only last 1:30 hours max. We try to run it on battery as much as possible but because the battery life is short sometimes we can't notice that the battery is so low until the computer blacks out. Because of the short battery life, the laptop is always plugged on AC power. One night the computer froze. Because it was already late, I just reset the laptop my pressing the power button for 10 seconds. The laptop shut off but I did not bother restarting it. The next morning, the laptop won't turn on on battery only. It will only turn on on AC power. The computer instantly shuts down(improperly) once the adapter is removed. But the battery was at 100% then. Now it is slowly losing charge (currently at 74%). The battery indicator says, "Plugged in, not charging". I want to bring the laptop to school but I can't because it won't be portable at all. Just to summarize it all: 1) The laptop suffered some blackouts already. 2) The laptop was on AC power most of the time. 3) When the computer froze, it was reset (hard shutdown). 4) The laptop won't boot with battery only since then. 5) The laptop will shutdown instantly when AC adapter is removed. 6) The battery won't charge and is gradually losing charge. ======================= UPDATE ============================= We got the battery replaced. Unfortunately, it delivers only 2 hours max of power. A: We have a Dell Inspiron which did the same thing. Instead of the battery only holding less and less times until nothing, it stopped working overnight. Went from maybe 15-30 minutes to 0. We now have to use the power cord and turn the computer off all the time (no more sleep for transportation). As you said We try to run it on battery as much as possible I guess it's just considered dead by the laptop after a year of use.
[ "stackoverflow", "0062714548.txt" ]
Q: how to ignore duplicates when I insert many records at once? I want to insert into a many to many table, the ID1 and ID2, where ID1 is always the same value and I have many ID2. I can use this query: insert into MyTable (ID1, ID2) select 1, ID from AnotherTable where ID in (1, 2, 3); But if ID1 is related with some of the ID2, I get an error because of unique constraint. So i would like to know how it would be the way to ignore the duplicate values and insert the rest of the rows. Thanks. A: You can use the EXCEPT operator for this: INSERT INTO MyTable (ID1, ID2) SELECT 1, ID FROM AnotherTable WHERE ID in (1, 2, 3) EXCEPT SELECT ID1,ID2 FROM MyTable ;
[ "stackoverflow", "0051750917.txt" ]
Q: VBA extracting only select info between tags I'm trying to check if the html tag: <nobr>Target</nobr> exists on the page, and if it does, search for the text between the html tag: <div style='width: 555px; -ms-overflow-x: auto; -ms-overflow-y: hidden;> ... </div> The text between the div tags look messy like: ABC [HSA: <a href="...">...</a> ] [KO: <a href="...">...</a> ] <br /> GHI-JK [JKI: ... And I want to get and print to my spreadsheet however many items there are, but I only want the item name (in the above example, there're 2 items - ABC and GHI-JK). Of course my code below doesn't work., I don't think I'm using queryselector correctly and I'm also not sure how to only grab the item names, instead of the entirety between the tags If IE.document.querySelector("nobr").innerHTML = "Target" Then If IE.document.querySelector("div[style^='width: 555px; -ms-overflow-x: auto; -ms-overflow-y: hidden;']") <> 0 Then Cells(1, 15).Value = IE.document.querySelector("div[style^='width: 555px; -ms-overflow-x: auto; -ms-overflow-y: hidden;']").innerText End If End If A: CSS selector: You can use a CSS selector combination to target the element of interest. The data is in a div, that is inside an element with class td51. You can write a CSS selector combination to target this pattern of: .td51 div This says elements with div tag whose parent is td51 class. Where "." is a class selector. The element space element pattern is known as a descendant combinator. CSS query results: This pattern matches multiple elements and you want the item as index 6. As multiple items are retrieved you use the querySelectorAll to apply the CSS combinator and retrieve a nodeList you index into to get the item of interest. As you only want part of the information retrieved you can use split to "slice" out the required info. Note that Kit is not Kit alone but is Kit (CD117). XMLHTTPRequest XHR: Option Explicit Public Sub GetInfo() Dim sResponse As String, i As Long, html As New HTMLDocument, arr() As String, ele As Object With CreateObject("MSXML2.XMLHTTP") .Open "GET", "https://www.kegg.jp/dbget-bin/www_bget?dr:D01441", False .send sResponse = StrConv(.responseBody, vbUnicode) End With With html .body.innerHTML = sResponse On Error Resume Next Set ele = .querySelectorAll(".td51 div")(6) On Error GoTo 0 If ele Is Nothing Then Exit Sub arr = Split(ele.innerText, Chr$(10)) End With For i = LBound(arr) To UBound(arr) Debug.Print Split(arr(i), "[")(0) Next i End Sub References (VBE > Tools > References): Microsoft HTML Object Library Internet Explorer: Option Explicit Public Sub GetInfo() Dim ie As New InternetExplorer, html As HTMLDocument, arr() As String, ele As Object, i As Long With ie .Visible = True .navigate "https://www.kegg.jp/dbget-bin/www_bget?dr:D01441" While .Busy Or .readyState < 4: DoEvents: Wend Set html = .document On Error Resume Next Set ele = html.querySelectorAll(".td51 div")(6) On Error GoTo 0 If ele Is Nothing Then Exit Sub arr = Split(ele.innerText, Chr$(10)) For i = LBound(arr) To UBound(arr) Debug.Print Split(arr(i), "[")(0) Next i '.Quit '<== Remember to quit application End With End Sub References: Microsoft Internet Controls Microsoft HTML Object Library EDIT: This has become rather long but following our debugging to merge with your other code: Option Explicit Public Sub ht() Dim ie As Object, ele As Object, i As Long Dim sourceSheet As Worksheet, lastRow As Long, rawString() As String, rowIndex As Long Dim arrayOfValues() As Variant, html As HTMLDocument, arr() As String Const URL As String = "https://www.genome.jp/kegg/drug/" Set sourceSheet = Worksheets("Sheet1") lastRow = sourceSheet.Range("A30000").End(xlUp).Row arrayOfValues = sourceSheet.Range("A1:A" & lastRow) Set ie = CreateObject("InternetExplorer.Application") With ie .Visible = True For rowIndex = 1 To lastRow .navigate URL Do While .readyState <> 4 Or .Busy: DoEvents: Loop rawString = VBA.Strings.Split(VBA.Strings.LCase$(arrayOfValues(rowIndex, 1)), ": ", -1, vbBinaryCompare) 'MsgBox rawString(1) .document.querySelector("input[name=q]").Value = rawString(1) .document.querySelector("input[value=Go]").Click Do While .readyState <> 4 Or .Busy: DoEvents: Loop Dim ele2 As Object On Error Resume Next Set ele2 = .document.querySelector("a[href^='/dbget-bin/www_bget?dr:']") On Error GoTo 0 If ele2 Is Nothing Then GoTo NextLink ele2.Click Do While .readyState <> 4 Or .Busy: DoEvents: Loop Set html = .document On Error Resume Next Set ele = html.querySelectorAll(".td51 div")(6) On Error GoTo 0 If Not ele Is Nothing Then arr = Split(ele.innerText, Chr$(10)) For i = LBound(arr) To UBound(arr) Debug.Print Split(arr(i), "[")(0) Next i End If NextLink: Next rowIndex .Quit End With End Sub
[ "stackoverflow", "0029493624.txt" ]
Q: Can't display board whereas the ID is same when I use chessboard.js I want to display chess from chessboardjs.com. But I can't whereas I follow documentation. And whereas the ID is same. <html> <head> <!-- UTF-8 (U from Universal Character Set + Transformation Formatβ€”8-bit[1]) is a character encoding capable of encoding all possible characters --> <meta charset="UTF-8"> <link rel="stylesheet" href="css/chessboard-0.2.0.css"/> <script type="text/javascript" src="js/chessboard-0.2.0.js" > </script> <script type="text/javascript"> var board1 = new ChessBoard('board1', 'start'); </script> </head> <body> <div id="board1" style="width: 400px"></div> </body> The id is same. It is 'board1'. I follow the rules from the documentation... link But, I get error. The error is chessboard error 1002: element with id "board1" does not exist in the DOM. Then, I read documentation about error 1002. It says.. ChessBoard could not find your element with document.getElementById. Please note that if you pass a string as the first argument to the ChessBoard() constructor it should be the value of a DOM id, not a CSS selector (ie: "board", not "#board"). link A: You need jquery to make this work. <html> <head> <!-- UTF-8 (U from Universal Character Set + Transformation Formatβ€”8-bit[1]) is a character encoding capable of encoding all possible characters --> <meta charset="UTF-8"> <link rel="stylesheet" href="css/chessboard-0.3.0.css"/> <script type="text/javascript" src="js/chessboard-0.3.0.js" > </script> <script src="https://code.jquery.com/jquery-1.10.1.js"></script> </head> <body > <div id="board1" style="width: 400px"></div> </body> <script type="text/javascript"> var init = function() { //--- start example JS --- var board = new ChessBoard('board1'); //--- end example JS --- }; // end init() $(document).ready(init); </script> </html>
[ "stackoverflow", "0023461609.txt" ]
Q: PHP's SimpleXML doesn't keep order between different element types As far as I can tell, when you have multiple types of elements at the same level in an XML document tree, PHP's SimpleXML, including SimpleXMLElement and SimpleXMLIterator both don't keep the order of the elements as they relate to each other, only within each element. For example, consider the following structure: <catalog> <book> <title>Harry Potter and the Chamber of Secrets</title> <author>J.K. Rowling</author> </book> <book> <title>Great Expectations</title> <author>Charles Dickens</author> </book> </catalog> If I had this structure and used either SimpleXMLIterator or SimpleXMLElement to parse it, I would end up with an array that looked something like this: Array ( [book] => Array ( [0] => Array ( [title] => Array ( [0] => Harry Potter and the Chamber of Secrets ) [author] => Array ( [0] => J.K. Rowling ) ) [1] => Array ( [title] => Array ( [0] => Great Expectations ) [author] => Array ( [0] => Charles Dickens ) ) ) ) This would be fine, since I only have book elements, and it keeps the order properly within those elements. However, say I add movie elements, too: <catalog> <book> <title>Harry Potter and the Chamber of Secrets</title> <author>J.K. Rowling</author> </book> <movie> <title>The Dark Knight</title> <director>Christopher Nolan</director> </movie> <book> <title>Great Expectations</title> <author>Charles Dickens</author> </book> <movie> <title>Avatar</title> <director>Christopher Nolan</director> </movie> </catalog> Parsing with SimpleXMLIterator or SimpleXMLElement would result in the following array: Array ( [book] => Array ( [0] => Array ( [title] => Array ( [0] => Harry Potter and the Chamber of Secrets ) [author] => Array ( [0] => J.K. Rowling ) ) [1] => Array ( [title] => Array ( [0] => Great Expectations ) [author] => Array ( [0] => Charles Dickens ) ) ) [movie] => Array ( [0] => Array ( [title] => Array ( [0] => The Dark Knight ) [director] => Array ( [0] => Christopher Nolan ) ) [1] => Array ( [title] => Array ( [0] => Avatar ) [director] => Array ( [0] => James Cameron ) ) ) ) Because it represents the data this way, it seems that I have no way to tell that the order of the books and movies in the XML file was actually book, movie, book, movie. It just separates them into two categories (although it keeps the order within each category). Does anyone know of a workaround, or a different XML parser that doesn't have this behavior? A: "If I ... used either SimpleXMLIterator or SimpleXMLElement to parse it, I would end up with an array" - no you wouldn't, you would end up with an object, which happens to behave like an array in certain ways. The output of a recursive dump of that object is not the same as the result of iterating over it. In particular, running foreach( $some_node->children() as $child_node ) will give you all the children of a node in the order they appear in the document, regardless of name, as shown in this live code demo. Code: $xml = <<<EOF <catalog> <book> <title>Harry Potter and the Chamber of Secrets</title> <author>J.K. Rowling</author> </book> <movie> <title>The Dark Knight</title> <director>Christopher Nolan</director> </movie> <book> <title>Great Expectations</title> <author>Charles Dickens</author> </book> <movie> <title>Avatar</title> <director>Christopher Nolan</director> </movie> </catalog> EOF; $sx = simplexml_load_string($xml); foreach ( $sx->children() as $node ) { echo $node->getName(), '<br />'; } Output: book movie book movie
[ "es.stackoverflow", "0000108098.txt" ]
Q: Como puedo vender productos desde un sitio web? Que tal, soy nuevo en programacion web y tengo un proyecto de un sitio web de ventas, que temas debo investigar? A: Puedes empezar usando un CMS (Content Management System) como Prestashop. Estos CMS te permiten tener lista tu tienda en cuestiΓ³n de dΓ­as y a medida que vayas teniendo exito, puedes desarrollar o comprar modulos que se adapten a tus necesidades especΓ­ficas.
[ "mathoverflow", "0000296983.txt" ]
Q: Lifting a representation from a discrete subgroup Let $\pi_0$ be an irreducible representation of a discrete subgroup $\Gamma$ of the reductive group $G$. My question in general is What can be said of representations $\pi$ of $G$ extending $\pi_0$, in the sense that $\pi$ acts on $\Gamma$ as $\pi_0$? I would like to know technical possibilities in this direction, even assuming freely further properties on $\pi_0$. What if in particular if $\pi_0$ is finite dimensional? The base case $\Gamma = SL(2, \mathbb{Z})$ and $G=SL(2, \mathbb{Q})$ is already of interest for me. A: If $\Gamma$ is a lattice in a connected semisimple $\mathbb{R}$-algebraic group $G$ without compact factors, then the Borel density theorem says that $\Gamma$ is Zariski dense in $G$. This implies that there can be at most one extension of a representation of $\Gamma$ to a rational representation of $G$. Of course, extensions need not exist. For finite-dimensional representations, however, you can often get information using the Margulis superrigidity theorem. This says that if $\Gamma$ is a lattice in a semisimple Lie group $G$ satisfying some technical assumptions and if $V$ is a finite-dimensional representation of $\Gamma$, then there exists a finite-index subgroup $\Gamma'$ of $\Gamma$ such that the action of $\Gamma'$ on $V$ extends to a rational representation of $G$. Passing to a finite-index subgroup is necessary here. For instance, if the action of $\Gamma$ on $V$ factors through a finite group, then you first have to pass to a subgroup $\Gamma'$ that acts trivially on $V$ (and the extension to $G$ is then the trivial action). The most important technical assumption in the superrigidity theorem is that $G$ is of higher rank. It applies to $\text{SL}(n,\mathbb{Z})$ in $\text{SL}(n,\mathbb{R})$ for $n \geq 3$, but not for $n=2$.
[ "stackoverflow", "0006654556.txt" ]
Q: MVC controller action is called twice On IIS 7 server with my ASP.NET MVC 3 application, I am encountering the following problem: when I have an action taking rather long time to complete (like 30 seconds), it will get fired for the second time after cca 15-20 seconds from the first request. I can see in Fiddler (HTTP sniffer) that the browser is not the culprit - it only sends the request once. However, in IIS log files, I can see the request twice. However, in IIS logs, both requests have the same timestamp (not in my own log files - there the two requests are separated by those 15-20 seconds). Originally, the action was processing an uploaded file, storing it in the database etc..However, even after I changed the action to just call Thread.Sleep(30000), it is still called twice. It is not caused by some malfunctioning JavaScript or missing-image references which seem to be the common reasons for this behavior as I read through similar problems here on StackOverflow. I cannot replicate this on the development ASP.NET server, only on the IIS server and just on one of two I use. This is the HTML form used to trigger that action @model TMAppServer.Abstract.DataTransferObject.ProjectOverviewData @{ Layout = null; } <!DOCTYPE html> <html> <head> <title>UploadTestForm</title> </head> <body> <div> @using (Html.BeginForm("UploadFileNew", "Manager", new { targetLanguage = "CS" }, FormMethod.Post, new { enctype = "multipart/form-data" })) { <input id="files" type="file" name="files" /><text><input type="submit" id="uploadFile" value="Upload the document..." /><input type="hidden" name="projectId" id="projectId" value="@(Model.Job.Name)" /> } </div> </body> </html> This is the controller action: public ActionResult UploadFileNew(string projectId, string targetLanguage, IList<HttpPostedFileBase> files) { foreach (var file in files) { if (null == file) continue; Thread.Sleep(30000); } return RedirectToAction("GetProjectOverview", new { projectId = projectId }); } Thank you for any suggestions. EDIT: Now I found out that this only happens when I access the server via its domain name from the same network (like server.domain.com), it does NOT happen when accessing the server via its IP address or from an outside network. This is what I get in the IIS logs: 2011-07-21 01:23:31 W3SVC2 WIN-AD50B4LJ2SU 192.168.1.48 POST /manager/upload-file projectId=3366 80 - 192.168.1.1 HTTP/1.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+rv:5.0.1)+Gecko/20100101+Firefox/5.0.1 .ASPXAUTH=cookie http://tm.web.com/manager/projects/3366/overview tm.web.com 302 0 0 440 6232309 578 2011-07-21 01:23:31 W3SVC2 WIN-AD50B4LJ2SU 192.168.1.48 GET /manager/projects/3366/overview - 80 - 192.168.1.1 HTTP/1.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+rv:5.0.1)+Gecko/20100101+Firefox/5.0.1 .ASPXAUTH=cookie http://tm.web.com/manager/projects/3366/overview tm.web.com 200 0 0 30125 769 93 2011-07-21 01:23:31 W3SVC2 WIN-AD50B4LJ2SU 192.168.1.48 POST /manager/upload-file projectId=3366 80 - 192.168.1.1 HTTP/1.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64;+rv:5.0.1)+Gecko/20100101+Firefox/5.0.1 .ASPXAUTH=cookie http://tm.web.com/manager/projects/3366/overview tm.web.com 302 0 64 0 6232309 39406 And these are my routes in Global.asax.cs public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute(null, "manager/upload-file", new { controller = "Manager", action = "UploadFile" }, new { httpMethod = new HttpMethodConstraint("POST") } ); routes.MapRoute(null, "manager/projects/{projectId}/overview", new { controller = "Manager", action = "GetProjectOverview" }, new { httpMethod = new HttpMethodConstraint("GET") } ); routes.MapRoute(null, "manager/{action}", new { controller = "Manager", action = "Main" }, new { httpMethod = new HttpMethodConstraint("GET") } ); routes.MapRoute("Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Manager", action = "ListProjects", id = UrlParameter.Optional } // Parameter defaults ); } A: From the logs you posted it looks like your web server is returning HTTP302 which is 'Moved Temporarily' or as IIS implements it 'Object Moved' status. It sounds like a network configuration problem. Does it happen to every action or only that one?
[ "stackoverflow", "0009562011.txt" ]
Q: Set dict value to the number of times it's inserted python? I'm dealing with a list of games and wanted to find out which player won the most games using python. I figured a multiset (C++) type data structure would make it easy as each key is unique but it keeps count of how many times an item was pushed in the dict. I started implementing it myself after I failed to find anything talking about them in searches. Is there an easier way where you can set a dict value to be the count of how many times the key is added instead of using a list like I did? ## logFiles is just a list of json files for each game. winnerList = [] winnerDict = {} if len(logFiles): for logFile in logFiles: jsonData = json.load(open("logs/" + logFile, 'r')) winnerList.append(str(jsonData[6]['winner'])) for winner in winnerList: winnerDict[winner] = winnerList.count(winner) A: You're looking for collections.Counter: import collections,json,os.path winners = collections.Counter() for logFile in logFiles: with open(os.path.join("logs", logFile), 'r') as jsonf: jsonData = json.load(jsonf) winner = str(jsonData[6]['winner']) winners[winner] += 1 winnerList = list(winners.keys()) bestPlayers = winners.most_common()
[ "stackoverflow", "0037519097.txt" ]
Q: Bind Id of checkboxes to an array I have a view model containg an object that is used to display some checkboxes: components = { "ComponentInfos": [ { "Id": "1abb0ee5-7e44-4e45-92da-150079066e99", "FriendlyName": "Component1", "LimitInfos": [ { "Id": "4b7cd37a-2378-4f4f-921b-e0375d60d19c", "FriendlyName": "Component1 Full", }, { "Id": "ff9ebe78-fbe4-4a26-a3df-6ec8e52cd0f2", "FriendlyName": "Component1 Light", } ] } I am able to create the checkboxes with FriendlyName as label: <h4>{{l.FriendlyName}}</h4> <div> <div ng-repeat="limitinfo in l.LimitInfos"> <label> <input type="checkbox" ng-model="vm.settings.ComponentInfos[limitinfo.Id]" value="{{limitinfo.Id}}"/> {{limitinfo.FriendlyName}} </label> </div> </div> I want to store the selected LimitInfo.Id in an array for each selected checkbox. I was able to store them in an object like this: settings = { "ComponentInfos" : {} }; Result example: "2e80bedb-4a18-4cc4-bdfd-837ffa130947": true, "add1edf8-4f11-4178-9c78-d591a6f590e3": true What I do need is to store the LimitInfo.Idin an array like this: settings = { "ComponentInfos" : [] }; Expected result: "2e80bedb-4a18-4cc4-bdfd-837ffa130947", "add1edf8-4f11-4178-9c78-d591a6f590e3" I uploaded my code to Plunker. A: One line solution You can do the following in vanilla JS (ES5 and above, so modern browsers) var data = { "a": true, "b": false, "c": true, "d": false, "e": true, "f": true } var arr = Object.keys(data).filter( key => !!data[key] ); // ['a', 'c', 'e', 'f'] A: you can use a ng-click method on the checkbox with a custom controller method to push to that array. <input type="checkbox" ng-model="vm.settings.ComponentInfos[limitinfo.Id]" value="{{limitinfo.Id}}" ng-click="toggleSelection(limitinfo.ImpliedLimits)"/> $scope.toggleSelection = function toggleSelection(item) { var idx = $scope.vm.settings.ComponentInfos.indexOf(item); if (idx > -1) { $scope.vm.settings.ComponentInfos.splice(idx, 1); } else { $scope.vm.settings.ComponentInfos.push(item[0]); } }; see this plnkr. see this answer A: Demo by directive: var app = angular.module('plunker', []); app.directive('myCheckbox',function(){ return { restrict:'EA', template:'<label>' +'<input type="checkbox" ng-model="model" ng-change="toggleModel()" /> {{label}}' +'</label>', replace: true, scope:{ label:'@', value:'@', output:'=' }, link:function(scope,elements,attrs){ //init checked status scope.model=scope.output.indexOf(scope.value) > -1; //binding click replace watch model scope.toggleModel = function(){ if(scope.model){ scope.output.push(scope.value); return false; } scope.output.splice(scope.output.indexOf(scope.value),1); } } } }); function MyViewModel() { this.components = { "ComponentInfos": [ { "Id": "1abb0ee5-7e44-4e45-92da-150079066e99", "FriendlyName": "Component1", "LimitInfos": [ { "Id": "4b7cd37a-2378-4f4f-921b-e0375d60d19c", "FriendlyName": "Component1 Full", "ImpliedLimits": [ "ff9ebe78-fbe4-4a26-a3df-6ec8e52cd0f2" ] }, { "Id": "ff9ebe78-fbe4-4a26-a3df-6ec8e52cd0f2", "FriendlyName": "Component1 Light", "ImpliedLimits": [ "4f74abce-5da5-4740-bf89-dc47dafe6c5f" ] }, { "Id": "4f74abce-5da5-4740-bf89-dc47dafe6c5f", "FriendlyName": "Component2 User", "ImpliedLimits": [] } ] }, { "Id": "ad95e191-26ee-447a-866a-920695bb3ab6", "FriendlyName": "Component2", "LimitInfos": [ { "Id": "8d13765a-978e-4d12-a1aa-24a1dda2149b", "FriendlyName": "Component2 Full", "ImpliedLimits": [ "4f74abce-5da5-4740-bf89-dc47dafe6c5f" ] }, { "Id": "2e80bedb-4a18-4cc4-bdfd-837ffa130947", "FriendlyName": "Component2 Light", "ImpliedLimits": [ "4f74abce-5da5-4740-bf89-dc47dafe6c5f" ] }, { "Id": "add1edf8-4f11-4178-9c78-d591a6f590e3", "FriendlyName": "Component2 Viewer", "ImpliedLimits": [ "4f74abce-5da5-4740-bf89-dc47dafe6c5f" ] } ] } ] }; this.settings = { "ComponentInfos" : ["4b7cd37a-2378-4f4f-921b-e0375d60d19c","2e80bedb-4a18-4cc4-bdfd-837ffa130947"] }; } app.controller('MainCtrl', function($scope) { $scope.vm = new MyViewModel(); }); <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <script>document.write('<base href="' + document.location + '" />');</script> <link rel="stylesheet" href="style.css" /> <script data-require="[email protected]" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script> <script src="app.js"></script> </head> <body ng-controller="MainCtrl"> <div ng-repeat="l in vm.components.ComponentInfos"> <h4>{{l.FriendlyName}}</h4> <div> <div ng-repeat="limitinfo in l.LimitInfos"> <my-checkbox label="{{limitinfo.FriendlyName}}" value="{{limitinfo.Id}}" output="vm.settings.ComponentInfos"></my-checkbox> </div> </div> </div> <hr> <pre> {{vm.settings | json }} </pre> </body> </html>
[ "gaming.stackexchange", "0000197934.txt" ]
Q: Will leaving corpses lying around upset my prisoners? I see questions/information online about how to get rid of corpses but I'm not sure what the consequences to having them lying around are. I know that I can use a morgue to store them and that they will eventually be taken away in a hearse. However, I've always just left them lying around. This doesn't seem to have any obvious consequences. Do they upset prisoners or staff (e.g. increasing the danger level beyond what death normally does)? Make them sick? Slow down pathing? Is this something that's not implemented yet or is leaving dead bodies all over the place meant to be completely fine? The wiki's pages for Death and Morgue don't shed any light on this. All I'm finding is the how of getting rid of corpses/glitches related to it but not why it matters in the first place. All I've seen that's related is that apparently prisoners can loot guard corpses for keys, but there's no obvious consequences for prisoner corpses which are what I tend to end up with. So why not just leave them in the corridors? A: I don't believe there's currently any effect on the mood or efficiency of your staff or prisoners. However, there's still something to keep in mind: dead (and unconscious) characters can be looted. If a staff member dies, then prompt movement to a morgue can prevent prisoners from looting Staff Keys off the corpse. This is even more important when the corpse is a guard, since Jail Keys and weapons can be taken. To a much less severe degree, storage of prisoner corpses in morgues will prevent access to any contraband they may have been carrying. If you do build a morgue, you will have to ensure your morgue is properly protected to prevent prisoners from walking in and just taking the items from dead bodies.
[ "stackoverflow", "0020616193.txt" ]
Q: trigger can not be created on system table in phpmyadmin My query is correct as per my knowledge, but gives error: CREATE TRIGGER `invite` AFTER INSERT ON `invite_page` FOR EACH ROW BEGIN Insert into userpost(userid,url,title,preview,sentiment,time) values(NEW.userid,NEW.url,NEW.title,NEW.preview,NEW.sentiment,NEW.time); Insert into urlcontent(userid,url,title,preview,sentiment,time) values(NEW.userid,NEW.url,NEW.title,NEW.preview,NEW.sentiment,NEW.time); END the error is: #1465 - Triggers can not be created on system tables A: As long as I'm concerned, you can't create triggers on system tables. See mysql: Cant we create triggers on system tables? for more information.
[ "stackoverflow", "0045200993.txt" ]
Q: Netbeans disable horizontal scroll Tried the other solutions and can't find the option to line wrap. i never write code with lines this much long and am getting frustrated of that horizontal scroll whenever i try to scroll down and my fingers move even a little bit diagonally. gif addressing the problem : http://g.recordit.co/dhuj8y0JZP.gif A: Restart your IDE. You are using a Mac and have probably not closed it for days. This happens when you use the zoom with alt + scroll down
[ "parenting.stackexchange", "0000006172.txt" ]
Q: 7 month old will no longer play on her stomach My 7 month old is capable of rolling both front-to-back and back-to-front. She can also sit fairly well when place in the sitting position, although she cannot get to that position on her own. Looking forward to future gross motor skills milestones I would like to provide her the opportunity to acheive what she needs to acheive. When I read about crawling, in all its variants, I read that encouraging tummy time is essential. My daughter simply won't do tummy time. I place her on her stomach with an enticing toy and she grabs the toy and rolls over to her back. After spending a day rolling onto her stomach she has simply stopped. She has no desire to be on her stomach. She'll happily play on her back, side, or seated, however. I do place toys out in front of her when she is seated or to her side just out of reach when she is lying down to try and encourage her to reach. When seated she will reach; when lying she usually won't. I don't want to push my daughter, but I do want to provide her an environment where she can develop valuable skills. What should I do for her play to help her move forward with being able to move to a sitting position on her own, crawling (or creeping, scooting, slithering, etc.), pulling up, standing, cruising, and walking? A: If your daughter doesn't want to stay on her tummy then she's not going to, it's simple as that and there's not a thing you can do about it. Once babies learn to roll around it's up to them. All you can do is make it a safe environment with lots of good things to play with then let them get on with it. As for why she doesn't want to be on her tummy who knows? She may have a stomach ache, or maybe she's sore from spending lots of time on her front before. Maybe she wants to have more eye contact with you, or maybe she just doesn't feel like it. Try not to obsess on it, just let her develop in her own time.
[ "math.stackexchange", "0001866339.txt" ]
Q: How to prove that there are only two kinds of 1-dim manifolds without boundary I just know a conclusion that all 1-dim manifolds without boundary is homomorphism to $S^1$ or $\mathbb{R}$ , but I don't know how to prove it . Why is so ? A: Here a sketch of the proof. Suppose that $M$ is a smooth 1-dimensional manifold. Let's first suppose that $M$ is orientable. This means that we can find a global top-dimensional never-vanishing differential form over $M$, i.e. (up to fixing a Riemannian metric over $M$) a never-vanishing global vector field $X \in \Gamma(TM)$. It is easy to check (the details are up to you) that a flow line $\gamma: \mathbb{R} \to M$ of $X$ gives either a diffeomorphism $M \simeq \mathbb{R}$ , or a periodic map (with say period $T$) that descends to a diffeomorphism $M \simeq \mathbb{R}/T \mathbb{Z} \simeq S^1$. Now we have just to rule out the evenience that there are non-orientable 1-dimensional manifolds. In order to do this suppose that $M$ is non-orientable and consider its universal cover $\widetilde{M}$. This is an orientable 1-diemnsional manifold (in fact, it is simply connected), and you can check (using what we proved so far) that $\widetilde{M}\simeq \mathbb{R}$. Now, if $M$ is non-orientable, there is $\gamma \in \pi_1(M)$ acting on the universal covering $\widetilde{M}\simeq \mathbb{R}$ as an orientation-reversing diffeomorphism. In order to obtain the contradiction, notice (this is elementary analysis) that an orientation reversing diffeomorphism of the real line always has a fixed point.
[ "stackoverflow", "0020208392.txt" ]
Q: how to distingguish "disable" or "enable" of pre-installed system apps on Android 4.0 or higher? As we know, from Android 4.0 users can disable/enable pre-installed system apps. Intent.ACTION_PACKAGE_CHANGED can be received by register broadcast receiver, but I can NOT distingguish app disable or enable. My question is how to distingguish them ? A: Some sample code: public void checkEnable() { PackageManager pm = getPackageManager(); ComponentName cn = new ComponentName("FULL PACKAGENAME", "Full ComponentName(activity/service)"); int ret = pm.getComponentEnabledSetting (cn); if(ret != PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { Log.w(TAG, "We are disabled by someone..."); } else { } }
[ "stackoverflow", "0029521938.txt" ]
Q: how to print a 2D array from class if the we print the object the of the this class in main class I have a class Employee which has a method that returns a 2D array with some employee information. I have another class TestEmployee in the same package where I create an object test of the class Employee and then print this object. Employee test = new Employee(); System.out.println(test); Now this test object should print the array I created in Employee. I am not able to write the code to do that. Can someone please help me with this question? Thanks A: I don't know why someone would downvote this question. Employee is an Object type, and you can't print Objects and expect good output because it prints out its hash code (thanks Obicere). Well, unless you override the toString() method. If you do, and you do it well, you can do: System.out.println(test.toString()); I'm assuming you want to print out the information contained in the 2D array. If that's so, then you'd want to parse all that information into a single String and have your toString() method return that. Cheers, Justin
[ "stackoverflow", "0004724209.txt" ]
Q: Which doctype do I need? I'm having an issue using the default VS doctype of <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> On my page I have a content box, which contains two divs, one floated left and the other floated right. The right floated div contains a height: 100%, however, this is never applied to match the height of the left div. When I remove the doctype (bad, I know, but was just testing..) in IE8 the site looks like a dogs breakfast, whereas in Chrome and Firefox it looked exactly as I wanted it to. A: You should use whatever doctype fits the version of HTML you have been coding for. e.g <!DOCTYPE HTML> for HTML 5.
[ "stackoverflow", "0060764338.txt" ]
Q: Remove Elements of an array on an object based on outer object property I have an object that I want to remove elements from one of its' properties that is an array of objects based on a matching property of the outer object. This uses npm deep-diff to compare the two objects. My problem is inside of combineDuplicateRecords it compares every record against every record, creating duplicates in the identities array. So identities will end up looking like: [{ id: "111", identities: [ { id: "111" }, { id: "111" }, { id: "222" }, { id: "222" }, { id: "333" }, { id: "333" } ] }] when I really want it to look like this: [{ id: "111", identities:[ { id: "222" }, { id: "333" } ] }] Code: var requestRecords = [ { vid: "12345", id: "12345", email: "[email protected]", firstName: "GrandFathering", lastName: "TestMN", postalCode: "55443-2410", phone: "123-456-7890", key: "1212" }, { vid: "121212", id: "12222", email: "[email protected]", firstName: "NoMatch", lastName: "NoMatchFound", postalCode: "43233-2410", phone: "123-456-7890", key: "121233" }, { vid: "111", id: "111", email: "[email protected]", firstName: "samebatch", lastName: "samebatch", postalCode: "5545", phone: "123-456-7890", key: "3333", }, { vid: "222", id: "222", email: "[email protected]", firstName: "samebatch", lastName: "samebatch", postalCode: "5545", phone: "123-456-7890", key: "4444", }, { vid: "333", id: "333", email: "[email protected]", firstName: "samebatch", lastName: "samebatch", postalCode: "5545", phone: "123-456-7890", key: "55", } ]; combineDuplicateRecords = (arrayOfRecords, prefilter) => { const recordsToRemove = []; arrayOfRecords.forEach(firstRecord => { arrayOfRecords.forEach((secondRecord, index) => { if ( firstRecord.firstName == secondRecord.firstName && firstRecord.lastName == secondRecord.lastName && firstRecord.dateOfBirth == secondRecord.dateOfBirth && firstRecord.phone == secondRecord.phone && firstRecord.postalCode == secondRecord.postalCode && firstRecord.id != secondRecord.id ) { const identities = []; let identity = {}; this.preserveExisitingIdentities(secondRecord, identities); this.preserveExisitingIdentities(firstRecord, identities); identity = this.setIdentityDifferencesBetweenRecords( firstRecord, secondRecord, prefilter, identity ); identities.push(identity); firstRecord["identities"] = identities; recordsToRemove.push(index); } }); }); [...new Set(recordsToRemove)].forEach(index => { arrayOfRecords.splice(index, 1); }); return arrayOfRecords; }; preserveExisitingIdentities = (record, identities) => { if (record.hasOwnProperty("identities")) { record.identities.forEach(identity => { identities.push(identity); }); } return identities; }; setIdentityDifferencesBetweenRecords = ( firstIdentity, secondIdentity, prefilter, identity ) => { const differences = Diff(firstIdentity, secondIdentity, prefilter); let i = differences.length; while (i--) { if (differences[i].path[0] == "vid") { differences.splice(i, 1); } if (differences[i].path[0] == "identities") { differences.splice(i, 1); } //we only want to keep the differences so we remove kind D if (differences[i]?.kind == "D") { differences.splice(i, 1); } } differences.forEach(diff => { identity[diff.path[0]] = diff.lhs; }); return identity; }; console.log(JSON.stringify(combineDuplicateRecords(requestRecords))); A: grab each inner id and save them in a data structure, then use Array#find to find the entire object and insert it back into identities const array = [ { id: "111", identities: [ { id: "111" }, { id: "111" }, { id: "222" }, { id: "222" }, { id: "333" }, { id: "333" } ] } ] const cleanObject = (obj) => { const allIds = obj.identities.map(({ id }) => id) const mainId = obj.id const uniqueIds = new Set(allIds) uniqueIds.delete(mainId) const nextIdentities = [...uniqueIds].map(currId => { return obj.identities.find(({ id }) => currId === id) }) obj.identities = nextIdentities return obj }; const el = array.map(entry => { return cleanObject(entry) }) console.log(el)
[ "stackoverflow", "0034550366.txt" ]
Q: Decoding JSON using PHP Forgive me for the simplicity of this question but I am brand new to working with API's and JSON. But I have a JSON file and I want to print out the "text" value of "duration". How can I do that? { "destination_addresses" : [ "San Francisco, CA, USA" ], "origin_addresses" : [ "Seattle, WA, USA" ], "rows" : [ { "elements" : [ { "distance" : { "text" : "808 mi", "value" : 1299998 }, "duration" : { "text" : "12 hours 27 mins", "value" : 44846 }, "status" : "OK" } ] } ], "status" : "OK" } I am trying to do it using: $url = 'https://maps.googleapis.com/maps/......' $content = file_get_contents($url); $json = json_decode($content, true); echo $json['rows']['elements']['duration']['text']; Many thanks! A: You should do it like this: echo $json['rows'][0]['elements'][0]['duration']['text']; Output: 12 hours 27 mins Notice that in the json, you have what marks new arrays [, so you forgot to use [SOME_NUMBER]. This is the structure (from print_r($json);): Array ( [destination_addresses] => Array ( [0] => San Francisco, CA, USA ) [origin_addresses] => Array ( [0] => Seattle, WA, USA ) [rows] => Array ( [0] => Array ( [elements] => Array ( [0] => Array ( [distance] => Array ( [text] => 808 mi [value] => 1299998 ) [duration] => Array ( [text] => 12 hours 27 mins [value] => 44846 ) [status] => OK ) ) ) ) [status] => OK ) You can also use it as object. It would be like this: $json = json_decode($content); // without true echo $json->rows[0]->elements[0]->duration->text; Output: 12 hours 27 mins
[ "stackoverflow", "0032859364.txt" ]
Q: PySpark RDD processing for sum of parts I have a RDD with tuples like (datetime, integer). And I try to get another RDD of some interval summation with pyspark. For example, from followings (2015-09-30 10:00:01, 3) (2015-09-30 10:00:02, 1) (2015-09-30 10:00:05, 2) (2015-09-30 10:00:06, 7) (2015-09-30 10:00:07, 3) (2015-09-30 10:00:10, 5) I'm trying to get followings sum of every 3 seconds: (2015-09-30 10:00:01, 4) # sum of 1, 2, 3 seconds (2015-09-30 10:00:02, 1) # sum of 2, 3, 4 seconds (2015-09-30 10:00:05, 12) # sum of 5, 6, 7 seconds (2015-09-30 10:00:06, 10) # sum of 6, 7, 8 seconds (2015-09-30 10:00:07, 3) # sum of 7, 8, 9 seconds (2015-09-30 10:00:10, 5) # sum of 10, 11, 12 seconds Please, could you give me any hints? A: I will assume that your input is an RDD time_rdd with tuples where the first element is a datetime object and the second element is an integer. You could use a flatMap to map every datetime object to the previous 3 seconds and then use a reduceByKey to get the total count for that window. def map_to_3_seconds(datetime_obj, count): list_times = [] for i in range(-2, 1): list_times.append((datetime_obj + timedelta(seconds = i), count)) return list_times output_rdd = time_rdd.flatMap(lambda (datetime_obj, count): map_to_3_seconds(datetime_obj, count)).reduceByKey(lambda x,y: x+y) This RDD will contain more datetime objects than the ones in the original RDD, so if you only want to have the original times, then you need to do a join with the time_rdd, result = output_rdd.join(time_rdd).map(lambda (key, vals): (key, vals[0])).collect() Now result will contain: [(datetime.datetime(2015, 9, 30, 10, 0, 5), 12), (datetime.datetime(2015, 9, 30, 10, 0, 2), 1), (datetime.datetime(2015, 9, 30, 10, 0, 10), 5), (datetime.datetime(2015, 9, 30, 10, 0, 1), 4), (datetime.datetime(2015, 9, 30, 10, 0, 6), 10), (datetime.datetime(2015, 9, 30, 10, 0, 7), 3)]
[ "stackoverflow", "0028056898.txt" ]
Q: regular expression to match exactly 0.[001 to 999] I tried (^[0]?)\.*(?=.*[1-9])\d{1,3}?$expression to match input value which should only accept 0.[001 to 999] , now the problem is : it is matching 012 or 090 etc numbers too. I wanted the expression to match exactly 0.[001 - 999] Any help is appreciated. Thanks, Sri A: You had \.* which matches 0 or more. It matches 0, therefore you get to match stuff like 012. ^0\.[0-9]{2}[1-9]$ Matches a 0, then a ., then [0-9] twice, then [1-9] Edit: Jonathan is right, this doesn't properly match stuff like 0.010. ^0\.[0-9]{3}$ and then ensure that it is not 0.000 would work. Alternatively try this ugly one: ^0\.(?:[0-9]{2}[1-9]|[0-9][1-9][0-9]|[1-9][0-9]{2})$
[ "serverfault", "0000881510.txt" ]
Q: Restrict network access for remote computer I have a remote office which has some computers which cannot have regular internet access, however, I will need to periodically access the computers remotely for which I plan to use VNC. What is a good way to make sure the computers have no internet access except my inbound VNC connections? My first thought here would be to configure a router ahead of them so that the router only allows ARP/DNS and the VNC port(s) 5000+N, and blocks all other ports in and out. Would that be an effective solution? A: As far as I know leaving VNC port opened to the world (0.0.0.0/0) is non-secure and hackable. Things you can do: Install a firewall and configure NAT - allowing you to access the network through the VNC port but only to one specific IP (and not to the world). Configure a VPN server which will let you reach all hosts within the network once you're connected to it. Using both solutions you can limit users access to the internet and allowing access to specific services within the network.
[ "stackoverflow", "0045584836.txt" ]
Q: How to make SASS work in Symfony3 project? I have a Symfony3 project and want to use SASS for my stylesheets. I have looked up many pages and found Assetic related threads - but no "real" explanation, how to integrate SASS in a Symfony3 project. Can't be too difficult, can it? I would be glad to hear any hint or complete "how to" - thanks a bunch! A: I create a separate frontend build process using NPM for this which can handle all images, SASS/CSS, and JS with compression etc. and then add a build step to generate everything. If you don't have NPM, follow instructions to install: https://www.npmjs.com/get-npm Initialise the project by running npm init in your project directory. Install some tools for compiling and compressing: npm install node-sass --save-dev this compiles SASS to CSS npm install postcss-cli --save-dev this processes compiled CSS npm install cssnano --save-dev this minifies CSS and is used as a plugin for postcss npm install autoprefixer --save-dev this adds moz, webkit and vendor prefixes and is used as a plugin for postcss npm install npm-run-all --save-dev this isn't strictly necessary but allows you to group commands which is helpful as you add more steps. Once you've got these dependencies installed, you can add your build scripts. Open package.json and modify the scripts key. { "name": "your-project-name", ... "scripts": { "build-task:scss-compile": "node-sass --source-map true app/Resources/sass/app.sass -o web/css", "build-task:css-minify": "postcss web/css/app.css --use cssnano autoprefixer -d web/css", "build": "npm-run-all -p build-task:*" }, ... } You can now run npm run build. build-task:scss-compile will compile your SASS into a single, uncompressed CSS file in the web/css directory which can be linked to in your templates. Then build-task:css-minify will compress it and add any vendor prefixes to the CSS. You can add more build tasks as mentioned above and chain them in this way. You can also add file watchers and a watch command which will run the build scripts when any watched files are modified. Don't forget to add node_modules to your .gitignore file. The reason I opt for a separate process over something like Assetic and leafo/scss as outlined in the Symfony docs is that Assetic filters add a lot of overhead to responses as they compress things on the fly which will slow down development considerably. It also separates concerns between application and presentation and gives you more flexibility to later build on and adapt your front end without touching your application. EDIT: Here is a gist of a package.json file that will also copy jQuery, FontAwesome, anything in the assets directory including any images or fonts, compile and minify JavaScripts, after checking them for errors and create required directories if they don't already exist and a file watcher for building when files are modified: https://gist.github.com/matt-halliday/6b9a3a015b7a87c5b165ce1a9ae19c9b
[ "stackoverflow", "0040743411.txt" ]
Q: Running ASP.NET Core with HTTPS in docker from Visual Studio 2015 On my computer, I have installed Docker for Windows and Visual Studio 2015 Update 3. I created a Web App with ASP.NET Core and configured Kestrel to use https. I tested if the application works without docker and it runs nicely over the https protocol. Next, I installed Visual Studio Tools for Docker and tried to debug the application in Docker. Although everything says that the application is running using https, I cannot connect to the application. Since everything is working without docker, I would expect that it would work in Docker as well. Unfortunately I didn't find much about this topic regarding .NET Core 1.0. Can someone point me in the right direction to set this up, so I can test this with https on Docker. One thing I haven't mentioned yet, is that I require https to be able to use Azure Active Directory to authenticate and authorize my users. I don't really know where to begin, so I have no code samples. But I can provide these upon request. TIA Edit: I logged into the container, installed Lynx and tested the web application. This works... The only thing I am not able to get solved is getting a connection from outside the container to the web application. A: Adjusting the paths in the configuration files to the linux format for paths and by using the standard docker commands to build the image worked. I guess the Docker Tools for VS2015 are not stable enough.
[ "stackoverflow", "0011197999.txt" ]
Q: Android button class returning incorrect value I am very new to Android development and Java. Have read around but I'm not getting anywhere on this issue. I have a button which when clicked should set a variable A's Value to "Item Purchased". However, I am only get the value used when the variable is first defined in the class. For those learning like me on this - this topic will hopefully make an excellent reference to those just starting. Code is: public class shopView extends Activity { String temp = "temp"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.shopview); Button btnRef1 = (Button) findViewById(R.id.btnbtnRef11); final TextView ConfirmPurchasetest = (TextView) findViewById(R.id.tvMigName); btnRef1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { temp = "passed value"; ConfirmPurchasetest.setText("item Purchased"); buyFromShop(); Log.v("after button push", "temp"); }; }); } public String buyFromShop(){ Log.v("button push", "after buy from shop"); Log.v("temp variable",temp); return temp; } } and is called using the following: shopcheckout = shop.buyFromShop(); Log.v("Value in myView",shopcheckout); Expected: shopcheckout = "item purchased" Actual: shopcheckout = "temp" Thanks again for any answers. Will actively monitor this post. A: Unless you click on your Button btnRef1, buyFromShop() will always return "temp". If you add this code in your onCreate(): temp = "Changing the string."; Now buyFromShop() will return "Changing the string.". If you want buyFromShop() to return the value of ConfirmPurchasedtest, change your code to this: public class shopView extends Activity { TextView confirmPurchaseTest; String temp = "temp"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.shopview); Button btnRef1 = (Button) findViewById(R.id.btnbtnRef11); confirmPurchaseTest = (TextView) findViewById(R.id.tvMigName); btnRef1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { temp = "passed value"; confirmPurchaseTest.setText("item Purchased"); buyFromShop(); Log.v("after button push", "temp"); } }); } public String buyFromShop(){ Log.v("button push", "after buy from shop"); Log.v("temp variable", temp); // Change this! return confirmPurchaseTest.getText().toString(); } } Also according to naming convention, class names like shopView should have the first letter of each word capitalized; so ShopView. Variables like ConfirmPurchasetest should start with lower case and then capitalize each word (after the first), so confirmPurchaseTest. Hope that helps!
[ "gis.stackexchange", "0000155628.txt" ]
Q: What is the Microstation keyin for Sychronize Google Earth View for a specific view? I'm using TerraScan on top of Microstation V8i and I am setting up hotkeys for frequently used commands. I can't find any documentation about the keyins for the Google Earth toolbar, specifically to link the Synchronize GE View button to a specific view (View 1). I know the keyin for this tool is: googleearth synch I have followed some keyins with "selview1" or just the number 1 for View 1. Such as: move up;selview 1 View Previous 1 Does anyone know the keyin to apply the synch google earth to a specific view? A: I too am trying to figure this out, the best I've come up with is toggling the view off and on before synchronizing. So my key-in for syncing view 1 is: view toggle 1;view toggle 1;googleearth synch this would work too: view off 1;view on 1;googleearth synch
[ "blender.stackexchange", "0000192606.txt" ]
Q: How can I make a custom fbx exporter for unity? I want to export fbx for unity based on manual way in this video I know there is an option as !!EXPERIMENTAL!!, I don't want to use it because sometimes it doesn't work. Manual Way manual way works fine I just want to do manual way by code. because I have to repeat these steps on every 3d models!!! suppose we have a fish model and we want to export it to untiy 1.Manually rotate the object by -90 degree around X-axis (if you don't see this panel - press N key) 2.press Ctrl + A and Apply => Rotation 3.and set X rotation to 90 degrees (do not apply this time) A: you can make steps automatic 1.rotate the object by -90 degree around X-axis obj.rotation_euler = (math.radians(-90),0,0) 2.press Ctrl + A and Apply => Rotation bpy.ops.object.transform_apply(location=False, rotation=True, scale=False) 3.and set X rotation to 90 degrees (do not apply this time) obj.rotation_euler = (math.radians(-90),0,0) also, you can export it by unit scale bl_info = { "name": "Unity Fix", "author": "Kamali", "version": (1, 0), "blender": (2, 80, 0), "location": "File > Export > Export For Unity", "description": "Fix Pivot ,Location , Rotation , Scale ", "warning": "", "doc_url": "", "category": "", } import bpy import math def write_some_data(context, filepath): bpy.ops.object.origin_set(type='ORIGIN_CENTER_OF_MASS', center='MEDIAN') obj= context.object # reset location to the center obj.location = (0,0,0) # reset everything to make sure it won't change bpy.ops.object.transform_apply(location=True, rotation=True, scale=True) # set rotation to -90 obj.rotation_euler = (math.radians(-90),0,0) # reset everything bpy.ops.object.transform_apply(location=True, rotation=True, scale=True) # rotate 90 degree along x axis obj.rotation_euler = (math.radians(90),0,0) # apply unit scaling bpy.ops.export_scene.fbx(filepath=filepath, use_selection=True,apply_scale_options='FBX_SCALE_UNITS',apply_unit_scale=True) return {'FINISHED'} from bpy_extras.io_utils import ExportHelper from bpy.props import StringProperty, BoolProperty, EnumProperty from bpy.types import Operator class ExportSomeData(Operator, ExportHelper): """Export For Unity""" bl_idname = "export_test.some_data" bl_label = "Export For Unity" filename_ext = ".fbx" filter_glob: StringProperty( default="*.fbx", options={'HIDDEN'}, maxlen=255, ) def execute(self, context): return write_some_data(context, self.filepath) # Only needed if you want to add into a dynamic menu def menu_func_export(self, context): self.layout.operator(ExportSomeData.bl_idname, text="Export For Unity") def register(): bpy.utils.register_class(ExportSomeData) bpy.types.TOPBAR_MT_file_export.append(menu_func_export) def unregister(): bpy.utils.unregister_class(ExportSomeData) bpy.types.TOPBAR_MT_file_export.remove(menu_func_export) if __name__ == "__main__": register()
[ "stackoverflow", "0009341494.txt" ]
Q: iFrame source can not be retrieved <iframe id="myFrame" runat="server" name="main" width="100%" src="http://www.somewebpage.com/" /> This is simple iFrame I put on my webpage. After I click on couple of buttons on that website, iframe source remains the same. But I want to be able to retrieve the changed source every time I click on buttons, links etc... How can I achieve this? Edit: This is the screenshot of my work. When I click on "Git" button, webpage loads on the iFrame. However, when I surf on the website, I want textbox to be updated to the source of the iFrame. A: Ok, here is an idea that I test it now and its work. You change the input box after the iframe loads using the onload event of the iframe <script> function HasChange(me) { document.getElementById("WhereIamId").value = document.getElementById("WhatIShowID").src; return false; } </script> and the html <input type="text" id="WhereIamId" value="" /> <iframe src="page1.aspx" onload="return HasChange(this);" id="WhatIShowID" ></iframe> You can use also the document.getElementById("<%=myFrame.ClientID>") to get the rendered id. After your iframe loads you update the text box with the current url.
[ "stackoverflow", "0062678168.txt" ]
Q: Using python on a Google Cloud Windows Server I've just installed Windows Server 2019 on Google Cloud Compute Engine, so I can host my python apps 24/7 but I can't install python because of this error: 0x80070659 - This installation is forbidden by system policy. Contact your system administrator. I was wondering if there's anything I can do to resolve this issue. A: Solution: I just needed to run the setup file as administrator.
[ "askubuntu", "0000703689.txt" ]
Q: Cannot run cmake from QtCreator QtCreator shows me this error message and asks me to browse for and select a cmake executable: /usr/bin/cmake: error while loading shared libraries: libgssapi_krb5.so.2: cannot open shared object file: No such file or directory A: That error message actually suggests that it is able to find the cmake executable (as /usr/bin/cmake) but when it attempts to execute it it can't, because cmake requires a shared library (libgssapi_krb5.so.2) which can't be found. There are a variety of ways that that might happen, but there are a couple of things you can try: If the library is just not actually installed, you may need to install its package: sudo apt-get install libgssapi-krb5-2 If the libgssapi-krb5-2 package is already installed, it's possible that there is just a problem with the libgssapi_krb5.so.2 symlink that links to the actual library. If this is the case, the following command should fix it: sudo ldconfig -v It may also be a good idea to make sure that there aren't any other libraries that are missing that cmake needs to run. You can do this with the following command: ldd /usr/bin/cmake This will print all of the shared libraries it needs, and where it found them in the filesystem (if it was able to find them, or tell you if it can't)
[ "boardgames.stackexchange", "0000024354.txt" ]
Q: When Data mine is triggered, if the runner survives this ice, can (s)he/other still continue? Let's say we have the following setup in this order: 1) ICE: Data mine. 2) Asset: Melange Mining Corp. That is I have a remote server, which consists of 1 ice and 1 asset. The Runner encounters the ICE. The runner loses 1 card, and survives the encounter. Since there is no 'End the run' subroutine, can the runner continue to access the asset once I trash the ice? ( according to the rule of this ICE, I have to trash the ice once the subroutine fires ) Thanks, Suman A: Core rules: After the Runner breaks all of the ice’s subroutines and/or any effects from unbroken subroutines resolve without ending the run, he has passed that piece of ice. He then continues the run by either approaching the next piece of ice protecting the server or proceeding to the Access phase if there is no more ice to approach. Data Mine doesn't end the run, so the run continues. In you example, the runner would go on to access Melange Mining Corp. It trashes itself as part of its ability because trap ice cards are designed to be hard to break but only hit once.
[ "space.stackexchange", "0000033135.txt" ]
Q: What time will news from New Horizons' Arrokoth (2014 MU69) encounter become available to the public? This is New Years Day and the big day for New Horizons' encounter with Arrokoth! But it doesn't mean there was nice pictures of MU69 on the big LED displays in Time Square at 00:01 01-Jan-2019. There are avoidable delays (press office closures due to government shut-downs) and unavoidable delays (speed of light), schedules (when is the flyby exactly?) and local buffering due to extremely slow data rates from a zillion miles away. Roughly what time is it likely that some news or data will make it to the general public about any or all of the following: a flyby happened and New Horizons did or may not have survived it a photo or spectrum or some measurement of MU69 itself a deviation of some kind in the trajectory or velocity produced by gravitational deflection by MU69 A: In simple explanation, we won't able to know what's up with New Horizons right away. The probe will be busy collecting all the science data during the high-speed flyby. Closest approach will be at a distance of 3,500 kilometers at about 05:33 on 1 January UTC, and it’ll happen at a zippy 14.16 kilometers per second. [1] (empasis mine) As happened at Pluto, New Horizons will not be communicating with Earth during closest approach, because it will be focused on gathering all the science it can during the high-speed flyby. Whenever it does turn back to point at Earth to transmit data it will take more than 6 hours for its data to traverse the distance between us. [1] However, there will still be downlinks from New Horizons around its January 1 flyby available but don't expect it to be either good or punctual1: Credit: ESA/Rosetta/MPS for OSIRIS Team MPS/UPD/LAM/IAA/SSO/INTA/UPM/DASP/IDA/Emily Lakdawalla from this page1 WHAT KINDS OF IMAGES OF 2014 MU69 WILL BE AVAILABLE WITHIN DAYS OF THE FLYBY? The downlinks from New Horizons around its 1 January 2019 flyby of 2014 MU69 will not contain its highest-resolution images. Instead, they will be photos that the team is reasonably confident will contain an image of 2014 MU69.1 Two "failsafe" downlinks are planned for before the closest approach, and three "New York Times" downlinks are planned over the two days after closest approach. These are Rosetta OSIRIS images of comet 67P/Churyumov-Gerasimenko, scaled to be approximately the same size that the New Horizons images of 67P are expected to be, with some processing to add blur and speckle noise (for a variety of reasons, New Horizons LORRI images of MU69 will not look as crisp as Rosetta OSIRIS images of 67P). They are at a phase angle of 10 degrees, similar to the 11-degree phase at which New Horizons will see MU69 from a distance. One important caveat: the times reported above are when the images will be downlinked. This is not the same as when they will be published. New Horizons (unlike Curiosity, Opportunity, InSight, solar missions, and formerly Cassini) doesn't push images straight to the Web once they land on Earth. The mission will process them, and the team will write captions, and then NASA will have to vet the captions, and then NASA will publish the images at a time of day that'll maximize news coverage, all of which means it could be up to a day or so after downlink that these images get released. [1] 1. A flyby happened and New Horizons did or may not have survived it Currently, we are in the Approach phase, which began on 16 August and runs through 24 December (7 days before closest approach). During approach, New Horizons has been taking images for optical navigation and searching for potentially dust-generating hazards like rings or moons. (So far, it has not spotted any.) The in-situ instruments have been busy gathering data on the fields and particles in interplanetary space. [1] Furthermore, the operations team weighed numerous factors in making its choice to closest approach. The considerations included what is known about MU69’s size, shape, and the likelihood of hazards near it, the challenges of navigating close to MU69 while obtaining sharp and well-exposed images, and other spacecraft resources and capabilities.2 It's unlikely that New Horizons will not survive the flyby. 2. A photo or spectrum or some measurement of MU69 itself As said above, New Horizons has been snapping pictures of Ultima Thule to identify any potential hazards. The result so far is that it appears clear and safe to approach. Earliest downlinks will be available on January 1, the rest will released accordingly during the Departure phase that will last one week after the 2-day period around closest approach, from 3 through 8 January. After that, New Horizons will spend 20 months downlinking all the remaining data, until September 2020. Regardless of U.S. government shutdown, the show will go on! New Horizon flyby of Ultima Thule event timeline (from this page1): Source: Partial screenshot of this page1 References 1 Emily Lakdawalla, December 17, 2018, What to Expect When New Horizons Visits 2014 MU69, Ultima Thule (And When We Will Get Pictures), The Planetary Society. 2 Johns Hopkins University Applied Physics Laboratory (2017), 6 September 2017, New Horizons Files Flight Plan for 2019 Flyby. Quoting New Horizons Principal Investigator Alan Stern of the Southwest Research Institute (SwRI), Boulder, Colorado. Also of interest Applied Physics Laboratory's YouTube channel Full coverage of New Horizon's encounter with MU69. Emily Lakdawalla, December 27, 2018, New Horizons fast approaching 2014 MU69 Check this blog entry for MU69 photos taken and returned by New Horizons before 1 January. A: According to this article, "The first images are expected by the evening of January 1, with release planned for January 2. More, higher resolution shots should follow." Evening is presumably that of Johns Hopkins University Applied Physics Laboratory, Eastern Standard Time (UTC-5). Other sources are a bit more specific: Of particular interest on Tuesday 2019-01-01 (from the schedule below): 0033 EST (0533 UTC) Closest approach It appears that data will be collected for about 3 hours after this time (note that it will take over 6 hours for any signal to reach Earth and that NH cannot collect and transmit data at the same time) 0945-1015 EST (1445-1515 UTC) Live coverage of signal-acquisition It is at this time that we will know whether NH survived the encounter. 1130-1230 EST (1630-1730 UTC) Press briefing: Spacecraft status, latest images and data download schedule All probe health data should have been received by this time and the status of the probe and its instruments should be known. Science data will follow with first imagery available possibly around 2000 EST (0100 Wednesday 2019-01-02 UTC). A highly detailed schedule can be found here including: 1045 EST (1545 UTC) End of system health data return (no science data) 1835 EST (2335 UTC) End of first post-pass science data return "LORRI image at 300 meters per pixel -- hopefully a full globe image of about 100 pixels across" plus other science data. The initial LORRI image should be available shortly thereafter. The JHUAPL is largely unaffected by the 3rd 2018 US government shutdown and will be providing full coverage on their Youtube channel and on the New Horizons website. There will also be live coverage on Twitter @JHUAPL Keep in mind that we may not get anything close to the quality we got for the Pluto system. Given all the unknowns any images returned may end up being blurry (wrong slew rate) or blank (pointing in the wrong direction). Schedule of events: Source: Alan Stern / JHUAPL via Twitter, screenshot of this page
[ "japanese.stackexchange", "0000060079.txt" ]
Q: The usage of 比べて -- without saying the thing being compared to? I want to express: 'He is good at basketball. In comparison, she is less skilled.' My sentence is: ε½Όγ―γƒγ‚Ήγ‚±γƒƒγƒˆγƒœγƒΌγƒ«γ§δΈŠζ‰‹γ§γ™γ€‚ε½Όε₯³γ―、比べて、下手です。 Is this correct? Please correct me for any errors I've made ηš†γ•γΎε›žη­”γ‚ˆγ‚γ—γγŠι‘˜γ„γ—γΎγ™m(_ _)m A: γ€Œζ―”γΉγ¦γ€ can't stand alone. You could use γ€Œγγ‚Œγ«ζ―”γΉγ‚‹γ¨γ€, as in... ε½Όγ―γƒγ‚Ήγ‚±γƒƒγƒˆγƒœγƒΌγƒ«γŒ[δΈŠζ‰‹]{γ˜γ‚‡γ†γš}です。彼ε₯³γ―γ€γγ‚Œγ«ζ―”γΉγ‚‹γ¨γ€ο½›[δΈŠζ‰‹]{γ˜γ‚‡γ†γš}γ§γ―γ‚γ‚ŠγΎγ›γ‚“γ€‚/ [δΈŠζ‰‹]{うま}γγ‚γ‚ŠγΎγ›γ‚“γ€‚ο½ γγ‚Œγ«ζ―”γΉγ¦ would be grammatically correct, but γγ‚Œγ«ζ―”γΉγ¦γ€ε½Όε₯³γ―下手です。/ δΈŠζ‰‹γ§γ―γ‚γ‚ŠγΎγ›γ‚“γ€‚ would sound like "In contrast / Unlike him, she is unskilled/poor.")
[ "stackoverflow", "0049860937.txt" ]
Q: C multiple write access to a log file (linux env) I have a set of independent programs that I wrote in C. I would like all of them to write their log to the same file. Obviously comes the issue of control access. Two or more of them could end up writing simultaneously. What is the most pragmatic way to achieve this? I came across solutions using pthread/mutexes/etc but that sounds overkill implementation for something like that. I am also looking at syslog but wonder if this is really for the purpose of what I need to do? I feel that I need a daemon service taking the message and control when they are written. I wonder if that already exists. A: I am also looking at syslog but wonder if this is really for the purpose of what I need to do? Yes I feel that I need a daemon service taking the message and control when they are written. I wonder if that already exists. It exists in the Unix derivatives (including Linux) and is called... syslogd More seriously, the syslog function is intended to pass a message to a syslogd daemon that will route it according to its configuration file. Most common uses include writing it down to a file or to the system console (specially for panic level messages when nobody can be sure whether the file system is still accessible). The syslog system may come with more features than what you are asking for, but it is an extremely robust and extensively tested piece of software. In addition, it is certainly already active on your system, so you should have a strong reason to roll your own instead of using it.