text:
Q: Odd output from dsmc (Tivoli storage manager or TSM) query backup I'm using TSM (dsmc) on Ubuntu 14.04.
# dsmc
IBM Spectrum Protect
Befehlszeilenschnittstelle des Clients für Sichern/Archivieren
  Clientversion 8, Release 1, Stufe 8.0
  Client-Datum/Zeit: 04.12.2019 13:57:40
(c) Copyright by IBM Corporation and other(s) 1990, 2019.
(c) Copyright by IBM Corporation und Andere 1990, 2019. Alle Rechte vorbehalten.

Knotenname: ServernameB
Sitzung hergestellt mit Server SB05: AIX
  Serverversion 7, Release 1, Stufe 7.300
  Serverdatum/-zeit: 04.12.2019 13:57:41  Letzter Zugriff: 04.12.2019 13:47:43

When I try to run a dsmc query backup command, I'm getting vers unusual results.
I'm using this as a reference.
When I try to see the contents of "/common/share/archive" it seems to reply with "/common/share/*/archive".
All of the responses returned are ONLY for files named "archive", that live anywhere below "/common/share/"
I.e.Trying ...
q ba /common/share/archive/ -subdir=yes

...or...
q ba /common/share/archive/* -subdir=yes

...both return nothing.
Output:
Protect> q ba /common/share/archive -subdir=yes
            Größe     Sicher.-Datum              Verw.klasse           A/I Datei
            -----     -------------              -----------           --- -----
            10  B  27.05.2019 11:57:10             STANDARD             A  /common/share/Armar3/SFB588_RefDist/LibrarySources/Qt-4.6.3/src/3rdparty/webkit/WebCore/loader/archive
            10  B  27.05.2019 12:02:14             STANDARD             A  /common/share/Armar3/SFB588_RefDist/LibrarySources/Qt-4.7.2/src/3rdparty/webkit/WebCore/loader/archive
            53  B  27.05.2019 12:03:51             STANDARD             A  /common/share/Armar3/SFB588_RefDist/LibrarySources/boost_1_44_0/boost/archive
            53  B  27.05.2019 12:06:53             STANDARD             A  /common/share/Armar3/SFB588_RefDist/LibrarySources/boost_1_46_1/boost/archive
            11  B  27.05.2019 12:17:54             STANDARD             A  /common/share/Armar3/SFB588_RefDist/Qt/build/qt-everywhere-opensource-src-4.6.3/src/3rdparty/webkit/WebCore/loader/archive
            10  B  27.05.2019 12:23:27             STANDARD             A  /common/share/Armar3/SFB588_RefDist/Qt/build/qt-everywhere-opensource-src-4.7.1/src/3rdparty/webkit/WebCore/loader/archive
            53  B  27.05.2019 12:31:32             STANDARD             A  /common/share/Armar3/SFB588_RefDist/boost/1.38.0/boost/archive
            53  B  27.05.2019 12:31:55             STANDARD             A  /common/share/Armar3/SFB588_RefDist/boost/1.38.0/boost_install/include/boost-1_38/boost/archive
            53  B  27.05.2019 12:34:46             STANDARD             A  /common/share/Armar3/SFB588_RefDist/boost/1.42.0/boost/archive
            53  B  27.05.2019 12:35:09             STANDARD             A  /common/share/Armar3/SFB588_RefDist/boost/1.42.0/boost_install/include/boost/archive
            53  B  27.05.2019 12:37:29             STANDARD             A  /common/share/Armar3/SFB588_RefDist/boost/1.44.0/include/boost/archive
            53  B  27.05.2019 12:38:36             STANDARD             A  /common/share/Armar3/SFB588_RefDist/boost/1.44.0_withInstalledLibraries/boost/archive
            53  B  27.05.2019 12:39:23             STANDARD             A  /common/share/Armar3/SFB588_RefDist/boost/1.44.0_withInstalledLibraries/boost_install/include/boost/archive
            53  B  27.05.2019 12:42:54             STANDARD             A  /common/share/Armar3/SFB588_RefDist/boost/1.48/include/boost/archive
            52  B  27.05.2019 12:44:09             STANDARD             A  /common/share/Armar3/SFB588_RefDist/boost/1.54.0/boost_1_54_0/boost/archive
            52  B  27.05.2019 12:46:18             STANDARD             A  /common/share/Armar3/SFB588_RefDist/boost/1.54.0/include/boost/archive
            52  B  27.05.2019 12:46:55             STANDARD             A  /common/share/Armar3/SFB588_RefDist/boost/old2_1.44.0/include/boost/archive
             4  B  27.05.2019 13:09:07             STANDARD             A  /common/share/Armar3/SFB588_RefDist/old/simox/simox_current_version_sourceforge/build_10.04/VirtualRobot/CMakeFiles/Export/_org/share/archive
             4  B  27.05.2019 13:09:21             STANDARD             A  /common/share/Armar3/SFB588_RefDist/old/simox/simox_current_version_sourceforge/build_8.04/VirtualRobot/CMakeFiles/Export/_org/share/archive
            53  B  27.05.2019 13:13:02             STANDARD             A  /common/share/Armar3/SFB588_RefDist/x86_64/boost/include/boost/archive
            10  B  27.07.2019 13:41:36             STANDARD             A  /common/share/backup/i61pc011/sda2/Anaconda2/Lib/site-packages/statsmodels/sandbox/archive
             7  B  27.07.2019 15:39:43             STANDARD             A  /common/share/backup/i61pc011/sda2/libs/Qt/4.6.1-x64/qt/src/3rdparty/webkit/WebCore/loader/archive
            10  B  27.07.2019 15:40:56             STANDARD             A  /common/share/backup/i61pc011/sda2/libs/Qt/4.6.2/qt/src/3rdparty/webkit/WebCore/loader/archive
            10  B  27.07.2019 15:44:00             STANDARD             A  /common/share/backup/i61pc011/sda2/libs/x64/Qt/4.6.2/src/3rdparty/webkit/WebCore/loader/archive
            52  B  27.07.2019 15:47:33             STANDARD             A  /common/share/backup/i61pc011/sda2/libs/x64/boost144/boost/archive
             7  B  18.07.2019 03:39:03             STANDARD             A  /common/share/project/HIS PROJEKTE ausgelaufen/10. Dissemination/Organisierte_Konferenzen-Workshops/stattgefunden/ECMR-2007/ECMR2007_homepage/archive
Protect>


text:
Q: Which App Store link do I use Before I uploaded the Xcode binary to iTunes Connect, I could only use the following link for app store to my app store page for game.
http://itunes.apple.com/app/id123456789
Now my app status is "pending developer release" and when I click on "view in app store" in iTunes Connect I now have another link...
https://itunes.apple.com/us/app/App-Name/id123456789?gs=2&bh=3
Which link do I use now, does it make a difference even?

A:
https://itunes.apple.com/us/app/App-Name/id123456789?gs=2&bh=3

This URL is Standard App Store Links.

http://itunes.apple.com/app/id123456789

This URL is short link.
The difference between these two is length. You can choose either one you like.
ref. Technical Q&A QA1633: Creating easy-to-read short links to the App Store for your apps and company
https://developer.apple.com/library/ios/qa/qa1633/_index.html

A: It doesn't matter if you keep use before link

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to allow speech recognition to continually transcript? (python) I'm new to coding and Python and at a little bit of a crossroads with this project I'm tackling.
I'm wanting the try a version that continually transcripts (and translates) as words are being spoken. Currently it waits for a period of silence before transcripting what was spoken. Do you know of any method do accomplish this? Is it more a matter of using alternative speech recognition/translating modules?
Here is my code:
import speech_recognition as sr
r = sr.Recognizer()
mic = sr.Microphone()
with mic as source:
    r.adjust_for_ambient_noise(source, duration=0.3)
    audio = r.listen(source)
    transcript = r.recognize_google(audio)
    print(transcript)

from googletrans import Translator
translator = Translator()
result = translator.translate(transcript, dest='de')
print(result.dest)
print(result.text)
print(result.pronunciation)

Thank you very much!


text:
Q: Mandelbrot set perturbation theory: When do I use it? I have read the post on Perturbation of Mandelbrot set fractal. I will also be referring to the PDF by K.I. Martin on this topic.
My question is to do with the precision laid out in the Martin paper. I understand that in the equation $\Delta_n=A_n\delta+B_n\delta^2+C_n\delta^3+o(\delta^4)$, Martin uses $o(\delta^4)$ for the small terms, since those terms are small and do not contribute much to the equation.
So, we can use the iterative approximation given in the paper for all the $Y_n$ of the points surrounding the initial point $X_0$. He states that "the approximation should be good as long as the $\delta_3$ term has a magnitude significantly smaller then the $\delta_2$ term."
First Question:
But, how much smaller is "significantly smaller?" If I want to generate an image where the $\Delta_x=\Delta_y=0.1$, would it be okay to just start in the center use this method for the surrounding points? Or does it depend on the center point?
Second Question:
Since, I am going to be generating images with these results, is it possible that I will need to generate them with "seeds?" In other words, I could start with some center point $X$. Then calculate all of the surrounding points, expanding outward from $X$ until the $\delta$ is too large (i.e. the $\delta_3$ term no longer has a magnitude significantly smaller than the $\delta_2$ term). Then go to another $X$ seed, following the same process, and so on until the entire image is generated. Will that ever be neccessary?
Note: Since I am going to be implementing this, I could just go ahead and try things out, but I like to understand all of the theory before I start.

A: First answer:  "the $\delta^3$ term remains significantly smaller than the $\delta^2$ term" means that $\left|C_n \delta^3\right| << \left|B_n \delta^2\right|$, usually a few orders of magnitude is a good amount (factor of $10^3$ or so).  What the final $n$ will be for this stage depends on both the $X_0$ and the largest $\delta$ for the pixels in the image.
Often it will be obvious how many per-pixel iterations it is safe to "skip" by this series approximation technique, the $\left|C_n\right|$ will suddenly increase, but sometimes you get more subtle image distortion first - a common technique is to use regular perturbed iterations for some "probe points" in the image and stop the series approximation iterations once they deviate too much.
The final $n$ in the series approximation step is usually significantly smaller than the minimum iteration count for the first escaping pixel in the view.  So you combine it with perturbed iterations for the remaining count.
Second answer: I'm not sure what you mean by seed.  Usually it works like this:

*

*pick a reference point $X_0$ and some probe points $\Delta_0$ in the image

*while the series approxmation is accurate, determined by the worst relative error among all the probe points $|e| << 1$

*

*step the high precision reference one iteration
using $$X_{n+1} = X_n^2 + X_0$$

*step the series approximation coefficients one iteration
using $$\begin{aligned}A_{n+1} &= 2 X_n A_n + 1 \\ B_{n+1} &= 2 X_n B_n + A_n^2 \\ C_{n+1} &= 2 X_n C_n + 2 A_n B_n \end{aligned}$$

*step the probe points one iteration
using $$\Delta_{n+1} = 2 X_n \Delta_n + \Delta_n^2 + \Delta_0$$

*initialize all the image points from their $\Delta_0$ with last good series approximation coefficients using $$\Delta_n = A_n \Delta_0 + B_n \Delta_0^2 + C_n \Delta_0^3$$

*step the reference $X_n$ until it escapes or maximum iteration count is reached using $$X_{n+1} = X_n^2 + X_0$$

*step all image points $\Delta_n$ using stored reference iterations $X_n$ using $$\Delta_{n+1} = 2 X_n \Delta_n + \Delta_n^2 + \Delta_0$$  If you detect "glitches" in the perturbed iterations by $|X_n + \Delta_n| << |X_n|$, set these pixels aside

*if there are glitched pixels remaining (or the reference escaped too early), repeat this whole process for the glitched pixels (pick a different $X_0$)

"Glitches" occur when the dynamics of a pixel are too different from the dynamics of the reference.  They can (usually) be detected by Pauldelbrot's criterion1 $\left|z_n+\delta_n\right| << \left|z_n\right|$ and corrected by picking a better reference.
This is all a bit adhoc and seems to work well, but rigourous numerical analysis proofs are still lacking as far as I know.  There are two arbitrary thresholds (for series vs probe point relative error tolerance, and for glitch detection) which is very unsatisfactory.
Asymptotics
Suppose $M$ iterations are skipped by series approximation, and $N$ iterations are needed in total. The image size is $W \times H$.  Suppose the cost of high precision operations is $K$ times the cost of low precision operations.  Then the cost of the traditional method using high precision for all pixels is $O(K \times N \times W \times H)$.  With perturbation, the cost is $O(K \times N + N \times W \times H)$.  With perturbation and series approximation the cost is $O(K \times N + (N - M) \times W \times H)$.


text:
Q: GROUP BY ordering I have the following query in mysql:
select territory_id, platform_type_id, p.store_url
    from main_itemmaster m
    inner join main_iteminstance i on m.id=i.master_id
    inner join main_territorypricing p on p.item_id=i.id
    inner join main_territorypricingavail a on a.tp_id=p.id
    where imdb_url = 'http://imdb.com/title/tt1576422/'
group by platform_type_id

Which gives me the following:
territory_id    platform_type_id    store_url
US  Amazon  http://www.amazon.com/dp/B00EQIHJAG
PT  ITUNES  https://itunes.apple.com/pt/movie/id582142080

However, I want to do a GROUP BY to return the territory_id="US" first if that exists. How would I do that?
This is one way I tried which looks quite dirty but does work in the version of mysql I'm using:
select * from
(select territory_id, platform_type_id, p.store_url from main_itemmaster m
    inner join main_iteminstance i on m.id=i.master_id
    inner join main_territorypricing p on p.item_id=i.id
    inner join main_territorypricingavail a on a.tp_id=p.id
 where imdb_url = 'http://imdb.com/title/tt1576422/'
 order by territory_id='us' desc
) x group by platform_type_id

Which gives:
territory_id    platform_type_id    store_url
US  Amazon  http://www.amazon.com/dp/B00EQIHJAG
US  ITUNES  https://itunes.apple.com/us/movie/id582142080

Which is the correct result set I'm looking to get.
Here is a link to a SQL fiddle. I condensed all the data into one table to focus on the GROUP BY statement: http://sqlfiddle.com/#!9/81c3b6/2/0

A: So from the comments and the addition of the SqlFiddle it actually seems like you want to create a partitioned row number with a precedence on US per platform and then select the first record.  One way of doing partitioned Row Numbers in mysql is to use variables here is an example:
SELECT
  territory_id
  ,platform_type_id
  ,store_url
FROM
( SELECT
    *
    ,@PlatFormRowNum:= IF(@prevplatform = platform_type_id, @PlatFormRowNum + 1, 1) as PlatformRowNum
    ,@prevplatform:= platform_type_id
  FROM
    main_itemmaster m
    CROSS JOIN (SELECT @prevplatform:='',@PlatFormRowNum=0) var
  ORDER BY
    platform_type_id
    ,CASE WHEN territory_id = 'US' THEN 0 ELSE 1 END
    ,territory_id
) t
WHERE
  t.PlatformRowNum = 1
ORDER BY
  t.platform_type_id

SQL Fiddle: http://sqlfiddle.com/#!9/81c3b6/12
Basically this partitions the row number by platform, orders US before any other territory and then selects the first row foreach platform.  The one question/trick is how do you choose which to return when US is not available for the platform simply the ascending alphabetical order of the territory_id?


text:
Q: What should I do to merge multiple pdf files in react native? I want to merge multiple pdf files into one. But I can not see any packages in react-native to meet this purpose.
However, I have got a package named "pdf-merger-js," though this is for reactjs. What should I do to merge multiple pdf files in react native?

A: There are multiple packages out there which can help you to achieve what you are looking for.
so as a recap you need to read the pdf file(s) and then mix them together or also add a new one which is written by yourself.
the following package helped me at the time to achieve what i wanted.
https://github.com/Hopding/react-native-pdf-lib


text:
Q: Newman(Postman) - Import collection from a URL under windows authentication I'm trying to run newman with postman collection from a url as mentioned in this link .
newman run http://localhost:62254/api/postman

Only catch is that the url is under windows authentication, so I'm getting a 401 Unauthorized response, causing newman to fail with below error.
the url "http://localhost:62254/api/postman" did not provide valid JSON data

I tried passing the credentials with the request like below. But it didn't work.
http://username:password@localhost:62254/api/postman
If I directly hit the endpoint with Postman using 'NTLM Authentication' feature it works fine. But I'm not sure if I can use this with newman to get the collection itself.

A: We were not able to find any option in Postman/Newman. So finally we made this URL alone (http://localhost:62254/api/postman) open to Anonymous Authentication in the web server.


text:
Q: How to make the range an variable? I want to make the range as an number according to my last row calculation but I can't find a way to do it.
Please refer below for the double asterisk.
Sub TestVBA()
    OptimizeVBA True
    Dim startTime As Single, endTime As Single
    startTime = Timer

    Dim testnames As Range, testvalues As Range
    Dim lookupTestNames As Range, lookupTestValues As Range
    Dim vlookupCol As Object

    Dim lastRow As Long
    Dim lCol As Long

    'Dim LastLine As Long
    'LastLine = Range("A" & Rows.Count).End(xlUp).Row

    'Find the last non-blank cell in column A(1)
    lastRow = Cells(Rows.Count, "A").End(xlUp).Row

    'Find the last non-blank cell in row 1
    lCol = Cells(1, Columns.Count).End(xlToLeft).Column

    'Set testnames = Worksheets("Data Analysis").Range("C8:C399")
    **Set testnames = Worksheets("Data Analysis").Range("C8:C&lastRow")**
    Set testvalues = Worksheets("Data Analysis").Range("O8:O399")
    Set lookupTestNames = Worksheets("Graph").Range("A5:A172")
    Set lookupTestValues = Worksheets("Graph").Range("T5:T172")

    'Build Collection
    Set vlookupCol = BuildLookupCollection(testnames, testvalues)

    'Lookup the values
    VLookupValues lookupTestNames, lookupTestValues, vlookupCol
    endTime = Timer
    Debug.Print (endTime - startTime) & " seconds have passed [VBA]"
    OptimizeVBA False
    Set vlookupCol = Nothing
End Sub

A: You have lastRow inside of double quotes.
Incorrect
Set testnames = Worksheets("Data Analysis").Range("C8:C&lastRow")
Correct
Set testnames = Worksheets("Data Analysis").Range("C8:C" & lastRow)


text:
Q: adjust the content inside the width i have created a tooltip the data its showing is getting overflowed. so want to fit the content inside the width of the tooltip. its more of the badge on hover i need to show the content also we can have a max width of 500px and height no restrictions. Also you could see that on hover the tooltip is not coming exactly down of the respective item on which it is hovered. This is what i have tried, below is my code

 .lightgrey-badge {
width: auto;
height: 20px;
padding: 0px 8px 0px 8px;
border-radius: 4px;
background-color: #f2f2f2;
  }
  .lightgrey-badge-text {
font-size: 12px;
font-weight: 600;
text-align: center;
color: #595959;
vertical-align: middle;
  }
.border {
  border-radius: 20px;
  border: solid 2px #595959;
}

.lightgrey-badge-text-elipses {
  display: inline-block;
  max-width: 40px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tooltiptext {
  visibility: hidden;
  max-width: 250px;
  height: 50px;
  opacity: 0.6;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.04);
  background-color: #000000;
  color: #ffffff;
  text-align: center;
  border-radius: 6px;
  position: absolute;
  z-index: 9999;
  margin-top: 28px;
  margin-left: -150px;
}

.tooltiptext::after {
  content: "";
  position: absolute;
  bottom: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent transparent black transparent;
}

.lightgrey-badge:hover .tooltiptext {
  visibility: visible;
}

        Element

             this s the dummy data the orifinal will look something like this a big long test.i have created a tooltip the data its showing is getting overflowed. so want to fit the content inside the width of the tooltip

A: Try this code It will help you

  .tooltip {
    position: relative;
    display: inline-block;
    border-bottom: 1px dotted black;
  }

  .tooltip .tooltiptext {
    visibility: hidden;
    background-color: black;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 5px 0;
    /* Position the tooltip */
    position: absolute;
    display: block;
    z-index: 1;
  }

  .tooltip:hover .tooltiptext {
    visibility: visible;
  }
<!DOCTYPE html>

Move the mouse over the text below:

Hover over me
    Tooltip text

Hover over me Hover over me
    blah bla blaa a bal  blak a ba b alj ang

Hover over me Hover over me 3
    askdjf ksfjlskd flsaa flsjdlfj sdfk sadkjflskd af sdkjf lsdkf sdljf

Verify my answer if it's work for you

A: The reason for the element is not in the proper width is that it should increase the max-width. I changed the max width to 50px. it was at 40px
.lightgrey-badge-text-elipses {
  max-width: 50px;
}

I added a min-width, max-width and padding for the long text as follows
.tooltiptext {
  min-width: 100px;
  max-width: 500px;
  padding-left: 100px;
  padding-right: 50px;

}

You can break the lines of the paragraph to get the long text in different lines so you can see the entire thing. Like this
 this s the dummy data the orifinal will look something like this a big long test.i have created a tooltip the data its showing is getting overflowed. so want to fit the content inside the width of the tooltip

You will have to add a class in the css too.
.new-content {
  white-space: pre-wrap;
}


text:
Q: how to fetch Facebook Audience Network Reporting API Version 2 programmatically and automatically? Facebook Audience Network Reporting API Version 2 only support Facebook Login to fetch token, see here https://developers.facebook.com/docs/audience-network/optimization/report-api/guide-v2#login

here I want to ask how to make this programmed (automatically)? I no need to open browser, login facebook manually to create token very three months? I think it is so inconvenient.


text:
Q: Writing foreign characters to .json file, eclipse vs jar Using eclipse IDE to for tests on writing data to .json and .txt files with few foreign(Chinese, Hindi) characters using Java. I could successfully write into .txt where as .json displayed ascii characters.
Code Snippet:
try(BufferedWriter br = new BufferedWriter(new FileWriter(new File("test.json")))) {
            JSONObject obj = new JSONObject();
            obj.put("key", "Hello, ओ ो ु ऋ 样品");
            String str = obj.toJSONString();
            System.out.println(str);
            br.write(str);
            br.close();
} catch (Exception e) {
        e.printStackTrace();
}

Output of .txt: {"key":"Hello, ओ ो ु ऋ 样品"}
Output of .json: {"key":"Hello, ओ ो � ऋ 样�"}
Have tried using DataOutputStream to write data. But the result is same.
On decoding, it worked to decode back as same foreign character and looks good.
On building a jar, and running the same as .jar file doesn't give same results. Writing and Reading both were displayed in ascii. Yes, I understand in eclipse the file is saved as utf-8, which helped to compile. By the way I'm using maven to build the jar.
Please help me with the wayout a solution. Thanks.


text:
Q: Local mollifier for part of a function Given $u\in W^{1,2}(\mathbb{R}^n)$ and a smooth bump function $\eta\in C^\infty(\mathbb{R}^n)$ with $\eta(x)=0$ for $||x||\ge 1$, the mollified functions $u_\epsilon \in C^\infty(\mathbb{R}^n)$ for each $\epsilon>0$ given by $u_\epsilon(x):=\int_{\mathbb{R}^n} u(y) \eta\left(\frac{||y-x||}{\epsilon}\right)dy$ satisfies $\lim_{\epsilon\to 0} ||u_\epsilon-u||_{L^2(\mathbb{R}^n)} = 0$ and
$$||\,|\nabla u_\epsilon|\,||_{L^2(\mathbb{R}^n)} \le ||\,|\nabla u|\,||_{L^2(\mathbb{R}^n)}.$$
I want to construct another function $\hat{u}_\epsilon$ which is a "local mollification" of $u$. That is, given open sets $\Omega_1,\Omega_2\subset \mathbb{R}^n$ with $\overline{\Omega_1} \cap \overline{\Omega_2}=\emptyset$, I want to construct , with the following properties:

*

*$\hat{u}_\epsilon$ is smooth inside $\Omega_1$,

*$\hat{u}_\epsilon=u$ inside $\Omega_2$,

*$\lim_{\epsilon\to 0} ||u_\epsilon-u||_{L^2(\mathbb{R}^n)} = 0$,

*$||\,|\nabla \hat{u}_\epsilon|\,||_{L^2(\mathbb{R}^n)} \le ||\,|\nabla u|\,||_{L^2(\mathbb{R}^n)}$.

Is this possible for all such $u$? Is there an explicit construction for $\hat{u}_\epsilon$?


text:
Q: Bootstrap 3.1 affix scroll-spy content staying visible when using overflow I am implementing a table of contents (TOC) in sidebar using bootstrap 3.1 and scroll-spy.  It generally works great, but sometimes I have enough page content that the TOC gets too long to present entirely in the viewport.  So I tweaked the height to be 100% with overflow-y: 100% so the user can still at least scroll entire TOC.
However, as user scrolls down the page, the highlighted element "scrolls' off the TOC's visible view, so the question is, how can I scroll the TOC contents along with the page once the user has scrolled sufficiently far down the page that highlighting in the TOC is no longer visible?

Example

Example 2

A: Easiest way to do this it install jquery pluging animatescroll:  http://plugins.compzets.com/animatescroll/ and then use the following:
$('#sidebar').on('activate.bs.scrollspy', function () {
  item = $('#toc').find(".active").first();
  item.animatescroll({element: '#toc', padding:20});
});

This will keep the active table of contents row visible.  the activate.bs.scrollspy is fired every time a new item becomes active and the animatescroll call moves it to (in this case) 20px from top.


text:
Q: Django, can I get reference objects included with a queryset Say I have these models:
models.py:
class Item(models.Model):
    ref_id = models.PositiveIntegerField()
    name = models.CharacterField(max_length=32)

class ItemDue(models.Model):
    item = models.ForeignKey(Item)
    due_date = models.DateField(null=True, blank=True)
    lots of other fields below
    .
    .
    .

I want to query the ItemDue objects but want to also include the Item with the query.
If I get a set of ItemDues I can loop like this:
for item_due in ItemDue.objects.filter(some_criteria):
    print item_due.item.ref_id

However, when I did some performance tests, this is going back to the database to get the referenced Item object, so I have to run another query for each ItemDue to get the Item.ref_id. This makes a difference in a huge query, so I want to get the Item.ref_id along with the queryset to get the ItemDues. I can do .values('id', 'item__ref_id') to get a dictionary of the ItemDue with the id and item__ref_id. So, I could use .values('id', 'item__ref_id', ...) for all fields in ItemDue but that would be a lot of work. Is there a simple way I can append to the values of a queryset to get that reference object, without spelling out ALL the fields in the ItemDue along with just the one extra field item__ref_id?
Thanks
EDIT:
Here is some code run in the manage.py shell:
def check():
    start = datetime.now()
    print "Starting {0}".format(datetime.now() - start)
    index = 0
    item_rows = dict()
    print "Getting Items for PG and Parents {0}".format(datetime.now() - start)

    # items due for PG
    items = pg.item_due.all().filter(disabled=False).select_related()

    # Loop the parents, and chain their items due to the PG items due.
    for p in parents:
        items = itertools.chain(items, p.item_due.all().filter(disabled=False).select_related())
        index += 1
    print "All Items Retrieved {0}".format(datetime.now() - start)
    for item in items:
        pass
    print "Loop Items Complete {0}".format(datetime.now() - start)
    return item_rows

>>> rows = check()
Starting 0:00:00.000008
Getting Items for PG and Parents 0:00:00.000032
All Items Retrieved 0:00:00.004669
Loop Items Complete 0:00:00.022597

Notice the time it takes to loop the items and just pass is about .018 seconds.
Now I simply change the pass in the loop to item.item.ref_id and it takes a LOT longer.
def check():
    start = datetime.now()
    print "Starting {0}".format(datetime.now() - start)
    index = 0
    item_rows = dict()
    print "Getting Items for PG and Parents {0}".format(datetime.now() - start)

    # items due for PG
    items = pg.item_due.all().filter(disabled=False).select_related()

    # Loop the parents, and chain their items due to the PG items due.
    for p in parents:
        items = itertools.chain(items, p.item_due.all().filter(disabled=False).select_related())
        index += 1
    print "All Items Retrieved {0}".format(datetime.now() - start)
    for item in items:
        item.item.ref_id
    print "Loop Items Complete {0}".format(datetime.now() - start)
    return item_rows

>>> rows = check()
Starting 0:00:00.000007
Getting Items for PG and Parents 0:00:00.000031
All Items Retrieved 0:00:00.004712
Loop Items Complete 0:00:00.258209

From .018 seconds to run the loop to .25 seconds. Why does it take 13 times the time just to process the item.item.ref_id if it is getting it from the query already?

A: Use select_related to get related tables data in one query:
for item_due in ItemDue.objects.filter(some_criteria).select_related():
    print item_due.item.ref_id


text:
Q: How to place PlotLabel inside the plot frame I have the following plot:
dibA1 = Show[Plot[{PDF[eϕ1rand, x], PDF[eϕ1fps, x], PDF[eϕ1grad, x], PDF[eϕ1rank, x]},
      {x, 0, 1200},
      Frame -> True,
      Filling -> None,
      PlotLegends -> Placed[{"No Stigmergy", "FPS", "Gradient", "Rank"}, {0.85, 0.7}],
      FrameLabel -> {"Minutes", "Probability"},
      AspectRatio -> 0.8,
      LabelStyle -> {FontFamily -> "Times", 12},
      PlotRange -> {{0, 100}, All},
      PlotStyle ->
        {Directive[Thick, Opacity[0.45], {Black}, Dashing[{0.045, 0.020}]],
         Directive[Thick, Opacity[0.75], {Red}],
         Directive[Thick, Opacity[0.75], {Blue}, DotDashed],
         Directive[Thick, Opacity[0.75], {Green}, Dashing[{0.025, 0.014}]]},
      PlotLabel -> "Event 1"],
      ImageSize -> 600]

I would like to place it in the same relative position but into the plot frame. I have been testing
Epilog -> Text[Style["Event1", 12], {0, -1}]

in different parts of the code and trying other text positions but I can not see any text into the plot frame.
How can I get to see the text "Event1" into the frame and determine its location?

A: Legended[Plot[x Cos[x] Sin[x], {x, 0, Pi}, Frame -> True],
 Placed[Style["Event 1", Red, Bold, 20], {Center, Top}]]

Use Placed[Style["Event 1", Red, Bold, 20], {.7, .9}] to get

A: Use scaled coordinates Scaled[{x,y}] for easier control. Scale runs $0<(x,y)<1$ independently of actual axes values, therefore not only it is easier to control, but also if you ever change the plot so axes values change,  Scale will faithfully keep your text in the originally specified location relative to the Frame. Remember Style works in Text and hence in Epilog. Also next time your ask a question try to give a minimal code example, no need to overload the question with irrelevant code.
Plot[Cos[x^2],{x,0,Pi},
    Frame->True,
    Epilog->Text[Style["Hey There",Red,Italic,20],Scaled[{.5,.9}]]]


text:
Q: Unexpected behaviour of Nothing inside List inside Association When evaluating the following input:
<|a -> {c, d, e}|> /. d -> Nothing

I get (expression 1):
<|a -> {c, Nothing, e}|>

However I would expect to get (expression 2):
<|a -> {c, e}|>

Nevertheless, if i place the cursor on the unexpected output (expression 1) and evaluate it by pressing Shift + Enter, I get the expected output (expression 2), which is even more puzzling.
Mathematica version is 11.0.0.0
Should this behaviour be expected or is it a bug? Why?

A: The observed puzzle is resolved by the following two observations:
From Leonid's answer in the linked q/a:

*

*Association is HoldAllComplete. Once it is created, its parts will then normally be held unevaluated.

From Nothing>> Details

*

*Nothing is removed as part of the standard evaluation process. It is not removed in expressions that are held or inactive.

You can Map ReplaceAll on the association to force removal of Nothings:
ReplaceAll[d -> Nothing] /@ assoc (* or *)
Map[# /. d -> Nothing &]@<|a -> {c, d, e}|>

<|a -> {c, e}|>

A: Use Replace with level spec All rather than ReplaceAll:
Replace[<|a -> {c, d, e}|>, d -> Nothing, All]

<|a -> {c, e}|>

Related: Is there a difference between Replace with parameter "All" and ReplaceAll

A: Pattern matching to a function evaluation inside an Association answers your question about bug vs expected result.
This will not do what your input suggests but let me anticipate your needs:
<|a -> {b, c, d}, e :> {d, Print[1], d}, f -> d|> //.
  {a___, d, b___} :> {a, b} /. (*this way Print is not evaluated*)
  d -> Nothing

<|a -> {b, c}, e :> {Print[1]}, f -> Nothing|>

A: For completeness sakes (I believe Coolwater's answer is best):
assoc = Association[ a → {c,d,e} ];

Query
assoc // Query[ All, ReplaceAll[ d → Nothing ] ]

(* <|a -> {c, e}|> *)

Note:  This will need repeated use of All for nested associations.
DeleteCases
Before there was Nothing there was DeleteCases and the like:
assoc // DeleteCases[ #, d, Infinity ]&

(* <|a -> {c, e}|> *)

A: You may use Query to evaluate the result of the replace in an Association. Query gives direct access to the key's value which then evaluated in Query.
Query[All, # /. d -> Nothing &]@<|a -> {c, d, e}|>

<|a -> {c, e}|>

Hope this helps.


text:
Q: can't prevent dragging page when touch and drag on input field jquery mobile phonegap ios i prevented from scrolling my cross platform app adding
document.addEventListener('touchmove', function(e) { e.preventDefault(); }, false);

on device ready function.
Everything works good except for input fields: when i tap on input fields and drag the page down, i can move the entire window down and see a black screen.
Any idea on how to prevent scrolling when gesture start from inside an input field?

A: Setting UIWebViewBounce to NO should fix this.
Your project > Resources > Cordova.plist > set:
UIWebViewBounce Boolean NO


text:
Q: How to Consume SOAP WSDL Using Vertx 3 i have a project in vertx.3, i wanna to consuming a SOAP service.
is there a lib in vertx that allow me to do that?
i do a lot of search and i get anything.
please some one can help me!

A: There is no SOAP module in the Vert.x stack. That being said, you can craft SOAP messages in XML yourself, also by reading the WSDL descriptor if any.
For sure this is not an ideal solution, but it is doable.
Another option is to use the Vert.x Camel Bridge and have Camel / SOAP do the endpoint adaptation for you.


text:
Q: How to map a List to a ModificationMapping SP for Insert in EF4? I have an entity with
Entity
{
    int Id;
    object otherProperties;
    List<int> ForeignIds;
}

I have written an Insert SP that takes:
@Id INT,
@ForeignId INT

How can I map a List to a SP for Insert for a Modification Mapping that would insert a row with the Id and an element from ForeignIds for each element in ForeignId?
E.g.
Entity(){ id=1; ForeignIds = new List<int>(){2,3};}

Would insert:
Id | ForeignId
1 | 2
1 | 3

A: You cannot map this. EF doesn't understand List of scalar types. You must manually iterate the list and execute stored procedure for each item in the collection. You can map the procedure as function import or execute it directly by objectContext.ExecuteStoreCommand.


text:
Q: updating google maps marker from a broadcast sms receiver I am a newbie to android and java. I am trying to make an application to perform following task.

*

*receive incoming sms (which will have latitude and longitude information)

*show them on map with markers
So every time an sms comes map should get a new marker.

currently I have a map where I can show a point and I have implemented a broadcast receiver to get lattitude and longitude form SMS.
But I am unsure how to update the map from broadcast receiver on receiving a new sms.
Any help or tips will be useful.
Thank you

A: There are 3 items you need to address:
A. Receive an SMS via a BroadcastReceiver
B. Annotating a MapView using an ItemizedOverlay
C. Communicate the updates from the BroadcastReceiver to the activity showing the map
 Item A: Receive SMS

*

*Implement your BroadcastReceiver class:
public class SMSBroadcastReceiver extends BroadcastReceiver
{
    private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent)
    {
        if (intent.getAction().equals (SMS_RECEIVED))
        {
            Bundle bundle = intent.getExtras();
            if (bundle != null)
            {
                Object[] pdusData = (Object[])bundle.get("pdus");
                for (int i = 0; i < pdus.length; i++)
                {
                    SmsMessage message = SmsMessage.createFromPdu((byte[])pdus[i]);

                    /* ... extract lat/long from SMS here */
                }
            }
        }
    }
}

*Specify your broadcast receiver in the app manifest:
<manifest ... >
        <application ... >
                <receiver
                        android:name=".SMSBroadcastReceiver"
                        android:enabled="true"
                        android:exported="true">
                        <intent-filter>
                                <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
                        </intent-filter>
                </receiver>
        </application>
</manifest>

(Credits go to the posters in this thread: Android - SMS Broadcast receiver)
Item B: Annotate the Map

*

*Create a class derived from ItemizedOverlay, which is used to inform a MapView of any markers which need to be displayed:
class LocationOverlay extends ItemizedOverlay<OverlayItem>
{
        public LocationOverlay(Drawable marker)
        {
                /* Initialize this class with a suitable `Drawable` to use as a marker image */

                super( boundCenterBottom(marker));
        }

        @Override
        protected OverlayItem createItem(int itemNumber)
        {
                /* This method is called to query each overlay item. Change this method if
                   you have more than one marker */

                GeoPoint point = /* ... the long/lat from the sms */
                return new OverlayItem(point, null, null);
        }

   @Override
   public int size()
   {
                /* Return the number of markers here */
                return 1; // You only have one point to display
   }
}

*Now, incorporate the overlay into an activity that displays the actual map:
public class CustomMapActivity extends MapActivity
{
    MapView map;
    @Override

        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            /* We're assuming you've set up your map as a resource */
            map = (MapView)findViewById(R.id.map);

            /* We'll create the custom ItemizedOverlay and add it to the map */
            LocationOverlay overlay = new LocationOverlay(getResources().getDrawable(R.drawable.icon));
            map.getOverlays().add(overlay);
        }
}

Item C: Communicate the updates
This is the trickiest part (see also Updating an Activity from a BroadcastReceiver). If the app's MapActivity is currently visible, it needs to be notified of the newly received markers. If the MapActivity isn't active, any received points need to be stored somewhere until the user chooses to view the map.

*

*Define the private intent (in CustomMapActivity):
private final String UPDATE_MAP = "com.myco.myapp.UPDATE_MAP"

*Create the private BroadcastReceiver (in CustomMapActivity):
private  BroadcastReceiver updateReceiver =  new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        // custom fields where the marker location is stored
        int longitude = intent.getIntExtra("long");
        int latitude = intent.getIntExtra("lat");

        // ... add the point to the `LocationOverlay` ...
        // (You will need to modify `LocationOverlay` if you wish to track more
        // than one location)

        // Refresh the map

        map.invalidate();
    }
}

*Register your private BroadcastReceiver when the activity is started (add this to CustomMapActivity.onCreate):
IntentFilter filter = new IntentFilter();
filter.addAction(UPDATE_MAP);
registerReceiver(updateReceiver /* from step 2 */, filter);

*Invoke your private intent from the public BroadcastReceiver (add this to SMSBroadcastReceiver.onReceive):
Intent updateIntent = new Intent();
updateIntent.setAction(UPDATE_MAP);
updateIntent.putExtra("long", longitude);
updateIntent.putExtra("lat", latitude);
context.sendBroadcast(updateIntent);

A: It sounds like you are looking for detail on how to communicate between your Activity and the BroadcastReceiver? One approach (there are many different approaches) is to have your map Activity register a temporary BroadcastReceiver that is setup to only listen to private broadcasts from your app, and then have your SMS broadcast receiver generate a new broadcast with the latitude/longitude from the SMS. In your map Activity your receiver will add a new point to the map every time it receives a new private broadcast.


text:
Q: How do I remove the /view in the url of my view page I developed my site jobgurus.com.ng with codeigniter. For SEO purpose, How do I change the view page url form www.jobgurus.com.ng/jobs/view/system-support to www.jobgurus.com.ng/jobs/system-support
I want to remove the /view in the url.
Any help will appreciated. Thanks

A: You can try using the following code in your .htaccess file:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteRule ^view/(.*)$ /$1 [L,NC,R]

Explanation of the flags used:
L  -> Last
NC -> No case comparison
R  -> Redirection

Note: The default code for redirection is 302. You can change it to 301 of you want that by setting: [L,NC,R=301].

A: If job is your controller name and view is your method, You can use route of CI.
Add below line in file application/config/routes.php
 $route['job/(:any)'] = 'job/view/$1';

you can list similarly all possible links there.


text:
Q: How to reuse a single JavaScript in both server and client components of G Suite Add-on? I have a JavaScript file that's a generated parser (let's call it MyParser), which I am using in an add-on for Google Forms.
It needs to be used in the client side's Sidebar.html where I'm including it with HtmlService.createHtmlOutputFromFile('MyParser.js').getContent();, which means it must be an .html file as far as I understand. Then it must be used on the server side where I have it in a file MyParser.js.gs.
With my current solution, it's duplicated in my file structure:
Code.gs
MyParser.js.gs
MyParser.js.html
Sidebar.html

Is there a way I can make this work without having two files? Edit: As I understand it, libraries are only for the server side.
If not, any hints to making the updating of the two files more robust (currently it's manual copy/paste)?
Edit: According to the best practices, one must wrap the JavaScript inside a "; } > MyParser.js.html

Since I'm using bash it's not a true node.js solution (won't run unless there's bash installed). If someone knows of a better way to pull off the wrapping that's 100% node and doesn't require installing a whole bunch of other modules, feel free to edit the answer.

A: As your add-on has just few files you might use ScriptApp.getResource(filename).getDataAsString() to get the content of a .gs file and add it to the sidebar HttpOutput object enclosed in `);
  SpreadsheetApp.showSidebar(htmlOutput,'My Sidebar');
}

JavaScript.gs
To keep things simple, this file should contain only reusable (server-side + cliente-side) JavaScript
function myFunction(){
  console.log('My function ran successfully');
}

The above over simplistic code example might be applied to a bit more complex projects and will keep you away from having to use CLASP.
Contrary as happens with .gs and .html files, so far I was unable to make ScriptApp.getResource(filename).getDataAsString() to work to pull reusable JavaScript from .gs files hosted on a Google Apps Script library. Anyway, it's still possible to stay away of CLASP, one option might be to use Advanced Service Google Apps Script API, another might be to host the shared JavaScript and imported from Google Drive or from another host by using Url Fetch service.
Related

*

*Is it possible to read the contents of a Google Apps Script from another Script

*HTML and JavaScript from another server?

*Server side HTML Form validation?


text:
Q: Is this proper behavior? std::map iterator invalidation #include <iostream>
#include <map>

int main(int argc, char** argv)
{
  std::map<int, int> map;
  map.emplace(1, 1);
  auto reverse_iter = map.rbegin();
  std::cout << reverse_iter->first << ", " << reverse_iter->second << std::endl;
  map.emplace(2, 2);
  std::cout << reverse_iter->first << ", " << reverse_iter->second << std::endl;

  return 0;
}

This prints out:
1, 1
2, 2

Is this really what's supposed to happen, according to the standard?  I'm not touching reverse_iter but the value it's pointing to is changing. I thought iterators in std::map were supposed to be safe against insertion. Yet it seems to be deciding that reverse_iter is not to stay pointing to the value I told it to, rather to "whatever happens to be at the end of the map at this point in time".
Update: further info, in case it matters: this doesn't seem to happen with forward iterators (in any situation I can seem to find), and my gcc version is 5.1.1-4.

A: According to the C++ Standard (23.2.4 Associative containers)

9 The insert and emplace members shall not affect the validity of
  iterators and references to the container, and the erase members shall
  invalidate only iterators and references to the erased elements.

On the other hand (24.5.1 Reverse iterators)

1 Class template reverse_iterator is an iterator adaptor that iterates
  from the end of the sequence defined by its underlying iterator to the
  beginning of that sequence.

Though in the last quote there is said about class std::reverse_iterator the same is valid for reverse iterators of standard containers.
According to  Table 97 — Reversible container requirements
rbegin() corresponds to reverse_iterator(end())
So in your example the reverse iterator still corresponds to end().
`

A: As quoted here http://en.cppreference.com/w/cpp/container/map/rbegin

Reverse iterator stores an iterator to the next element than the one it actually refers to

the side effect would be that if you insert something before that iterator (incliding end()) you will see that new value when you dereference that reverse iterator. I do not think that reverse iterator is invalidated in this case.

A: map.rbegin() returns an iterator that is equal to std::reverse_iterator(map.end());
The problem arises when you dereference a reverse iterator. When you dereference a reverse_iterator the value you actually get is from the iterator before the one is stored inside the reverse_iterator. That might seem strange, but is there for good reasons, and it's unavoidable.  This is so, in order to arrange for the past-the-end element of a range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the first element in a range is reversed, the reversed iterator points to the element before the first element (this would be the past-the-end element of the reversed range).
That is, in your case when dereferencing the reverse_iter is equivalent with doing:
*(--map.end());

Consequently, after the second emplace the last element of the map has changed and dereferencing (--map.end()) (i.e., your reverse_iter) you get the new last element in the map.

A: std::map<int, int> map2;
map2.emplace(2, 2);
auto fiter = map2.begin();
std::cout << fiter->first << ", " << fiter->second << std::endl;
map2.emplace(1, 1);
std::cout << fiter->first << ", " << fiter->second << std::endl;
fiter = map2.begin();
std::cout << fiter->first << ", " << fiter->second << std::endl;

prints
2, 2
2, 2
1, 1


text:
Q: How to draw normal vector in Mathematica? Question
If I have plane equation $x+y+z=0$, then normal vector is $\{1,1,1\}$. Why is it not normal visually?  How can I draw it properly?
Code
p1 = Plot3D[-x-y, {x,-1,1},{y,-1,1}];
p2 = Graphics3D[Line[{{0,0,0},{1,1,1}}]];
Show[p1,p2]

Output

A: I see a black line from $(0,0,0)$ to $(1,1,1)$
The reason it does not appear to be orthogonal to the brown plane is the scale of the vertical axis not matching the scales of the other two axes either in range or in size.  Stretch it and it looks better


text:
Q: vector.push_back(B) and vector.push_back(new A((*B))), why not act as the same? I have these two classes:
class A
{
public:
    A();
    virtual ~A();

    virtual void TellMyName();
};

class B : public A
{
private:
    std::string szName;
public:
    B();
    ~B();

    void TellMyName();

    void SetName(std::string val){ szName = val; }
};

And this is my code:
void main()
{
    std::vector<A*> List_A;

    B* B_Instance = new B();
    B_Instance->SetName("B");

    List_A.push_back(B_Instance); // Way 1
    List_A.push_back(new A((*B_Instance))); // Way 2

    List_A[0]->TellMyName();
    List_A[1]->TellMyName();
}

TellMyName() is just going to prompt a message box. If I use "Way 1" there is no problem with it, but if I use "Way 2" it would prompt the message with no text and that means all members of the B class are empty like they're never being filled with anything. I solved this with the use of std::shared_ptr, but is there any other way to not use smart pointers because I have to implement this approach in a big project and there would be a lot of change and failure. And by the way, what's the cause to "Way 2"?

A: List_A.push_back(new A((*B_Instance))); // Way 2

This line is not doing what you think it is.
You are creating a new instance of the class "A" on the heap by calling the default copy constructor generated by C++. That copy constructor uses the instance of B (treated as though it were an instance of A) and does a field-by-field copy, which in this case, does nothing.
You're essentially creating an empty instance of A and pushing it onto the list.
As many have mentioned, the formal term for this is called object slicing.

A:
that means all members of the B class are empty like they're never being filled with anything

No. it doesn't mean they're empty.  To be empty, they'd have to be there in the first place.
List_A[1]->TellMyName(); performs dynamic dispatch and ends up calling A::TellMyName, because class A is the actual type of the object.  Members of the B class don't even exist.
You've run into the slicing problem.

A: std::vector<A*> List_A;
// ...
List_A.push_back(new A((*B_Instance))); // Way 2

You are suffering from a form of Object Slicing, sort of.
Object slicing happens when you instantiate (or assign) a base class with the values from a derived type, and lose -- or "slice off" -- all the stuff that was unique to the derived class.
Above, you are instantiating a new A, rather than a new B.  But since B is derived from A, you can simply instantiate a new B and cast the returned pointer to an A*:
List_A.push_back(new B(*B_Instance)); // Way 2

All of this being said, as an aside I would strongly advise you to consider refactoring your code to use smart pointers.

A: You should be calling
List_A.push_back(new B((*B_Instance)));

As B inherits from A it can also be added to the list, but as the copy constructor of B will also copy all fields in B, it will work.
Calling A's copy constructor doesn't copy the fields in B, as A doesn't "know" about B's fields.


text:
Q: How to test if PyObject has an iterator I am implementing a C function as an extension for Python. Inside abstract.h, I found the following:
/* ==== Iterators ================================================ */

/* Takes an object and returns an iterator for it.
   This is typically a new iterator but if the argument is an iterator, this
   returns itself. */
PyAPI_FUNC(PyObject *) PyObject_GetIter(PyObject *);

/* Returns 1 if the object 'obj' provides iterator protocols, and 0 otherwise.

   This function always succeeds. */
PyAPI_FUNC(int) PyIter_Check(PyObject *);

When I try to get iterators using PyObject_GetIter on obviously non-iterable objects like a number, I get the error SystemError: <built-in function xxx> returned a result with an error set.
static PyObject *my_method(PyObject *self, PyObject *args)
{
    PyObject *obj;
    PyArg_ParseTuple(args, "O", &obj)
    //  printf("\ncheck %d",PyIter_Check(obj)); // always 0
    PyObject *iter = PyObject_GetIter(obj); // throws error
    return PyLong_FromLong(0);
}

I would like to handle errors on my own. So I tried to use the PyIter_Check to test if the object has an iterator. However, this function returned 0 for all objects I provided, including the iterable ones.
I thought that it might be caused by the PyAPI_FUNC() macro but I found it in pyport.h and it seems to be only adding __declspec.

*

*Why is the function PyIter_Check returning zero for all objects?

A: PyIter_Check is for checking whether an object is an iterator, not whether it can provide one.  There doesn't appear to be a PyIterable_Check.
Moreover, Python pretty much enforces EAFP: since anything could provide an __iter__ that raises an exception, you have to check for an error from PyObject_GetIter anyway, so the only point of the *_Check functions is to provide early sanity checks (sometimes with better error messages).


text:
Q: sinon stub does not recognise a call to a stub This is the code to test:
    const AWS = require('aws-sdk');
const { APPLICATIONS, NOTIFICATION_FREQUENCIES } = require('./config');

exports.createHandler = ({ notificationService }) => async (event, context) => {

  try{
    Object.values(APPLICATIONS).forEach(async appId => {

      const notifications =  await notificationService
        .getNotificationsByApplication(appId);

      const dailyNotifications =notifications.filter(
        e =>
          e.frequency === NOTIFICATION_FREQUENCIES.DAILY,
      );

      console.log('dailyNo', dailyNotifications);

      const dailyTemplate = notificationService.prepareDailyTemplate(
        dailyNotifications
      );
      console.log('dailyTemplate', dailyTemplate);

      notificationService.notifyToAdmin(dailyTemplate);
    });
  }
  catch(err) {
    console.log(err);
  }

};

And this is my test using sinon:
const sinon = require('sinon');
const { APPLICATIONS, NOTIFICATION_FREQUENCIES } = require('../lib/config');
describe('Daily notifier tests', () => {

  it('should prepare daily template for each of the applications', () => {

    const notificationService = require('../lib/notificationService').createHandler({
      commands: {},
      simpleMailService: {},
    });

    const notifications = [
      {
        type: 'create_order',
        frequency: NOTIFICATION_FREQUENCIES.DAILY,
      },
      {
        type: 'create_order',
        frequency: NOTIFICATION_FREQUENCIES.DAILY,
      },
      {
        type: 'create_order',
        frequency: NOTIFICATION_FREQUENCIES.MONTHLY,
      },
    ];
    const template = 'some html template as string';

    sinon.stub(notificationService, 'getNotificationsByApplication').resolves(notifications);
    sinon.stub(notificationService, 'prepareDailyTemplate').returns(template);
    sinon.stub(notificationService, 'notifyToAdmin');

    const sut = require('../lib/dailyNotifier').createHandler({
      notificationService,
    });

    const event = {};
    const context = {};

    sut(event, context);

    const dailyNotifications = [
      {
        type: 'create_order',
        frequency: NOTIFICATION_FREQUENCIES.DAILY,
      },
      {
        type: 'create_order',
        frequency: NOTIFICATION_FREQUENCIES.DAILY,
      }
    ];

    sinon.assert.calledOnce(notificationService.prepareDailyTemplate);
    sinon.assert.calledWith(notificationService.notifyToAdmin, template);

  });

});

According to sinon the method prepareDailyTemplate is not called at all (0 times), but when I execute the test I can even see the console.log 'dailyTemplate', which means that the method has been executed once.
The error message:
AssertError: expected prepareDailyTemplate to be called once but was called 0 times

What I am doing wrong?

A: sut is an async function created by createHandler so it returns a Promise.
You just need to await the Promise that it returns:
it('should prepare daily template for each of the applications', async () => {  // <= async

  // ...

  await sut(event, context);  // <= await

  // ...

  sinon.assert.calledOnce(notificationService.prepareDailyTemplate);  // Success!
});


text:
Q: How do I get predictions on new data using a fitted statsmodel GLMgam model? After running the code form the example found in the documentation of the GLMgam class of the statsmodel package,
from statsmodels.gam.api import GLMGam, BSplines
from statsmodels.gam.tests.test_penalized import df_autos
df_autos_train = df_autos.iloc[0:165]
df_autos_test = df_autos.iloc[165:205]
x_spline = df_autos_train[['weight', 'hp']]
bs = BSplines(x_spline, df=[12, 10], degree=[3, 3])
alpha = np.array([21833888.8, 6460.38479])
gam_bs = GLMGam.from_formula('city_mpg ~ fuel + drive', data=df_autos_train, smoother=bs, alpha=alpha)
res_bs = gam_bs.fit()
print(res_bs.summary())

I fail to get the prediction
res_bs.predict(exog = df_autos_test[['fuel', 'drive']], exog_smooth = df_autos_test[['weight', 'hp']])

gives me the error
File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 116, in pandas._libs.index.IndexEngine.get_loc
TypeError: '(slice(None, None, None), 0)' is an invalid key


text:
Q: Similar function of ArcGIS Network Analyst in MapInfo I am currently using MapInfo and trying to create a road network base walking catchment map, rather than just a cycle buffer. The finished plan should look similar as follows.

This map was created in ArcGIS with the Network Analyst feature. I wonder whether MapInfo has the similar feature to generate this kind of map? maybe in the latest version v12.

A: Yes, Pitney Bowes offers a similar product.  It's called DriveTime (another link here) and it's an additional program which you can buy.  It's not built into MapInfo, unfortunately.
I've always had Pitney Bowes run the drive times for me.  I've never been terribly impressed with the results, but they did the job.  They were able to provide catchment polygons, like in your image, as well as a line file which contained routes and times between all the points to all other points.
I'm not sure if you have to purchase Pitney Bowes road data for it to work.  Have a look here: http://www.mapinfo.com/data-products/drivetime-routing/
Hope this helps.

A: There is a new tool available, too. Well new in the Pitney Bowes product range. The tool is called MapInfo RouteFinder.
You can see a demo on how to creating catchment area like the ones above here:
https://www.youtube.com/watch?v=8NZDK4R2ZWw.
You can read a bit more about the product in this article from the MapInfo Journal:
http://web.pb.com/mapinfopro-nov-2014/MapInfo-RouteFinder-Using-Isochrones
MapInfo RouteFinder can create networks from tab files holding basic information for routing.
Pitney Bowes also sell networks based on the TomTom road network, including travel speed at morning rush hour, evening rush hour, between rush hours and during the weekend.
You might have heard about RouteFinder before. RouteFinder for MapInfo is a tool developed by RouteWare. Pitney Bowes has entered into an agreement with RouteWare to create our own "MapInfo RouteFinder" version of their product.


text:
Q: Return to current page on INPUT result in Struts 2 I have an <s:form> that is present on all pages of my web application.
<s:form action="search" method="post">
    <s:textfield name="query" placeholder="Enter movie title..." cssClass="searchbox" />
    <s:submit type="image" src="images/btn_search.gif" />
</s:form>

Currently, it is redirecting to index.jsp when the validate() method of SearchAction class results to input.
<action name="search" class="com.mypackage.action.SearchAction">
    <result>/search-result.jsp</result>
    <result name="input">/index.jsp</result>
</action>

SearchAction:
public class SearchAction extends ActionSupport implements RequestAware, Message {
    private static final long serialVersionUID = 1L;

    private Map<String, Object> request;

    private String query;

    @Override
    public String execute() throws Exception {
        // business logic
        request.put("searchResults", searchResults);

        return SUCCESS;
    }

    @Override
    public void validate() {
        if(getQuery().length() == 0) {
            addFieldError("query", BLANK_SEARCH);
        }
    }

    @Override
    public void setRequest(Map<String, Object> request) {
        this.request = request;
    }

    public String getQuery() {
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }
}

Output:

It works, but it seems unnatural for the user to return to index.jsp every time the parameter is invalid (i.e. blank).
My goal is to keep the user on the current page when the Please enter... message appears.
Questions:

*

*How do I get the current page, where the action was called?
(For example, a visitor used the search while at the Log In page, how do I
get login.jsp from the address bar?)

*How do I make this current page the location at
<result name="input">/currentpage</result>?

A: You can get the current page name using following code:
String actionName = ServletActionContext.getRequest().getHeader("Referer");

In Struts.xml, use a dynamic result such as:
<result name="input" type="redirect">${url}</result>

In the action, use getter method for url. By default set the value of url as "index.jsp". If you want to change it, set appropriate value for url. Like login.jsp etc.

A: The current page you can get via servlet request. Create interceptor for intercepting a current page
public class CurrentPageInterceptor extends AbstractInterceptor {

  @Override
  public String intercept(ActionInvocation actionInvocation) throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    Map<String, Object> session = actionInvocation.getInvocationContext().getSession();
    String queryString = request.getQueryString();
    String savedUrl = request.getRequestURI()+(queryString==null?"":("?"+queryString));
    String currentPage = (String) session.get("savedUrl");
    if(currentPage == null) currentPage = savedUrl;
    session.put("currentPage", currentPage);
    session.put("savedUrl", savedUrl);
    return actionInvocation.invoke();
  }
}

Registering interceptor in the parent package
<interceptors>
  <interceptor name="currentPage" class="com.company.interceptor.CurrentPageInterceptor"/>
  <interceptor-stack name="curentPageStack">
    <interceptor-ref name="currentPage"/>
    <interceptor-ref name="defaultStack"/>
  </interceptor-stack>
</interceptors>

<default-interceptor-ref name="curentPageStack"/>

Add a result to return a dynamic parameter
@Results({
  @Result(name = "input", type = "redirect", location = "${currentPage}"),
  @Result(location= "/search-result.jsp")
})
public class SearchAction extends ActionSupport implements RequestAware, SessionAware, Message {

private String currentPage;
//getter

   @Override
    public String execute() throws Exception {
        if (hasErrors()){
          currentPage = (String) session.get("currentPage");
          return "input";
        }

        // business logic
        request.put("searchResults", searchResults);

        return SUCCESS;
    }

    ...
}

A: This is just to show how I went about the solution with Jigar's approach which I marked as accepted answer.
struts.xml:
<action name="search" class="com.mypackage.action.SearchAction">
    <result>/search-result.jsp</result>
    <result name="input">${url}</result>
</action>

I removed the type="redirect" because the fielderror message disappeared. I believe that is the expected behavior as documented in Apache docs:

Redirect Result
  The response is told to redirect the browser to the specified location
  (a new request from the client). The consequence of doing this means
  that the action (action instance, action errors, field errors, etc)
  that was just executed is lost and no longer available.
  Source: http://struts.apache.org/release/2.1.x/docs/redirect-result.html

SearchAction:
public class SearchAction extends ActionSupport implements RequestAware, Message {

    private String url;

    public String getUrl() {
        return url;
    }

    @Override
    public String execute() throws Exception {
        // business logic
        request.put("searchResults", searchResults);

        return SUCCESS;
    }

    @Override
    public void validate() {
        url = ServletActionContext.getRequest().getHeader("referer")
            .replace("http://localhost:8080/mysite/", ""); // get resource name only

        if(!url.contains(".jsp")) {
            url = "index.jsp"; // default page
        }

        if(searchWord.length() == 0) {
            addFieldError("searchWord", BLANK_SEARCH);
        }
    }
}

Output:

It now stays on the current page on error.


text:
Q: How can we set the url of the img element to print the view with the images.Below is my code The assets folder consists of many images which are to be printed in the view according to the list elements.
My code:
<ion-content padding>
  <ion-list>
    <ion-item *ngFor="let data of datas | async" class="pqr">
      <ion-thumbnail item-left>

      </ion-thumbnail>
      {{data.Comp}}

      {{data.Demand}}

 {{data.Desig}}

        {{data.Place}}

        {{data.when}}

    </ion-item>
  </ion-list>

</ion-content>

A: You need to use the DomSanitizer.
// Angular
import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

...

@Component({...})
export class YourPage {

    constructor(private domSanitizer: DomSanitizer, ...) {

        //...
    }

    public getImageUrl(data: any): any {
        let url = `../assets/image/${data.imageName}`;
        return this.domSanitizer.bypassSecurityTrustResourceUrl(url);
    }
}

And then in your view:

<ion-item *ngFor="let data of datas | async" class="pqr">
    <ion-thumbnail item-left>

    </ion-thumbnail>


text:
Q: How to get the values from the formatted string? I have an app which counts down the time.
I formatted a string like this:
String.format("%02d:%02d:%02d", hour, min, sec);

It will be for example 01:42:12.
I would like to know how to do this in the reverse order?
I would like to get 3 values divided by ':'.
How to do that?
Thanks in advance!

A: you may use DateFormat for that purpose:
DateFormat tf = DateFormat.getTimeInstance()
String str = tf(new Date());    // gives you current time '01:05:06'
Date d = tf.parse(str);         // parses it back to the Date

otherwise there's a SimpleDateFormat and many other ways to skin a cat.


text:
Q: How does the AppBundles of Forge Configurator work? i'm trying to extract and run the AppBundles from this demo written in C#
https://github.com/Autodesk-Forge/forge-configurator-inventor
I don't know anything about C# (i use php to program) and i need to integrate this Forge Configurator in my site but i don't understand how the AppBundles works
Can someone explain to me how to run the AppBundles?
(i already run other AppBundle on forge, but there was documentation on each of them, with input/output parameters, ecc...)

A: You can find the zip of each app bundle inside the release zip file: https://github.com/Autodesk-Forge/forge-configurator-inventor/releases/download/v1.0.355/ForgeConvInv-Release-win7-x64-1.0.355.zip
Inside the appsettings.json file you can find what name is used for each of them when they are uploaded to Forge: https://github.com/Autodesk-Forge/forge-configurator-inventor/blob/master/WebApplication/appsettings.json
Inside this folder you'll find how the activities are set up, inc the input/output parameters and commandLine they use: https://github.com/Autodesk-Forge/forge-configurator-inventor/tree/master/WebApplication/Processing
e.g. CreateBOM commandLine https://github.com/Autodesk-Forge/forge-configurator-inventor/blob/master/WebApplication/Processing/CreateBOM.cs#L37 and output parameter https://github.com/Autodesk-Forge/forge-configurator-inventor/blob/master/WebApplication/Processing/CreateBOM.cs#L30
Concerning the format of the input json file that is used by UpdateParameters activity: https://github.com/Autodesk-Forge/forge-configurator-inventor/blob/master/WebApplication/Processing/UpdateParameters.cs#L55 you can find the structure here https://github.com/Autodesk-Forge/forge-configurator-inventor/blob/master/Shared/InventorParameters.cs


text:
Q: "Could not find resource" when trying to retrieve latest build artifact In my Artifactory repo I want to retrieve the latest build artifact.
Described at this link REST API
https://www.jfrog.com/confluence/display/JFROG/Artifactory+REST+API#ArtifactoryRESTAPI-RetrieveLatestArtifact
My target artifact (name of the package ADS_*.zip) I can download if I specify version explicitly:
Invoke-WebRequest -Headers @{'X-JFrog-Art-Api'=$API_KEY}
"$ARTIFACTORY_URL/ADS/ADS_2019_4_1.zip"
-OutFile "$DOWNLOAD_PATH\ADS.zip"

But if I try methods which were suggested on the link using the [RELEASE] or [INTERGATION] or [SNAPSHOT]:
Invoke-WebRequest -Headers @{'X-JFrog-Art-Api'=$API_KEY}
"$ARTIFACTORY_URL/ADS/ADS_[RELEASE].zip"
-OutFile "$DOWNLOAD_PATH\ADS.zip"

I am getting the:
"status" : 404,
"message" : "Could not find resource"

What am I doing wrong?

A: To use this feature, you should configure and use a repository layout.
You can read here for instructions on how to do that. More specifically, see baseRev.
However, configuring a repository layout is not always the best option, since it affects all artifacts in the repository. It is also a bit complicated.
Instead, I'd recommend using the JFrog CLI for downloading artifacts, instead of the REST API.
jf rt dl <path-in-artifactory> <local-path> --sort-by updated --limit 1 --url <jfrog-platform-url>/artifactory --user <username> --password <api-key>

For example, in your case:
jf rt dl "ADS/ADS_*.zip" "$DOWNLOAD_PATH\ADS.zip" --sort-by updated --limit 1 --url <jfrog-platform-url>/artifactory --user <username> --password <api-key>

For more information see Downloading files.


text:
Q: Compare contents of System.Text.JsonDocument C# in unit test I feel like I'm taking crazy pills here... but how can I compare two JsonDocuments (or JsonElements or what have you) for JSON equality, i.e. same keys with same values?
To limit the scope, the ability to perform this comparison in a unit test is sufficient unto the day.
I have a unit test in which I want to compare the result of a function that returns a JsonDocument to some expected value. Things that don't work include using FluentAssertions.Json (because my type is not JObject), and comparing the value of GetRawText because I don't care about the whitespace.
I guess I could write the strings out and re-serialize them or something but this honestly feels like such a hack that I must be doing something wrong.
I understand the business logic of comparing them, I have seen the other questions like this and this. The first is much more in keeping with what I want, it's just an embarrassing result for C#...
The second is not what I need at all.

A: Thanks to @ChristophLütjen for identifying the fix I needed in this issue
Given two JsonDocuments I can compare them using FluentAssertions like this:
Doc1.RootElement.Should().BeEquivalentTo(Doc2.RootElement, opt => opt.ComparingByMembers<JsonElement>());

I'm still bemused that there is not a more straightforward comparison method out there for the general case, but since my immediate use was unit testing, I'm satisfied with this result.


text:
Q: Detect empty, new tab openings in Google Chrome I just published a Google Chrome extension which loads background images into new, empty tabs. The plugin is found here in the Chrome Web Store.
For detecting new and empty tabs, I need to ask for "tab" permissions in the extension's manifest.json. This, however, gives the extension the permission to read the browser's history. Not all users will want this and we don't actually need it. Is there a way to detect empty tabs without this permission requirement? Currently our check looks like this:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
    if (changeInfo.status == "loading" && tab.url == 'chrome://newtab/')
    { /* load background into tab */ }
});

A: If you want to customize the new tab page you should add this to your manifest:
"chrome_url_overrides": {
   "newtab": "newtab.html"
}

Then place the script you are currently injecting into new tab pages as a <script> tag in the newtab.html file. That won't cause that permission message.


text:
Q: Pandas idiomatic way of mapping json list to dataframe I have a dataset derived from a json input, which id like to map to a pandas dataframe. Lets say the json corresponding to individual rows of the table looks like so:
popo = {'foo': 3.14, 'bar': [1, 2, 3]}

That is, on of the keys corresponding to one of the desired columns in my table is itself a list, of a fixed length.
Loading a list of such dicts, using either pandas.DataFrame.from_dict, or pandas.io.json.json_normalize, results in a dataframe with two columns, foo and bar. In both cases, bar is of type object, with these objects being python lists.
df = pd.DataFrame.from_dict([popo] * 10, orient='index')

In a perfect world, what id like is for df['bar'] to dereference into an array of shape [n, 3], so I could proceed to write things like df['bar'].sum(axis=1) efficiently and concisely.
But not only does my loading code not give this result, to my unpleasant surprise, pandas does not appear to support anything but 1d arrays as series/columns on a dataframe, so I cannot subsequently manually cast to a similar format either.
Am I missing something? It feels like this isn't a very exotic use case, so surely there is an idiomatic way of working with data structured in such a way?
EDIT: another reason the column of type object containing python lists is annoying, is that binary formats like feather are unable to deal with it. So transforming this datastructure into one that can be efficiently serialized could be considered another requirement for unlocking the typical benefits of working in idiomatic pandas.

A: To answer my own question, this is the most satisfying answer I have found so far; to preprocess my json derived datastructure by casting all lists (or iterables) to enumerated dicts:
def list_to_dict(popo):
    if isinstance(popo, dict):
        return {k: list_to_dict(v) for k, v in popo.items()}
    try:
        return {str(i): list_to_dict(v) for i, v in enumerate(popo)}
    except:
        return popo

Now we have:
list_to_dict(popo) == {'foo': 3.14, 'bar': {'0': 1, '1': 2, '2': 3}}

That at least allows me to write things like:
df = pandas.io.json.json_normalize([list_to_dict(popo)] * 10)
df[[f'bar.{i}' for i in range(3)]].sum(axis=1)

Not a huge fan since this preprocessing does not come for free, and also the access will not have the same efficiency as addressing a single contiguous array... but maybe ill have to settle for it.

A: Well, this isn't going to get you where you wanted to go, but I had fun trying, so I figured I'll share this, because why not?
import pandas as pd

popo = {'foo': 3.14, 'bar': [1, 2, 3]}
df = pd.DataFrame.from_dict([popo]*10)
df

Output:
        bar     foo
0   [1, 2, 3]   3.14
1   [1, 2, 3]   3.14
2   [1, 2, 3]   3.14
3   [1, 2, 3]   3.14
4   [1, 2, 3]   3.14
5   [1, 2, 3]   3.14
6   [1, 2, 3]   3.14
7   [1, 2, 3]   3.14
8   [1, 2, 3]   3.14
9   [1, 2, 3]   3.14

Let's define a function:
def obj_sum(df, column):
   new_col = []
   for i in df[column].tolist():
           new_col.append(sum(i))
   df.drop(column, axis = 1, inplace = True)
   df[column] = new_col
   return df

And, finally, let's what this does:
obj_sum(df,'bar')

Output:
    foo     bar
0   3.14    6
1   3.14    6
2   3.14    6
3   3.14    6
4   3.14    6
5   3.14    6
6   3.14    6
7   3.14    6
8   3.14    6
9   3.14    6

Well, at least I tried...


text:
Q: Rails: How to disable asterisk on form's required fields? When I add the 'Required' attribute
to html input fields, Rails pre-pends an asterisk (*) before the label.
Does anyone know how to prevent this?
For some reason Rails transforms this:
<%= f.input :Company, :input_html => {:value => "", :id => "company_name"}, :label => "company name" %>

into this:

    * company name
    <input type="text" value="" size="50" required="required" name="lead[Company]" id="company_name" class="string required">

I don't like that it wraps everything in a DIV and adds an ABBR element to the party.
How can I prevent this?

A: You can just set the required mark to empty value in simple_form's locale file:
en:
  simple_form:
    required:
      text: 'required'
      mark: '*'

Or use CSS to hide it.

A: It isn't rails at all. It's the simple_form gem. So, if you don't want all the wrapping elements don't use simple_form. Use Rails form helpers. It would be more simple than customize something you don't like.

A: For anyone using Formtastic and having this issue, you can remove the asterisks by editing the config file, which is typically app/config/initializers/formtastic.rb.
Change this line: # Formtastic::SemanticFormBuilder.required_string = "(required)"
to be: Formtastic::SemanticFormBuilder.required_string = ""
More info here.

A: In config/initializers/simple_form.rb add this line:
config.label_text = lambda { |label, required| "#{label}" }

A: Code that has helped me solve the asterisk issue:
abbr[title="required"] {
  display: none;
}

The chosen answer and the other suggestions asking to change the HTML in locales file dint help me with the latest Simple_form gem.

A: Aside from the global config suggested in the accepted answer, you can pass required: false as an input option, or defaults: { required: false } to set it for the whole form.

A: You can remove it from the whole form:
<%= simple_form_for @form, defaults: { required: false } do |f| %>

A: I'm using Rails 3.1, and I have the following view code in my _form.html.erb for a given model:

  <%= f.label :full_name %>

  <%= f.text_field :full_name, :required => true %>

The label does not show an asterisk if you do it this way.  Unless you post code I can't be sure of what your approach is and if my solution would fit said approach.
Updated Answer:
It sounds like you've inherited this code from someone.  At any rate, after reading your code sample, you are most definitely using the simple_form gem.  Information about that gem can be found here https://github.com/plataformatec/simple_form.  To answer your question though, if you change your code the following:
<%= f.input :Company, :input_html => {:value => "", :id => "company_name"}, :label => "company name", :required => false %>

That should turn off the asterisk.
I would add, based on your disgust for the HTML generated from simple_form, it sounds like you should just do away with the gem and re-write your form code using the Rails default form helpers, which can be read about here http://guides.rubyonrails.org/form_helpers.html.  Depending on the size of the code base, you might be better off just sucking it up and learning how to use the simple_form gem for the sake of saving time, but if you think you have the time to change it all, go for it.

A: The simplest way is to hide it with this css:
abbr[title="required"] {
  display: none;
}

A: I found out that if you only want to remove the asterisk(*) behind it then all you have to  do is to go to this file file /config/locales/simple_form.en.yml
once again is not a good practice to change your configuration files for gems and something your using for some reason, it always a question of why do you really use simple_form!
But for example I found out about that because there is great things about simple_form we use but nowadays is a better usability practice to have the asterisks on none required fields then required ones.

A: you can used form_for, and override method def label in config/initializer to add asterisk for mandatory fields as the following:
def label(object_name, method, content_or_options = nil, options = nil, &block)
    if content_or_options.is_a?(Hash)

      content_or_options.each do |key, val|
        options[key] = val
      end

      content_or_options = method.to_s
    end

    content_or_options ||= method.to_s

    presence_validations = [ActiveModel::Validations::PresenceValidator, ActiveRecord::Validations::PresenceValidator]

    class_obj = options[:object].class if options[:object]
    class_obj ||= object_name.to_s.camelize.constantize

    validations = class_obj.validators_on(method.to_s).map(&:class)

    if (presence_validations.map { |pv| validations.include?(pv) }).any?
      content_or_options += "*"
    end

    Tags::Label.new(object_name, method, self, content_or_options, options).render(&block)
end

This method puts asterisk after all mandatory fields, if you used normal form_for, and used validates_presence_of


text:
Q: I want to know how to show a "loading" image when a form is submitted by action="any.php" I want show Loader img with jQuery when you post by PHP Simple action="search.php" Not ajax post or jquery post
and Thanx for all

A: This problem is not solvable in a meaningful way without the use of AJAX. In other words, you need AJAX to show a "loading" image while the response from a form submission is handled by the server.
If I understand you correctly, then you have a form:
<form action="search.php" method="post">
    ...
</form>

And it is handled as a regular HTML form. The data is passed by the page to the server that uses PHP to handle it. Without AJAX, you have no good way of finding out when the response of the form, the search results, are ready.
Generally, what is done is that the form is submitted to the server with the use of AJAX. The form is handled by the server (PHP does its stuff). During this time, a "searching" image is shown. Then  when the server responds, the image is removed and the search results are shown.
Using jQuery and AJAX on a page this could be done like this:
jsFiddle example
  // The form has an id of "theForm".
  // This function defines what happens when it is submitted.
$('#theForm').submit(function() {

      // Replace the form w the search icon.
    $("#theForm").html('Searching...
' +
        '');

      // Make the search request to the PHP page.
      // The 3 arguments are:
      //     1 - The url. 2 - the data sent
      //     3 - The function called when data is sent back
    $.post("/ajax_html_echo/", $(this).serialize(), function(result){

          // Here we replace the search image with the data
        $("#page").html(response);
    });

      // Cancel the regular submission of the form.
      // You have to do this, or the page will change and things won't work.
    return false;
});

The nice thing about the above is that it degrades nicely if JS is off, since you still have the regular HTML form and its regular submit functionality to fall back on, and if JS is on, then it blocks this regular functionality with the return false and uses the AJAX.
Jquery used:
.submit()
.html()
.post()
.serialize()


text:
Q: Why Adding angular-carousel throws $injector:modulerr? I tried adding angular-carousel in my application and I am getting this error
   Failed to instantiate module ngMaterial due to:
Error: [$injector:modulerr] http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=n...)
    at Error (native)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js:6:412
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js:40:222
    at q (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js:7:355)
    at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js:39:319)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js:39:488
    at q (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js:7:355)
    at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js:39:319)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js:39:488
    at q (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js:7:355

I got this error only after adding ngMaterial in my application with carousel. I am using latest stable version 1.5.8 of angularjs. This is my code I tried until now,
    <!DOCTYPE html>

            <meta charset="UTF-8">
            <title>angular-carousel demo</title>
            <meta name="viewport" content="width=620, user-scalable=no">
            <link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet' type='text/css'>
            <link rel="stylesheet" type="text/css" href="css/angular-material.min.css">
            <link href='css/angular-carousel.min.css' rel='stylesheet' type='text/css'>

Am I wrong by someway?. Can someone please help me?

A: First Include All Dependencies

Than include Angular Material JS file

A: Looks like to don't include the ngMaterial js files


text:
Q: AWS S3 Access via localhost works from one machine and denied from another I have NodeJS app hosted an AWS Elastic Beanstalk. I need to access objects (images) on S3. I am using AWS SDK.
Everything works as expected when application is launched on the web.
When I ran it on localhost on 1 of my PCs (part of Windows Domain Network, behind firewall) it works fine, when I try to do run the same code on the other PC (stand-alone, connected directly to internet) i get an access denied error.
The code is identical, the credentials (Key and Secret Key) are identical.
I appreciate any suggestions on how to solve this.


text:
Q: First initialization of a VisitCount session gives a null pointer exception but a redeploy makes it work When I initially start the tomcat Server I get a nullpointer exception referring to the line "visitCount = visitCount + 1;" And I'm not quite sure how to fix it. To my understanding it has something to do with the fact that when the session is new and it does not know what value to give back although I thought it would give 0 because of this line "Integer visitCount = new Integer(0);"
Redeploying makes the nullpointerexception go away. So that to me confirms my assumption explained above.
Help is greatly appreciated.
Error
Servlet:
  private String getLogCount(HttpServletRequest request, HttpServletResponse response) {

            HttpSession session = request.getSession();
            Date createTime = new Date(session.getCreationTime());
            Date getLastAccesTime = new Date(session.getLastAccessedTime());

            String titleKey;
            Integer visitCount = new Integer(0);
            String visitCountKey = new String("visitCount");

            if (session.isNew()) {
                titleKey = "Welkom!";

            } else {
                titleKey = "Welkom terug!";
                visitCount = (Integer) session.getAttribute(visitCountKey);
                visitCount = visitCount + 1;

            }
            session.setAttribute(visitCountKey,  visitCount);
            session.setAttribute("createTime", createTime);
            session.setAttribute("lastAccessTime", getLastAccesTime);
            session.setAttribute("title", titleKey);

            return "activiteit.jsp";
        }

JSP PAGE:

${title}

                Aantal keren deze website bezocht: ${visitCount}
                Eerste moment van je sessie: ${createTime}
                Laatste moment van je sessie: ${lastAccessTime}

A:
[..] although I thought it would give 0 because of this line Integer visitCount = new Integer(0);

That line of code ends up doing nothing because a few lines below you override it with this:
visitCount = (Integer) session.getAttribute(visitCountKey);

So now, visitCount has whatever value you extract from the session. Based on the error you are describing, you most likely retrieve null from the session.
So basically, your code does this:
Integer visitCount = new Integer(0);  // value is 0
// ...
visitCount = (Integer) session.getAttribute(visitCountKey); // value is whatever you get from session, most likely null based on the error you get
visitCount = visitCount + 1; // this can result in null + 1, thus your error

I would rewrite the code like this:
private String getLogCount(HttpServletRequest request, HttpServletResponse response) {

    HttpSession session = request.getSession();
    Date createTime = new Date(session.getCreationTime());
    Date getLastAccesTime = new Date(session.getLastAccessedTime());

    String titleKey;
    int visitCount = 0;
    String visitCountKey = "visitCount";

    if (session.isNew()) {
        titleKey = "Welkom!";

    } else {
        titleKey = "Welkom terug!";
        Integer sessionVisitCount = (Integer) session.getAttribute(visitCountKey);
        if (sessionVisitCount != null) {
            visitCount = sessionVisitCount.intValue() + 1;
        }
    }

    session.setAttribute(visitCountKey, Integer.valueOf(visitCount));
    session.setAttribute("createTime", createTime);
    session.setAttribute("lastAccessTime", getLastAccesTime);
    session.setAttribute("title", titleKey);

    return "activiteit.jsp";
}


text:
Q: declare a variable using `execute` Interpolation in Terraform I want to declare a a sub-string of a variable to another variable. I tested taking a sub-string using terraform console.
> echo 'element(split (".", "10.250.3.0/24"), 2)' | terraform console
> 3

my subnet is 10.250.3.0/24 and I want my virtual machine to get private IP address within this subnet mask 10.250.3.6. I want this to get automatically assign by looking at subnet address. What I've tried;
test.tf
variable subnet {
  type = "string"
  default = "10.250.3.0/24"
  description = "subnet mask myTestVM will live"
}

variable myTestVM_subnet {
  type = "string"
  default = "10.250." ${element(split(".", var.trusted_zone_onpremises_subnet), 2)} ".6"
}

And then I test it by
terraform console
>Failed to load root config module: Error parsing /home/anum/test/test.tf: At 9:25: illegal char

I guess its just simple syntax issue. but couldn't figure out what!

A: As you've seen, you can't interpolate the values of variables in Terraform.
You can, however, interpolate locals instead and use those if you want to avoid repeating yourself anywhere.
So you could do something like this:
variable "subnet" {
  type = "string"
  default = "10.250.3.0/24"
  description = "subnet mask myTestVM will live"
}

locals {
  myTestVM_subnet = "10.250.${element(split(".", var.trusted_zone_onpremises_subnet), 2)}.6"
}

resource "aws_instance" "instance" {
  ...
  private_ip = "${local.myTestVM_subnet}"
}

Where the aws_instance is just for demonstration and could be any resource that requires/takes an IP address.
As a better option in this specific use case though you could use the cidrhost function to generate the host address in a given subnet.
So in your case you would instead have something like this:
resource "aws_instance" "instance" {
  ...
  private_ip = "${cidrhost(var.subnet, 6)}"
}

Which would create an AWS instance with a private IP address of 10.250.3.6. This can then make it much easier to create a whole series of machines that increment the IP address used by using the count meta parameter.

A: Terraform doesn't allows interpolations declaration of variables in default. So I get ;
Error: variable "myTestVM_subnet": default may not contain interpolations

and the syntax error really got fixed after banging my head, so here is what Terraform likes;
private_ip_address = "10.250.${element(split(".", "${var.subnet}"), 2)}.5"


text:
Q: Beginner, trying to setup Python I'm a PHP programmer, but I want to learn Python. I'm a bit confused with how to actually execute a script. I've created test.py in my web server root, in the file I've written:
#!/usr/bin/python
import jon.cgi as cgi
import jon.fcgi as fcgi

print "Content-type: text/html"
print "hello world"

My server is running Litespeed on CentOS 5, following the tutorial at: http://www.litespeedtech.com/support/wiki/doku.php?id=litespeed_wiki:python_fcgi I've installed Jon's CGI.
But when I navigate to the script in my browser it just prints the full code, as if it's not parsing it. Sorry if I'm asking a stupid question, I would really appreciate any help, thanks.

A: A real answer needs a lot more information (relevant paths, chunks of configuration, is your *.py executable, did you restart after configuration etc) so I'm going to do the best I can, but first...
Unlike PHP which has fastCGI built into the interpreter itself, Python doesn't hide the fastCGI implementation from you.  At the very basic level, this test.py sets invalid headers (\r\n newlines are mandatory) and is missing the required blank line between headers and body.  These are both things that the req.set_header() and req.write() functions (as shown in the example) deal with.
Second, you have to write a fastCGI application that runs "forever" (or until it hits the maximum number of requests and the server kills it to start another).  Unlike PHP, there isn't a "python-cgi" like "php-cgi" (that I'm aware of, anyway...) that will run forever and handle requests by running little bits of source code from various files.
That app will have a request handler function that is called for every request and is responsible for reading and processing the actual request.  In the case of the example given, the Handler class (which is a subclass of cgi.Handler) is created and is used to construct a fastCGI server whose run() method is called to handle the "run forever" part of the question.  The class has a process() member added that accepts the request and does something.  This "something" is where you would have your hello world code.
Based on the configuration in the example you linked, when a browser goes to http://vhost.example.com/python/banana/apple.jpg, litespeed will attempt to connect to an existing /absolutepathto/demoapp.py process through the socket file at /tmp/lshttpd/mypythonfcgi.sock (or run the demoapp.py program then connect if necessary).  Once it's connected, it uses the fastCGI protocol to tell the running app that it has a request for banana/apple.jpg via REQUEST_URI (I think. It may be /python/banana/apple.jpg or something like that.  Use the example given to dump the request and see).  It's up to the process() member function to figure out what to do with the banana/apple.jpg request.  Unlike plain PHP, URLs will not necessarily correspond to individual pieces of source code. (Though you could write a python program that uses REQUEST_URI to execute other python programs.)
Also note that this /absolutepathto/fastcgiapp.py is traditionally outside of your server document root so that people can't accidentally download the app itself.
Now, as to why your script is being printed out instead of throwing a bad header error, giving you a blank page, or just crashing.  Leading suspects are one of the three:

*

*your "/absolutepathto/test.py" isn't executable (though I'm sure this would cause an error)

*your virtualhost in litespeed isn't configured with your test.py as an "External App" (this could also be configured at the server level for all virtualhosts)

*your URI on that virtualhost isn't configured to route requests to your "External App" configured in step #2.

*you didn't restart litespeed after changing the configuration for #2 and #3? (not really a leading suspect but gotta ask)

If it isn't #1 or #4, update the question with your relevant litespeed configuration, and we'll go from there.


text:
Q: PHP: Accessing array variables Can someone help me access this array please I'm having trouble with indexes.
array(10) {
    [0]=>array(2) {
        ["t"]=>array(1) {
            ["tag"]=>string(3) "php"
        }
        [0]=>array(1) {
            ["NumOccurrances"]=>string(1) "2"
        }
    }
    [1]=>array(2) {
        ["t"]=>array(1) {
            ["tag"]=>string(6) "Tomcat"
        }
        [0]=>array(1) {
            ["NumOccurrances"]=>string(1) "1"
        }
    }
}

I want to use it in a foreach loop displaying like "PHP x 2" but am having trouble with the indexes
Thanks
Jonesy

A: something like
foreach($array as $entity)
{
    echo $entity['t']['tag'] . ' x ' . $entity[0]['NumOccurrances'];
}

Would work.

A: foreach ($array as $key => $value){
  echo $value['t']['tag'] . " x " . $value[0]['NumOccurrances'];
}

A: Does this do?
foreach ($tags as $t) {
    echo $t['t']['tag'].' x '.$t[0]['NumOccurrances'].'
';
}

The structure seems a bit weird. If this does not help, please provide the rest of array.

A: foreach( $a as $item ) {
    echo $item['t']['tag'] . 'x' . $item[0]['NumOccurrances'] . '
';
}

A: I wouldn't use a foreach loop here. foreach creates a copy of the array and therefore is not as efficient as a for loop. Since your first dimension is numerically indexed, I would do the following:
$count = count($array);
for ($i = 0; $i < $count; ++$i){
  echo $array[$i]['t']['tag'] . " x " . $array[$i][0]['NumOccurrances'];
}

I agree with vassilis that the array structure is odd.