text:
Q: Including script reference from HtmlHelper extension method Here is the sample extension method for calendar:
public static string Calendar(this HtmlHelper html)
{
    return "<input type='text' onclick='showCalendar(this)'/>";
}

Function showCalendar() is defined in calendar.js.
Is it possible to register a reference to calendar.js from an extension method?
Html.Calendar() could be called more than once, but only one script should be included.

A: Short answer: YES.
Here comes the But...
But you need to change your return type. if you just return a string, it will be encoded so you browser wont actually run the script block.
In Chrome you get somthing like this "" notice the quotes. to get round this use IHtmlString as your return type, and to make double sure return helper.Raw.
public static IHtmlString RegisterScripts(this HtmlHelper helper)
    {
        return helper.Raw("<script>function () { DO SOMETHING }</script>");
    }

A: Nice question.. for the time being I just make another extension method from which I return the script registration (say, RegisterCalendarScriptBloc()) but it would be better to have an automatic inclusion the first time a dependency is needed.

A: Try something like this if you are using WebForms Views (not tested):
using System.Web.UI.HtmlControls;

public static string Calendar(this HtmlHelper html, HtmlHead head)
{
    var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
    var url = urlHelper.Content("~/Script/calendar.js");

    //var scriptControl = new HtmlGenericControl("script");
    //scriptControl.Attributes.Add("src", url);
    //scriptControl.Attributes.Add("type", "text/javascript");

    //if(head.Controls.Contains(scriptControl))
    //{
    //    head.Controls.Add(scriptControl);
    //}

    // or

    if(!head.Controls.Cast<Control>().Any(x => (x as HtmlGenericControl) != null
        && (x as HtmlGenericControl).Attributes["src"] == url))
    {
        var scriptControl = new HtmlGenericControl("script");
        scriptControl.Attributes.Add("src", url);
        scriptControl.Attributes.Add("type", "text/javascript");

        head.Controls.Add(scriptControl);
    }

    return "<input type='text' onclick='showCalendar(this)'/>";
}

In View:
<%= Html.Calendar(Header) %>

Hope this works :)


text:
Q: How do I see the semantic data for a URL? Let's say I have an URL for a website. How do I see if there is semantic content (FOAF, RDF, etc) associated? And what the URLs for these are?
I just installed Semantic Radar, a Firefox plugin that will notify of semantic content for a website. E.g. if I go to http://sioc-project.org/firefox in Firefox, it tells me that there that there is some semantic data available and shows their links.
But how does Semantic Radar get to know about this semantic data?

A: Well, looking for .rdf links within the contents of a given .html page should not be very difficult. For more info: http://www.w3.org/TR/rdf-syntax-grammar/#section-rdf-in-HTML
On the other hand, it is also possible to directly embed RDF encoded semantic data into an HTML page by using RDFa standard: http://en.wikipedia.org/wiki/RDFa. This means a tool can use this information to extract semantic data (and then use this to probably indicate links to other sources of semantic data).

A: To complete Emre answer, this is the RFDa standard : http://www.w3.org/TR/rdfa-syntax/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to set a "global" conditional breakpoint that is evaluated anywhere the condition is valid? I am working with a C++ codebase that does not use exceptions, and the convention is that every function returns false on failure, such that a significant portion of the code looks like this:
bool compute_something(int& result) {
    bool ok = step1();
    ok = ok && step2();
    ok = ok && step3();
    ...
    ok = ok && stepN(result);
    return ok;
}

When debugging an error, I would like to add a breakpoint whenever any variable named "ok" in the program becomes false, in order to find the exact moment the error occured.
I found this question, which is somewhat similar, but does not solve this problem (and it is gdb specific).
Can this be achieved in visual studio? Or any other environment for that matter, the answer might help someone else.

A: Unfortunately, I am pretty sure you can't. There could be no breakpoints on variables by random names. You can place memory access breakpoint on a specific memory address, or you can use a variable name which is in scope in current sessions (which just puts the breakpoint on the address of said variable).
The reason for this is the fact that memory access breakpoints are done in hardware, and hardware has no notion of any names at all.


text:
Q: Do the Lienard Wiechert Potentials satisfy the wave equation? The Lienard Wiechert potential (leaving out the vector potential for simplicity),
$$\left.\phi(\vec{r},t)=\frac{e}{4\pi\epsilon_0R\,(1-\hat{n}\cdot\vec{\beta})} \right|_{t'=t_{\rm ret}},$$
where the quantities should be evaluated in the retarded time given by $t_{\rm ret}=t-R/c$, should satisfy the wave equation. The wave equation for the potential is derived from Maxwell's equations in the Lorenz gauge and given by
$$\left(\nabla^2-\frac{1}{c^2}\partial_t^2\right)\phi(\vec{r},t)=-\frac{\rho}{\epsilon_0}, $$
where $\rho$ is the charge density and should be
$\rho=e\,\delta(\vec{r}-\vec{r}')$ for the point charge. Plugging $\phi(\vec{r},t)$ into the wave equation we need to compute the second-order spatial and time derivatives with respect to the observer. To assist with the derivation, I have computed the following spatial derivatives in cartesian coordinates ($i=x,y,$ or $z$),
$$\partial_i R=n_i, $$
$$ \partial_i \frac{1}{R} = -\frac{n_i}{R^2},$$
$$\partial_i n_i = \frac{1-n_i^2}{R},$$
$$\partial_i (1-\hat{n}\cdot\vec{\beta}) = \frac{n_i(\hat{n}\cdot\vec{\beta})-\beta_i}{R},$$
and the following observer time derivatives (taking mind to switch from $\partial_t$ to $\partial_{t'}$ using $dt=dt'(1-\hat{n}\cdot\vec{\beta})$ when necessary),
$$\partial_t R=-c\frac{\hat{n}\cdot\vec{\beta}}{(1-\hat{n}\cdot\vec{\beta})}, $$
$$ \partial_t \frac{1}{R} = c\frac{\hat{n}\cdot\vec{\beta}}{R^2(1-\hat{n}\cdot\vec{\beta})},$$
$$\partial_t n_i = \frac{c}{R(1-\hat{n}\cdot\vec{\beta})}\left({n_i(\hat{n}\cdot\vec{\beta})-\beta_i }\right),$$
$$\partial_t (1-\hat{n}\cdot\vec{\beta}) = \frac{c\left({ \vec{\beta}\cdot\vec{\beta}-(\hat{n}\cdot\vec{\beta})^2 }\right)}{R\left({1-\hat{n}\cdot\vec{\beta}}\right)}.$$
Now, when I compute the second-order derivatives I get:
$$\nabla^2\phi(\vec{r},t) = -\frac{e}{2\pi\epsilon_oR^3(1-\hat{n}\cdot\vec{\beta})^3}\left({ 1-(\hat{n}-\vec{\beta})\cdot(\hat{n}-\vec{\beta}) }\right)$$
$$\frac{1}{c^2}\partial_t^2 = \frac{e}{4\pi\epsilon_oR^3(1-\hat{n}\cdot\vec\beta)^7}
\left({(1-\hat{n}\cdot\vec\beta)^3 \left({(\hat{n}\cdot\vec\beta)^2-\vec\beta\cdot\vec\beta +2(\hat{n}\cdot \vec\beta)(\hat{n}\cdot\vec\beta-\vec\beta\cdot\vec\beta)}\right) + (\hat{n}\cdot\vec\beta-\vec\beta\cdot\vec\beta)((\hat{n}\cdot\vec\beta)^2-\vec\beta\cdot\vec\beta) }\right) $$
which I dont see any way that their difference will be equal to $-\rho/\epsilon_0$ for a point charge as dictated by the wave equation. Am I doing something wrong here?

A: Yes, the Lienard-Wiechert potential is a solution to the wave
equation with a point charge source. That's how it is derived.
However, if you want to take derivatives in order to show this
explicitly from the differential equation, you must be very
careful to not neglect any terms in the derivatives, and also
be careful to be able to extract the delta function.
For the second point,
the delta function occurs from derivatives like those in the simple
Coulomb's law static case
$\nabla^2 \frac{1}{r} = -4\pi \delta^3(\vec r)$. However, if you
were to write $\nabla^2$ in spherical coordinates it would be
$\frac{1}{r}\partial_r^2 r$ plus angular terms. Taking the derivatives
above gives
$\frac{1}{r}\partial_r^2 r \frac{1}{r} = 0$. The delta function is
hidden at the coordinate boundary at $r=0$. Exactly this case will
also occur for the
the Lienard-Wiechert potential, so it is best to isolate a
$\nabla^2 \frac{1}{R}$ term and realize this will give the delta function,
by either using the divergence theorem, smearing out the singularlity,
or changing to other coordinates.
For the derivatives, you just have to be meticulous. If you think of
a derivative as being
$\lim_{\delta\rightarrow 0} \frac{F(x+\delta)-F(x)}{\delta}$, then
when you change the observation point $x$, $y$, $z$, or $t$, the
retarded time changes. You have to take derivatives with respect to
$t_{\rm ret}$ times derivatives of $x$, $y$, $z$, or $t$ using the
chain rule.
So realizing that $R$ is a function of $t_{ret}$,
$t_{\rm ret} = t-R(t_{\rm ret})/c$
\begin{equation}
\partial_t  t_{\rm ret} = \partial_t [t-R(t_{\rm ret})/c]
= [1-\vec \beta(t_{\rm ret}) \cdot \hat R(t_{\rm ret})\partial_t t_{\rm ret}]
\end{equation}
gives
\begin{equation}
\partial_t t_{\rm ret} = \left . \frac{1}{1-\vec \beta(t')\cdot \hat R(t')}
\right |_{t'= t_{\rm ret}}
\end{equation}
similarly
\begin{equation}
\partial_x t_{\rm ret} = -\left . \frac{1}{1-\vec \beta(t') \cdot \hat R(t')}
\frac{X(t')}{cR(t')} \right |_{t'= t_{\rm ret}}
\end{equation}
with analogous expressions for $y$ and $z$. $X/R$ is the $x$ component of your $\hat n$.
Using the chain rule, your need to evaluate your derivatives as
\begin{eqnarray}
\partial_ t \left [ F \right ]_{\rm ret} &=&
\left [  \frac{1}{1-\vec \beta \cdot \hat R} \dot F \right ]_{\rm ret}
\nonumber\\
\partial_ x \left [ F \right ]_{\rm ret} &=&
\left [ \partial_x F -\frac{X}{cR} \frac{1}{1-\vec \beta \cdot \vec r} \dot F
\right ]_{\rm ret}
\end{eqnarray}
where the dot means take the partial derivative with respect to the time
argument, and I have just written the subscript ret to indicate evaulating
at the retarded tim.
If this isn't clear, just carefully take the derivatives with
the chain rule. The second terms are from the change in the retarded time.
If you do this and don't make an algebra mistake, you will find
your desired result.


text:
Q: Why is concatenating two linked lists by assigning pointers wrong? So our lecturer just showed us how to concatenate two linked list but then went on and showed us and example that would be wrong if implemented,I don't seem to quite understand why it won't work as good,since it wasn't explained.What would be the problem if I concatenate two linked lists this way:
template <typename T>
void LList<T>::concat(LList<T> const & list) {
    end->next = list.start;
    end = list.end;
}

A: The approach used in the question is wrong because it incorrectly shares Ownership of the transferred nodes.
list owns its nodes. It maintains and ultimately releases them. By giving pointers to nodes owned by list to the receiving linked list, you will now have two linked lists referring to and trying to own the same set of nodes.  If you later modify list, you will modify the receiver and potentially leave it in an inconsistent state (end may no longer be correct, for example). If you later destroy list, the receiver is left pointing to invalid memory after list destroys its nodes. Likewise list is left in a precarious state by modifying or destroying the receiver.
This is somewhat related to The Rule of Three, and it's the copy constructor required by Rule of Three that I'd take advantage of to get out of this mess. I'd pass list in by value rather than as a reference so that it is correctly duplicated and then move its list of nodes, copies of the nodes owned by the source list, into the receiving linked list. You can then clean up list so that it is safe to destroy and leave it to die when it goes out of scope. This approach may be a little slow, but it's very nearly foolproof. See the Copy and Swap Idiom for a nearly identical trick being applied to the assignment operator.


text:
Q: How to write subprocess' stdin continuously? I have a script behaves like subscript.py below and I want to run it from another one because it was written with Python 2.7. I tried some of subprocess functions but none of them provides the same functionality like subscript runs in terminal natively.
subscript.py
import threading
from queue import Queue
import argparse

class FooBar():
    def __init__(self) -> None:
        self.q = Queue()
        foo = threading.Thread(target=self.foo)
        bar = threading.Thread(target=self.bar)
        foo.start()
        bar.start()

def foo(self):
    while True:
        text = input()
        print(f"{text} is sent by foo()")
        self.q.put(text)

def bar(self):
    while True:
        if not self.q.empty():
            text = self.q.get_nowait()
            print(f"{text} is sent by bar()")

if __name__ == "__main__":
    c = FooBar()

main1.py
This one kills process right after something printed by subscript.
import subprocess
subprocess.run("py subscript.py", text=True, input="foo\n")

main2.py
This one is a blocking type. So it is not possible to feed subscript with stdin.
import subprocess
output = subprocess.call("py subscript.py")

A: Your first option closed stdin as soon as the string was written and the second doesn't give you any opportunity to write to stdin so it hangs. You can use the lower-level Popen call to get a pipe to stdin and write it yourself.
>>> import sys
>>> import subprocess
>>> proc = subprocess.Popen([sys.executable, "subscript.py"], stdin=subprocess.PIPE)
>>> proc.stdin.write(b"hello\n")
6
>>> proc.stdin.flush()
>>> hello is sent by foo()
hello is sent by bar()

That pipe requires byte objeccts. But it can be put in a text wrapper that does the string to bytes encoding for you (and lets you use print if you want).
>>> import io
>>> txt_stdin = io.TextIOWrapper(proc.stdin)
>>> print("hello again", file=txt_stdin, flush=True)
>>> hello again is sent by foo()
hello again is sent by bar()

But there is still a lot missing. If the program writes things too, you may need to use pipes for stdout and stderr also. If it is expecting a terminal, you may need to use a pseudo-tty or pexpect if you are also on a unix like system.


text:
Q: Conservation of linear momentum, when is it conserved?
*

*Will Linear momentum be conserved in a non-inertial frame of reference?

*In other words what is the fundamental condition for linear momentum to be conserved?

*Also which is more fundamental- Newton's Third Law or Conservation of Linear Momentum? (as in Newton's third law does not hold true when we go to the quantum/atomic level or at relativistic speeds whereas linear momentum to my knowledge holds true)

A: Linear momentum will be conserved when the Lagrangian that describes your system is unchanged by translations in space. This is a consequence of Noether's theorem, and it's as close as you're going to get to a fundamental explanation for the conservation of momentum.
In general a Lagrangian written in the coordinate system of an accelerating observer is not going to satisfy this condition, so momentum will not be conserved.
I suspect most physicists would regard Newton's third law as derived from conservation of momentum.


text:
Q: Yocto: why is a package included? I am currently using yocto for building an embedded linux image for TI AM335x (I am using hob, since I find it more comfortable than using command-line).
I start using the recipe for building 'core-image-base' and here is the selection of packages which are included:

Now I would like to exclude the package alsa-utils-1.0.28-r0 from build, since it has some problems compiling for my target and I really do not need it... so, as far as I can understand, I have to remove all the dependencies which brought alsa-utils in (that is: alsa-state and packagegroup-base, looking at following screenshot):

So I move to Package groups tab and I remove packagegroup-base and then I remove alsa-state and alsa-utils from the Included recipes:

Now it seems that alsa-utils is there no more... but if I try to build the image, this is the result:

Why? Who is still bringing-in alsa-utils? What am I doing wrong? Is there a way (even command-line) to know why a package is brought-in by yocto?

A: Use
bitbake -g alsa-utils -u depexp

to display a dependency tree you should be able to see who's depending on it.
See the openembedded wiki.


text:
Q: Wait for Mail to send then delete it from sent-folder in PowerShell I'm currently writing a script to automatically send some mails.
I want to send an automated mail, and for purpose of a clean mailbox I want these automated mails to be deleted from the sent-folder straight away.
I have got the script so far as to send the mail, and I also have written a perfectly functioning function that clears the sent-folder.
The problem is that the mail will remain in the outbox while it is being sent and only enters the sent-folder when it is in fact sent, but by then my script will have ended and the Clear-function will have passed without having cleared the mail.
I will need some sort of timer or if possible some triggered event for when the mail is in fact sent and stored in the sent-folder.
Code:
function Send
{
    $mItem = $ol.CreateItem(0)
    $mail = $routlook.GetRDOObjectFromOutlookObject($mItem)

    $mail.To = "users@mail.com"
    $mail.Subject = "some subject"
    $mail.Body = "some body stuff"
    $mail.Attachments.Add("<path to attachment>")

    $mail.Send()
    Clear

}

function Clear
{
    $SItems = $sent.Items
    foreach($s in $SItems)
    {
        if( $s.To -eq "'user@mail.com'")
        {
            $s.Delete()
        }
    }
}

Please help me, thanks ;)

A: Set the MailItem.DeleteAfterSubmit property to true - the message will never be moved to the Sent Items folder after it is sent.

A: Don't send mail through Outlook in the first place, unless you absolutely must for some odd reason. Use Send-Mailmessage instead.
Send-MailMessage -to users@mail.com -subject "Some Subject" -body "some body stuff" -attachments <Collection of file paths> -SmtpServer Your_SMTP_HOST -from fromuser@mail.com


text:
Q: Event clicked in UITableView I have a problem when clicked a row in a UITableView
I used this method didSelectRowAtIndexPath to catch when the user clicks on a row, but doesn't work normally.
the user must press and hold the row to execute the action but do not want it to be so.
Any idea what may be happening?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

   Refunds *current = [refunds_view objectAtIndex:indexPath.row];

   UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
   DetailRefundsViewController *myVC = (DetailRefundsViewController *)[storyboard     instantiateViewControllerWithIdentifier:@"DetailRefundsViewController"];
[self presentViewController:myVC animated:YES completion:nil];
 }

Thanks.
Best Regards.

A: In my case, your code is instantly work, just modify class name and Storyboard Identifier.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    LJWDetailViewController *myVC = (LJWDetailViewController *)[storyboard instantiateViewControllerWithIdentifier:@"LJWDetailViewController"];
    [self presentViewController:myVC animated:YES completion:nil];
}

I think, some of your codes are block this didSelectRowAtIndexPath: Method.
find out which controls are block this method
and set those control's delaysContentTouches Property by NO like this.
_imageScroll.delaysContentTouches = NO;

Sorry for Poor English :<

A: If you're using StoryBoards, then I think you're better off using a push segue directly from the TableViewCell to the ViewController you want in the Interface Builder (control click and drag from the TableViewCell to the ViewController). Make sure to give the segue a name (in my case below "showDetail"). Then implement the code below:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showDetail"]) {
        [[segue destinationViewController] setDetailItem:object];
    }
}


text:
Q: Is it possible to have Sharepoint display a Shared Exchange calendar? The reason for this is that we use Live meeting heavily.  While you can create a live meeting in a SharePoint calendar, because it is just a list, the links do not work if accessed through Sharepoint.
We would need to have these links work properly.
We use MOSS 2007 and Exchange/Outlook 2007

A: I'm not sure I fully understand your question - but this might prove useful:
You can use setup MOSS lists to receive incoming mail and then send a meeting invite to that email address. Create a calendar list, and in the list settings select 'Incoming e-mail settings' (If you haven't set this up on your MOSS farm, you can Google how to do so)
Allow your list to receive email by checking the box and give your list a suitable email alias. Allow your list tor receive attachments and accept mail from any sender (you could dive into permission-based senders if you want, but outside scope of this).
Now whenever you setup a meeting just include the email alias you used for the list as a meeting request recipient. The list will receive the email and include the meeting on your calendar with the appropriate details.
You can then overlay this shared calendar in your outlook if you select 'Actions' - 'Connect to Outlook' from the calendar list.
May have misread your intention here - so sorry if the above is not relevant.


text:
Q: Möbius transformation sending line and circle to concentric circles I want to find some Möbius transformation sending the line $l$ defined by $Re(z) = 5$ and the circle $\vert z\vert = 4$ to concentric circles in the complex plane. I know that Möbius transformations preserve (generalized) circles and that möbius transformations are closed under composition via its group structure.
So the simplest inversion Möbius transformation $T_1(z) = \frac{1}{z}$ turns $l$ into the circle with radius $\frac{1}{10}$ situated at  $\frac{1}{10} +0i$. I can then turn it into the unit circle by two composed möbius transformations moving it to the left by $\frac{1}{10}$ and then scale it by $10$. Even if this is correct, how can I make sure that $\vert z\vert = 4$ stays somewhat "invariant" so that encloses the image of my line $l$?

A: One possible method is to find points $a, b$ which are symmetric with
respect to both the given circle $C$ and the given line $l$, and then choose $T$ as a Möbius transformation which sends $a, b$ to $0, \infty$:
$$
 T(z) = \frac{z-a}{z-b}
$$
Möbius transformations preserve symmetry, therefore $0, \infty$ are
symmetric with respect to both $T(C)$ and $T(l)$, which are therefore
circles centered at zero.
The symmetry of the problem suggest to search for real $a, b \in \Bbb R$.  Then symmetry with respect to the line $\operatorname{Re} z = 5$
means  $a + b = 10$, and symmetry with respect
to the circle $\vert z \vert  = 4$ means $ab = 4^2$.
So $a, b$ are the solutions of the quadratic equation $x^2 - 10 x + 16 = 0$, which can easily be determined.

A: In the desired concentric situation, all lines through the common center will ber perpendicular to both circles. These must correspond to circles/lines that are perpendicular to the given circle and line and intersect in two points. If you bring one of these two points to infinity, you should be done.
So how do we find enough of these common perpendicular circles/lines?
One is easy: Take the line through the origin of the circle and perpendicular to the line.
Another can be found as circle around any point on the line (so that it at least intersects the line at a right angle) of suitable radius, obtained using Pythagoras from the given circle's radius and the distance.


text:
Q: Could Data filter the CO2 out of the air? In Act 1 of Episode 5x04 (Silicon Avatar)

Back on the planet, the colonists have taken shelter underground. Data believes that the refractory metals in the rock strata will protect them. Crusher is concerned that they and the settlers will run out of air soon.

Data, Riker, Dr. Crusher and a number of colonists are sealed into an underground cavern, and they start to run out of oxygen.
According to Memory Alpha concerning respiratory systems

The Android Lieutenant Commander Data also had a functional respiratory system with the purpose to maintain thermal control of his main systems. Data explained this to Doctor Julian Bashir after he noticed that Data was breathing. (TNG: "Birthright, Part I")

Why couldn't Data reprogram/use his respiratory system to filter out the carbon in the air and exhale oxygen?  Even if it was a percentage of what was needed, it would extend the time in the cave by some degree, I'm sure.

A: That article doesn't say anything about Data being able to generate oxygen from CO2. It only implies that his apparent "breathing" is used for cooling (therefore, not true respiration).
In other words, Data uses air cooling, and that's part of the purpose of his apparent breathing. That's all which has been stated in canon.
A regular air cooling system might have the ability to filter out particulates beyond a certain size but not the ability to filter out CO2 (as a rebreather does) or split CO2 into C/CO and O2. Filtering out particulates makes sense for cooling systems to prevent dust buildup in the cooling system. But O2 extraction has no beneficial effects for air cooling (in fact, the techniques used, such as electrolysis or laser-excitation of CO2 to produce C and O2 or CO and O2 would likely generate more heat in the system in addition to taking up more space).

A: The most obvious answer is that Data's breathing doesn't use up oxygen and create carbon dioxide. As you've noted in your question, the reason he draws air into his body is for thermal regulation, e.g. to remove the heat from his system.

DATA: Yes. I do have a functional respiration system. However, its
  purpose is to maintain the thermal control of my internal systems. I
  am, in fact, capable of functioning for extended periods in a vacuum. - Birthright, Part I

Even if it were the case that his respiration was classical (e.g. converting oxygen and sugars into CO2 + energy) then turning it around using some form of chemosynthesis or photosynthesis (e.g. turning CO2 and energy into oxygen and sugars) would be next to impossible in the short time available. It would be like trying to get a combustion engine to run on fumes and create petrol.

In-universe, Crusher and Geordi are recognised experts at operating on Data's systems. Data himself is probably the Federation's foremost expert in Soongian android design and maintenance. Short of having Bruce Maddox with them, they've literally got the full set of the Federation's most knowledgeable engineers with regard to Data's systems and capabilities all in one place.
The fact that none of them even suggested it at the time would strongly suggest that it simply can't be done.

A: In addition to the other answers pointing out that Data's respiratory system was for primarily for temperature control, and not necessarily for gaseous exchange (although, from other episodes he does seem to need some bio-material, and that may have by-products requiring excretion), there is also the question of how much air volume Data would need to process if he could.
Only two colonists were lost to the crystalline entity - and it could be assumed that all surviving colonists and away team were in the same cave. For a viable initial colony, there's probably at least 100 people there - maybe a lot more. As Lese Majeste points out in his comment below - that'd mean Data would have to scrub thousands of litres of air each minute.
(for Americans - 1 cubic foot is 28 litres - in liquid terms, that's about 7.5 US gallons)


text:
Q: Flutter, Cannot Build For iOS: Missing .h-Files Building our Flutter project fails on iOS. The following steps work without problems:

*

*running on the XCode simulator (flutter run)

*building in the terminal (flutter build ios)

*running on a real device in debug mode (flutter run -d "abcd")

If I open the project in XCode, change the build target to "Generic iOS Device" and hit "Build" or "Archive" I get the following error:
/Users/.../development/testproject/ios/Runner/GeneratedPluginRegistrant.m:6:9: 'flutter_exif_rotation/FlutterExifRotationPlugin.h' file not found
After removing the FlutterExifRotationPlugin, the error reoccurs with the next plugin alphabetically, so I figured that plugins in general don't work at the moment.
I tried:

*

*dev, stable and master channels of flutter

*reinstalling XCode

*reinstalling Flutter

*create a new project and moving the old files there

But nothing worked so far.

A: Ok the solution was very simple. I had to open the .xcworkspace file instead of the .xcodeproject one.
One WEEK went down the pipe for this error. I hope that you, future reader, will find this comment useful.


text:
Q: Round off Issue with Decimal SELECT CAST(960 AS NUMERIC(18,2)) -- it gives 960.00
SELECT CAST(178.5 AS NUMERIC(18,2)) -- it gives 178.50

I need the result 960 and 178.5, how could I do that

A: use below
SELECT CAST(960 AS NUMERIC(18,0)) -- it will give 960

SELECT CAST(178.5 AS NUMERIC(18,1)) -- it will give 178.5


text:
Q: Obtener el valor seleccionado de radio buttons para hacer cálculos Tengo un formulario donde solicito varios datos, entre ellos el valor del envío se calcula de acuerdo a su ciudad, la sorpresa se calcula cuando deciden incluir una sorpresa en su pedido, en este orden de ideas ambas son input selects.
No he tenido problemas al sumar los subtotales y los totales de lo anterior. Sin embargo, el cambio sub-total depende de un input radio, el cual no he dado para sumarlo sin que me de error, es decir:
El subtotal depende de escoger uno de 3 planes y su valor varía de acuerdo al precio:

*

*bimensual $45000

*mensual $50000

*única vez $55000

de que manera puedo cambiar su valor sin que sea fijo la variable sub-total, sino que cambia al seleccionar una de esas radios...
Dejo el código de mi desarrollo.
<input type="radio" name="planes" class="planes" value="45000">1
<input type="radio" name="planes" class="planes" value="50000">2
<input type="radio" name="planes" class="planes" value="55000">3

Sub-total  ($) : 45000

Envío ($) : 0

Sorpresa ($) : 0

 Total ($) : 45000

Igualmente intenté cambiando la variable del subtotal de la siguiente manera:

Sub-total  ($) : 45000

Con lo anterior, logré traer el dato del plan escogido al subtotal, sin embargo, me deja de calcular los demás valores de sorpresa, envío y total y me da error.
¿De que manera puedo calcular la sumatoria de los inputs de select y radios de manera correcta con el primer código que realicé? especialmente en los inputs de radios porque los selects me calculan sin problema los valores.
De antemano, muchas gracias por su amable colaboración.

A: Si tienes problemas para obtener el valor seleccionado en los radio buttons, lo que puedes hacer es crear una función que coloque el valor del subtotal en la variable:
function setsubtotal(valor){
  subtotal=valor;
  document.getElementById("subtotal").innerHTML = subtotal;
}

y agregarles un onclick a los radios con la función y su valor:
onclick="setsubtotal(45000)"

de ese modo ya puedes obtener sus valores para hacer las sumatorias:

var subtotal = 45000;

function setsubtotal(valor){
  subtotal=valor;
  document.getElementById("subtotal").innerHTML = subtotal;
  console.log(`el subtotal es :${subtotal}`);
}

function costoFinal(){
            var ciudad = document.getElementById("ciudad").value;
            var sorpresa = document.getElementById("sorpresa").value;

            var total = (parseInt(ciudad)) + (parseInt(sorpresa)) + (parseInt(subtotal));
            var envio = (parseInt(ciudad));
            var sorpresaadicional = (parseInt(sorpresa));

            document.getElementById("envio").innerHTML = envio;
             document.getElementById("sorpresaadicional").innerHTML = sorpresa;
            document.getElementById("result").innerHTML = total;
            document.getElementById("subtotal").innerHTML = subtotal;
        }
<input type="radio" name="planes" class="planes" value="45000" onclick="setsubtotal(45000)" checked>1
<input type="radio" name="planes" class="planes" value="50000" onclick="setsubtotal(50000)">2
<input type="radio" name="planes" class="planes" value="55000" onclick="setsubtotal(55000)">3

Sub-total  ($) : 45000

Envío ($) : 0

Sorpresa ($) : 0

 Total ($) : 45000

No olvides colocar checked al radio seleccionado por defecto.
Espero sea lo que buscas, saludos.


text:
Q: Is there a Linux console command line MVC framework? Is there a framework for developing Linux console application, where controllers are console commands and views are their stdout output?

A: If you don't mind using Python, the cmd module might be worth looking into.


text:
Q: Wildlfy module.xml Configuration for one java class I am testing an java application and getting this error:
org.jboss.naming.remote.protocol.NamingIOException: Failed to rebind [Root exception is java.io.IOException: java.lang.ClassNotFoundException: de.brockhaus.userMgmt.control.process.SomeProcess from [Module "org.jboss.remote-naming:main" from local module loader @ed17bee (finder: local module finder @2a33fae0 (roots: C:\Program Files\jboss\wildfly\modules,C:\Program Files\jboss\wildfly\modules\system\layers\base))]]
...
Caused by: java.io.IOException: java.lang.ClassNotFoundException: de.brockhaus.userMgmt.control.process.SomeProcess from [Module "org.jboss.remote-naming:main" from local module loader @ed17bee (finder: local module finder @2a33fae0 (roots: C:\Program Files\jboss\wildfly\modules,C:\Program Files\jboss\wildfly\modules\system\layers\base))]

So my purpose is modifying the module.xml file of
C:\Program Files\jboss\wildfly\modules\system\layers\base\org\jboss\remote-naming\main
<module xmlns="urn:jboss:module:1.3" name="org.jboss.remote-naming">
    <resources>
        <resource-root path="jboss-remote-naming-2.0.4.Final.jar"/>
    </resources>

    <dependencies>
        <module name="javax.api"/>
        <module name="org.jboss.ejb-client" optional="true"/>
        <module name="org.jboss.remoting"/>
        <module name="org.jboss.logging"/>
        <module name="org.jboss.marshalling"/>
        <module name="org.jboss.marshalling.river"/>
        <module name="de.brockhaus.userMgmt.control.process"/>
    </dependencies>
</module>

But this also gives errors. I would like to know how to change this above xml file in order to achieve the things working right.

A: Instead of modify jboss system modules
you can create your own modules
create a directory /modules/com/xyz/some/main
with files

*

*module.xml

*some-class.jar
some-class.jar
module.xml
<module xmlns="urn:jboss:module:1.3" name="com.xyx.some">
    <resources>
        <resource-root path="some-class.jar"/>
    </resources>

    <dependencies>
        <module name="org.jboss.remote-naming"/>
    </dependencies>
</module>

and add it as part of global module configuration
open file /standalone/configuration/standalone-full.xml
<subsystem xmlns="urn:jboss:domain:ee:4.0">
            <global-modules>
                <module name="com.microfocus.itom.nom.common" slot="main"/>
            </global-modules>


text:
Q: Is it possible to host R shiny app on AWS Lambda I've never seen any documentation about this and I'm planning on trying it for myself and documenting it if it works.
But the question is, can you host an R Shiny app on just AWS Lambda? A dynamic app where a user can enter inputs, use reactives, render new plots...etc.
Say for example we have this function which is an R shiny app
binner <- function(var) {
  require(shiny)
  shinyApp(
    ui = fluidPage(
      sidebarLayout(
        sidebarPanel(sliderInput("n", "Bins", 5, 100, 20)),
        mainPanel(plotOutput("hist"))
      )
    ),
    server = function(input, output) {
      output$hist <- renderPlot(
        hist(var, breaks = input$n,
          col = "skyblue", border = "white")
      )
    }
  )
}

We then call this function from any of the runtimes AWS Lambda supports such as Python, would this work?


text:
Q: In C (also C++), how '&' operator works as both address operator and bitwise operator ? As operator overloading is not supported by C The operator '&' can be used in both of following way  int a; scanf("%d",&a);
and printf("%d",1&2).
But different behaviour (for first as address operator and second time as bit-wise operator).
I know operator overloading is not there in C. Then how it works ?. Also highlight for c++.

A:
I know operator overloading is not there in C.

This is incorrect. a + b performs integer addition if a and b are integers, floating-point addition of a and b are floating-point numbers, and pointer arithmetic if a or b is a pointer.
C has operator overloading built into the language. It does not support custom operator overloading defined by the program.
In the case of & being an operator for taking an address and for performing a bitwise AND, the distinction is made by the language grammar. The & for taking an address can appear only applied to a cast-expression in the grammar. The & for bitwise AND can appear only after an AND-expression and before an equality-expression. These "tokens" (cast-expression, AND-expression, and equality-expression) may be unfamiliar to you, but they are formally defined in the grammar for the C language, and, as the compiler is parsing source code, it recognizes the structure of expressions and matches the source code to the tokens of the grammar. This is also true for C++ except for a minor technical difference: In C++, one of the tokens is and-expression instead of AND-expression.
The definition of the grammar is such that recognition of these tokens always uniquely distinguishes how the & operator is being used.

A: In "C" language, operators have different meaning when they are used as prefix to expression, suffix to expression or "infix" (between two expressions).
Consider '*', which performs multiplication as 'infix' operator, and pointer indirection when used as a prefix. Similarily, the '-' operator, which performs subtraction as 'infix' operator, and negation when used as a prefix.
Basically, it's not about overriding, it if the operator appears between two expressions, or as a  prefix to a single expression.
In the same way, The "C" compiler knows if the '&' is bit-wise and, or address-of, based on it's position is the expression: If it is between two expressions, it's the AND, if it is before an expression, it is 'address-of'.
See https://en.wikipedia.org/wiki/Infix_notation about infix.

A: C does not support operator overloading (beyond what it built into the language).
As you can see in this Wikipedia Operators in C
The Address-of ("address of a")     "&a" is defined as R* K::operator &();
whereas
The Bitwise AND     "a & b" is defined as R K::operator &(S b);
So basically the "&" operator has different meaning when used as a unary operator and as a binary operator operator. The same goes for various other operators like, "*" , "-", etc.

A: It has simple different meanings when applied to the lvalue (it the unary operator in this case) or when it is used in the math expression with two operands.

A:
"The operator & can be used in both of following way int a; scanf("%d",&a); and printf("%d",1&2)."

Note that in the case of C++ you forgot another important third use. The & operator can also be used to declare references.
int x = 24;
int& r_x = x;

A: the language divides operators based on its operands first. In one category itself overloading can be in-built. Your example is about the first division. Address-of is a unary operator and bitwise-AND is a binary operator. when you write operator function in c++ you will see the difference of these two categories.
Operator overloading is inbuilt to languages. example simple arithmetic addition operator. it can work with simple one-byte integer data as well as float (significant & exponent). Basically it is there with maths. so while making C language, they just translated those into functionality. In C specification, you cannot find overloading as a keyword for this behavior. According to them, after formula expression, anything has to be expressed as different functions. Each function should be named based on the functionality that it offers. When C++ introduced an opportunity to create new types, operators with its basic n-nary form allowed to operate with new types. In a nutshell, C's philosophy was different.


text:
Q: Error in mindist[l] <- ndist[l] : NAs are not allowed in subscripted assignments, while using the predict method in mixture discriminant analysis in R I have been stuck at this error for very long.
I am trying to use mda function from MDA package in R.
After I have fit the model on my data, I am encountering the following error while I am trying to get predictions on the training data itself(same error while predicting on test data)
> Error in mindist[l] <- ndist[l]: NAs are not allowed in subscripted assignments
The error traces back to the predict method of the function.
I am not able to understand the root cause of the error after extensive debugging.
Here are some stats about my data:

*

*I am calling the function using rpy2 interface in python since I am working in python and wanted to use this particular R function

*The dataset is not very large, around 200 rows and 500-600 columns, I know the features are exceeding the number of samples, but the problem seems to be independent of that since the error comes in predict function and not while training the model, secondly I have tested another dataset as well with no. of rows> no. of features, that gives same error, and most importantly I am anyway using Dimensionality reduction.

*The error comes only for a particular configuration: when I DO NOT scale my input data before training. Although, When I scale the data, the error disappears.

*Line of Error - error comes at 2nd line, in predict method.

    mda_clf = r['mda'](formula="Class~.", data=Dataset, method=r['polyreg'] )

    training_pred = r['predict'](mda_clf, X_train)

*I have checked multiple times , my data does not contains any NAs, I have printed the data before feeding it to the predict function to manually see it and used functions to check for NAs as well.

I am having hard time understanding the meaning of error, my data doesn't contains any NA values, the same function works when I scale the data. But the model trains in both the cases.
Any help would be appreciated.

A: I wanted to update that I found the error, actually at a certain point in my script, my X_train, which obviously should have been a matrix of floating point numbers was mistakenly converted into string type. For ex- if a row of X_train should be [0.123, 0.456, 0.542], it was converted into ['0.123', '0.456', '0.542'] in which the values got converted into string type.
So, in the following line where the error came
training_pred = r['predict'](mda_clf, X_train)

my model was not able to recognize any value since none were of float type thus giving the error.


text:
Q: purchase a downloadable product as guest checkout it does not appear in my downloadable products section When I purchase a downloadable product as a guest and create account after that. The downloadable products  does not appear in the my downloadable products section after completed purchase but invoice is appear in My Orders.
I got an answer that the fix for this issue has already available in 2.2-develop branch.
Where I can get that.
My magento ver is 2.2.6
https://user-images.githubusercontent.com/33385380/45645670-32319500-ba8f-11e8-8966-0979b54273e7.jpg

A: You may consider patching the core file, by rolling the changes in \Magento\Checkout\Model\GuestPaymentInformationManagement::savePaymentInformationAndPlaceOrder  from following commit back, as I did in my case.
https://github.com/magento/magento2/commit/e76430179fd9679f448883d05be40ae5423dd067?diff=unified#commitcomment-30923778
This issue is present since magento 2.2.4


text:
Q: Checking if enum type contains constant with given name I have multiple enums in my code:
public enum First { a, b, c, d; }

public enum Second { e, f, g; }

I want to have one method that checks to see if a value is present in any enum using valueOf() without writing one for each enum type.  For example (this code does not run):
public boolean enumTypeContains(Enum e, String s) {
    try {
        e.valueOf(s);
    } catch (IllegalArgumentException iae) {
        return false;
    }
    return true;
}

Usage:
enumTypeContains(First,"a"); // returns true
enumTypeContains(Second,"b"); // returns false

Any ideas on how to do something like this?

A: Here is your solution:
public static boolean contains(Class<? extends Enum> clazz, String val) {
   Object[] arr = clazz.getEnumConstants();
   for (Object e : arr) {
      if (((Enum) e).name().equals(val)) {
         return true;
      }
   }
   return false;
}

It gets all of the enum's vaules and checks to see if it has a value that shares a name with the parameter you passed in.  If so, then it returns true, otherwise it returns false.
This has been tested and works.  Test code:
public class Test {
   public static void main(String[] args) {
      System.out.println(contains(Haha.class, "Bad"));
      System.out.println(contains(Haha.class, "Happy"));
      System.out.println(contains(Haha.class, "Sad"));
   }

   static enum Haha {
      Happy, Sad;
   }
}

Prints:
false
true
true

A: I found another variant which has neither to iterate all enum constants nor to throw an exception ... but it is implementation specific, i.e. uses undocumented methods. It works for Sun's JDK 1.6.0_20 (and was made by reading the source code from 1.6.0_13).
public static <E extends Enum<E>> boolean enumTypeContains(Class<E> e, String s) {
    try {
        Method enumDir = Class.class.getDeclaredMethod("enumConstantDirectory");
        enumDir.setAccessible(true);
        Map<?,?> dir = (Map<?,?>)enumDir.invoke(e);
        return dir.containsKey(s);
    }
    catch(NoSuchMethodException ex) {
        throw new Error(ex);
    }
    catch(IllegalAccessException ex) {
        throw new Error(ex);
    }
    catch(InvocationTargetException ex) {
        throw new Error(ex.getCause());
    }
}

If we were in the java.lang package, this could simply look like this:
public static <E extends Enum<E>> boolean enumTypeContains(Class<E> e, String s) {
    return e.enumConstantDirectory().containsKey(s);
}

This uses the method Class.enumConstantDirectory(), which (on first call) creates and (later only) returns a map with all the enum constants as values, their names as key. (Just such a map one could also create manually.)
This method is used internally by Enum.valueOf(Class, String), and supposedly also by EnumType.valueOf(String) (depends on compiler).
On the first call of enumConstantDirectory or getEnumConstants(), a private helper method invokes EnumType.values() (which is implemented by the compiler). The result is then reused for following calls of these two methods.

A: This should work:
public <E extends Enum<E>> boolean enumTypeContains(Class<E> e, String s) {
    try {
        Enum.valueOf(e, s);
        return true;
    }
    catch(IllegalArgumentException ex) {
        return false;
    }
}

You then have to call it by
enumTypeContains(First.class, "a");

I'm not sure if simply searching through the values (like in the answer from jinguy) might be faster than creating and throwing an exception, though. This will depend on how often you will get false, how many constants you have, and how long the stack trace is (e.g. how deep this is called).
If you need this often (for the same enum), it might be better to create once a HashSet or a HashMap mapping the names to the enum values.


text:
Q: Good book or resource that talks about custom connectors and SharePoint search Integration? Do you know any good books or resources that explains how to write your own custom connector for search crawling?
I have been reading Professional Business Connectivity Services in SharePoint 2010 which talks about what I want to learn but by skipping several necessarily steps to be able to follow. I need a resource that talks about the same things but in a more step by step way.
Thanks

A: Here is a resource on MSDN - http://msdn.microsoft.com/en-us/library/ff625800.aspx
And a followon article by Cory Roth on how to debug them - http://dotnetmafia.sys-con.com/node/1525610


text:
Q: Drag and drop of image in Chrome I'm trying to write a script for drag and drop of image in  a  iframe in Chrome.

 this si a testing doc.here, we test the things

Is is not working..
In chrome console , I get this error message:

Uncaught Error: WRONG_DOCUMENT_ERR: DOM Exception 4

Something wrong with selection and range, i guess.

A: A DOMException.WRONG_DOCUMENT_ERR exception is thrown whenever a DOM manipulation method tries to work with nodes that are part of two different DOMDocuments. You must use the DOMDocument.importNode method in order to import a DOMNode from one document to another.
I suppose you have to import the image-node to the iFrame-document
something like (untested):
var nodeToImport = _doc.importNode(_image, true);
//nodeToImport can now be added to the second document
 _doc.appendChild(nodeToImport);

more here


text:
Q: Are the Alt+Ctl+FN key combinations (aka srvrkeys) hardcoded into Xorg? Are the Alt+Ctl+FN key combinations (aka srvrkeys) hardcoded into Xorg?
This question explains how to turn them on and off (I already knew that, just mentioning it to show I have done my homework). But what I need now is to keep the feature but bound to different key combinations, perhaps just Alt+FN like the usual Linux VT bindings. Possible?
The reason is that on my preferred leop^H^H^H^Hkeyboard the Alt+Ctl+FN combinations effectively don't exist :-(.

A:
Are the Alt+Ctl+FN key combinations (aka srvrkeys) hardcoded into Xorg?

No, they're not. They can be configured via Xkb. But understanding how to effectively and correctly configure Xkb would take someone more than a lifetime ;-).
But as a simple hack, completely client-side, this should allow you to switch with just Alt-F1 instead of Ctrl-Alt-F1 [See the diff at the end if your layout is so different that the ed script doesn't work]:
xkbcomp $DISPLAY - > xkb
cp xkb xkb~
ed xkb <<EOT
/type "CTRL+ALT"/
/Level5/s/Control+//p
w
EOT
xkbcomp - $DISPLAY < xkb

However, notice that your desktop environment may override your changes. Also,  just Alt-Backspace (a common keybinding in some editors) instead of Ctrl-Alt-Backspace may kill your X11 server, if you have that option enabled (look for Terminate_Server in the generated xkb file above).
diff xkb~ xkb
...
@@ -376,15 +376,15 @@
     type "CTRL+ALT" {
         modifiers= Shift+Control+Alt+LevelThree;
         map[Shift]= Level2;
         preserve[Shift]= Shift;
         map[LevelThree]= Level3;
         map[Shift+LevelThree]= Level4;
         preserve[Shift+LevelThree]= Shift;
-        map[Control+Alt]= Level5;
+        map[Alt]= Level5;
         level_name[Level1]= "Base";
         level_name[Level2]= "Shift";
         level_name[Level3]= "Alt Base";
         level_name[Level4]= "Shift Alt";
         level_name[Level5]= "Ctrl+Alt";
     };
     type "LOCAL_EIGHT_LEVEL" {


text:
Q: Visualforce Remoting Exception: Input too long I am getting the following error while trying to upload an excel file. What would be the best way of reducing the size of request?
https://help.salesforce.com/HTViewSolution?id=000193799&language=en_US

A: You can use action function instead of visualforce remotting.
Example:
Page:
<apex:actionfunction name="js_functionName" action="{!apexMethod}" >
<apex:param name="apexvariableName" value="" assignTo="{!apexvariableName}"/>

Java-Script:
js_functionName(longInputs);

Controller:
public string apexvariableName{get;set;}

public void apexMethod(){

   //Input parameter can be accessed using apexvariableName variable
}


text:
Q: Is it possible to create our own Solidity library? I am building a lottery D-App now based on Ethereum.
While creating a smart contract, I found that Solidity has no method to generate random numbers.
Solidity is not capable of creating random numbers.
So I've created my own method to generate random numbers using timestamp.
Is it possible to make this method as a library so that everyone can use my method with a simple import command?
If it's possible, many developers could save their time.

A: I believe you could deploy your PRNG contract, and allow other callers to use it, or alternatively publish its code on some public repository (e.g. github), allowing developers to add it directly in their code (using the import command).
Please note using the block timestamp as a source of randomness is considered insecure:
https://medium.com/dedaub/bad-randomness-is-even-dicier-than-you-think-7fa2c6e0c2cd
This post suggests overcoming the randomness challenge using an external oracle (requires trust in the oracle operator) or some commit-reveal scheme (e.g. several participants send hashes of random seeds - this is the commitment, and later they all reveal the preimages. The seed is defined to be some mix of the preimages, e.g. their XOR).
Another approach is to use a VDF (verifiable delay function). Here is an example of an implementation of a VDF by StarkWare including detailed information on how can it be used to provide secure randomness on Ethereum https://medium.com/starkware/presenting-veedo-e4bbff77c7ae.


text:
Q: How to marshal object with array of objects? I have problems with marshaling.
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public class Book
    {

        [MarshalAs(UnmanagedType.LPArray, SizeConst = 1000)]
        public Page[] astInject2;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public class Page
    {
        public int n;
    }

Why calling Marshal.SizeOf(typeof(Book)) throws an ArgumentException:
Type 'Book' cannot be marshaled as an unmanaged structure; no  meaningful size or offset can be computed.

?
Is there any solution?
I'm marshalling Book object to C++ struct.
If I do this:
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct Book
    {

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1000)]
        public Page[] astInject2;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct Page
    {
        public int n;
    }

then Marshal.SizeOf(typeof(Book)) returns 4000 as it should.
Note that I can't define Book as struct, it has to be class.


text:
Q: "I thought he is/was a good boy." Which tense is correct? "I think he is a good boy". If I convert this to the past tense, which one mentioned below would be the answer ?

*

*I thought he is a good boy.

*I thought he was a good boy.

Kindly explain why they are right/wrong (for both the sentences) ?

A: Was.
This is called backshifting and is most often used with indirect reported speech.  However it's also something English speakers do when talking about internal thoughts, emotions, or unspoken conversations (think, feel, guess, reason, know, theorize, intend, plan, etc.)

He thinks I am crazy -> He thought I was crazy.

This of course raises the question whether he still thinks I am crazy.  The past tense implies that he has since changed his mind -- but the truth is, we don't know.  We can sometimes guess from context, or we have to ask the speaker for clarification.
In the same way, when we back-shift we sometimes change the meaning of the sentence.  We say what we thought then, but might not think now:

I think it's a good idea to go to the beach today.
  I thought it was a good idea to go to the beach today (but now it's raining, so I guess I was wrong).
I think it would be a good idea to go to the beach today
  I thought it would have been a good idea to go to the beach today (but then my son got sick and we couldn't go).

But not always.  Sometimes we're just talking about an internal thought that happened in the past, and is still true:

I guess that Darth Vader is Luke's father.
  I guessed that Darth Vader was Luke's father.

Exception:  If you relate your past thought to a current condition, you can use the present tense to indicate it's still true today.

Since I was a child I knew that I can't stand broccoli.
  Since I was a child I knew that I couldn't stand broccoli.

It may still sound better to use the past tense, but the present isn't wrong.


text:
Q: Use NSNumberFormatter to map integer to letter? Is there a way to use NSNumberFormatter to map integers to letters or other strings that are not the number spelled out (i.e. 1 -> a, 2 -> b, 3 -> c, etc)?

A: I would not use NSNumberFormatter for something like this. Possible approaches include:

*

*Get the char equivalent:
- (char)characterForValue:(NSInteger)value {
    NSAssert(value >= 1 && value <= 26, @"expecting value 1-26, but received %ld", (long)value);

    return 'a' + value - 1;
}

*Return a string of the character equivalent:
- (NSString *)stringForValue:(NSInteger)value {
    NSAssert(value >= 1 && value <= 26, @"expecting value 1-26, but received %ld", (long)value);

    char c = 'a' + value - 1;
    return [NSString stringWithFormat:@"%c", c];
}

*Have an array or dictionary or string that map your numeric values to strings or characters and look it up in that:
- (NSString *)stringForValue:(NSInteger)value {
    NSString *characters = @"abcdefghijklmnopqrstuvwxyz";

    NSAssert(value >= 1 && value <= [characters length], @"expecting value 1-26, but received %ld", (long)value);

    return [characters substringWithRange:NSMakeRange(value - 1, 1)];
}

or
- (NSString *)stringForValue:(NSInteger)value {
    NSArray *strings = @[@"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", @"i", @"j", @"k", @"l", @"m", @"n", @"o", @"p", @"q", @"r", @"s", @"t", @"u", @"v", @"w", @"x", @"y", @"z"];

    NSAssert(value >= 1 && value <= [strings count], @"expecting value 1-26, but received %ld", (long)value);

    return strings[value - 1];
}

There are lots of other ways to tackle this, but hopefully this illustrates the basic idea. But, bottom line, this is not a problem well suited for NSNumberFormatter.

If you wanted to use emoji, just have an array of those emojis and use that:
- (NSString *)stringForValue:(NSInteger)value {
    NSArray *strings = @[@"", @"", @"", @""];

    NSAssert(value >= 1 && value <= [strings count], @"expecting value 1-%ld, but received %ld", (long)[strings count], (long)value);

    return strings[value - 1];
}


text:
Q: Topology of the automorphic quotient The MO question https://mathoverflow.net/questions/331549/compactness-of-the-automorphic-quotient-and-genericity made me realise that I don't really understand the topology on the adèlic points of an algebraic group $G$.  Indeed, the way I realised this is by making the wrong comment https://mathoverflow.net/questions/331549/compactness-of-the-automorphic-quotient-and-genericity#comment826950_331549.  To save your following the link, the question is about consequences of compactness of $G(F)\backslash G(\mathbb A)$.  Now I thought that, for each place $v$,

*

*the group $G(F_v)$ is a closed subgroup of $G(\mathbb A)$; and,

*since $G(F)$ is embedded diagonally in $G(\mathbb A)$, it intersects $G(F_v)$ trivially; so

*$G(F_v)$ sits as a closed subset of $G(F)\backslash G(\mathbb A)$.
Since further discussion (for example, paulgarrett's answer) showed that the conclusion is wrong, obviously one of the steps is wrong—but I'm embarrassed to say I don't know which one.  Is it the first?  If so, is there any easier way to see why than "because there's a definition of closed set that $G(F_v)$ doesn't satisfy"?


text:
Q: Make sure path doesn't go up a level I want to make sure relativePath doesn't go up a folder past basePath.  Is there any reliable way to detect this?
string basePath = "/myfolder/";
string relativePath;

// Invalid
relativePath = "../foo";
relativePath = "subfolder/../../bar";

// Valid, but if too hard this can also be invalid
relativePath = "subfolder/../subfolder2";

// Valid
relativePath = "subfolder/another..folder/";
relativePath = "subfolder/..anotherFolder/";

// There may be ways to circumvent that I haven't thought of...
// Maybe some of these would work
relativePath = " ../";
relativePath = ".. /";

// fullPath should not be above basePath
string fullPath = basePath + relativePath;

I'm thinking something like the following could work
Path.GetFullPath(basePath + relativePath).StartsWith(basePath)

But I couldn't find a VirtualPathUtility.GetFullPath() or something similar.  I could disallow ../ anywhere in the string, but there may be a way to circumvent that with strange spacing, special characters, etc.

A: You can use Path.GetFullPath to convert all your paths to absolute paths, and then just compare the strings.  That is:
string basePath = "/myFolder/";
string relativePath = "whatever_user_inputs";

string basePathRooted = Path.GetFullPath(basePath);
string relativePathRooted = Path.GetFullPath(relativePath);

if (!relativePathRooted.StartsWith(basePathRooted))
     //Fail


text:
Q: Html table header duplicates with empty body between two pages I have several tables on one page, and when I open the print preview in a browser, I've got some issue as on the screenshot. It happens when one of the tables is not fit to a paper. Is there a valid CSS way to prevent this problem.
Html page to reproduce behavior:

<title>Page Title</title>

                Header cell
                Header cell

                Body cell
                Body cell

                Body cell
                Body cell

                Body cell
                Body cell

                Body cell
                Body cell

                Header cell
                Header cell

                Body cell
                Body cell

                Body cell
                Body cell

                Body cell
                Body cell

                Body cell
                Body cell

Screenshot with issue

A: Use the page-break-inside property, it sets whether a page-break should be avoided inside a specified element.


text:
Q: Blazeds and Spring security, can remember-me be used in this combination? I'm using the latest release of Spring Blzeds integration which has some features making it easier to secure invocations on destination objects. However the basic setup I use which uses the ChannelSet login approach form the flex side looses the authentication information (sessions) on each page refresh. Here's the configuration I'm using:
<http entry-point-ref="preAuthenticatedEntryPoint" >

    </http>

    <beans:bean id="preAuthenticatedEntryPoint" class="org.springframework.security.ui.preauth.PreAuthenticatedProcessingFilterEntryPoint" />

    <beans:bean id="userAccountManager" class="com.comp.service.managers.jpa.UserAccountJpaManager" />
    <beans:bean id="userService" class="com.comp.auth.JpaUserDetailsService" />
    <beans:bean id="defaultPasswordEncoder" class="com.comp.auth.DefaultPasswordEncoder" />

    <authentication-provider user-service-ref="userService">
        <password-encoder ref="defaultPasswordEncoder"/>
    </authentication-provider>

<flex:message-broker>
    <flex:secured />
</flex:message-broker>

<bean id="testService" class="com.comp.service.TestService">
    <flex:remoting-destination channels="comp-amf" />
    <security:intercept-methods>
        <security:protect method="say*" access="ROLE_USER" />
    </security:intercept-methods>
</bean>

Is there another way to configure/implement this so I could get persistent sessions (remember me). Is it possible to do the logins from flex over standard HTTP POST (like forms) and still get the same level of granularity for protecting remote object calls?

A: Try adding this to your config:
<http entry-point-ref="preAuthenticatedEntryPoint" create-session="always">


text:
Q: JTable cloumn doesn't get focused anymore Recently I have a small problem with one column in a JTable: since I edited it's DefaultTableCellRenderer the password column doesn't get focused, when I focus a row in the table. Here's a screenshot an my code:
inputsTable.getColumn("Passwort").setCellRenderer(new DefaultTableCellRenderer(){

        private final String ASTERISKS = "*";
        public Component getTableCellRendererComponent(JTable table,
                                                       Object value,
                                                       boolean isSelected,
                                                       boolean hasFocus,
                                                       int row,
                                                       int column) {
            int length =0;
            if (value instanceof String) {
                length =  ((String) value).length();
            } else if (value instanceof char[]) {
                length = ((char[])value).length;
            }
            setText(asterisks(length));
            return this;
        }
        private String asterisks(int length) {
            if (length > ASTERISKS.length()) {
                StringBuilder sb = new StringBuilder(length);
                for (int i = 0; i < length; i++) {
                    sb.append('*');
                }
                return sb.toString();
            } else {
                return ASTERISKS.substring(0, length);
            }
        }
    });

I have already tried some different options, but they didn't help me, unfortunately. Does anyone of you have eventually a clue, is there maybe some better implementation of a password column in a JTable without this problem? Thanks in advance!

A: The DefaultTableCellRenderer implementation posted sets no formatting based upon the current state (in particular the isSelected parameter). To keep default formatting, consider calling the parent method prior to your customization.
                public Component getTableCellRendererComponent(JTable table,
                                                               Object value,
                                                               boolean isSelected,
                                                               boolean hasFocus,
                                                               int row,
                                                               int column) {
                    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                    //do your customization here
                }


text:
Q: Badge progress access Where are the 'Badge progress stats' accessible from?
At the moment I have to:

*

*Access the review page

*Access a review queue

*Point the progress bar

Is there any other way?
I suggest to let these stats be accessible from the badge tab of the user profile.


text:
Q: How to use the delete method in Devise for sign out? rails route failure (performing get) So I have built a mountable Engine and added devise for authentication:
And for some reason the :delete method on links is performing a get here is the relevant code:
Index.html.erb
<%= link_to 'Logout', destroy_user_session_path, :method => :delete, :class => 'navbar-link'  %>
Config/initializers/devise.rb
config.sign_out_via = :delete

Routes
destroy_user_session DELETE /users/sign_out(.:format)      devise/sessions#destroy

Error
No route matches [GET] "/my_engine/users/sign_out"

changing config.sign_out_via = :delete to config.sign_out_via = :get fix's the problem and allows me to sign_out however this is the wrong way to do things a signout should be a delete and would love to get this working if anyone has any ideas
Additional Info (Gems + Ruby Version + Actual HTML displayed on page for logout link)
I am using ruby-1.9.3-p398
this is the html displayed on page for layout link
Logout

and the gems:
Using rake (10.1.1)
Using i18n (0.6.9)
Using minitest (4.7.5)
Using multi_json (1.8.4)
Using atomic (1.1.14)
Using thread_safe (0.1.3)
Using tzinfo (0.3.38)
Using activesupport (4.0.2)
Using builder (3.1.4)
Using erubis (2.7.0)
Using rack (1.5.2)
Using rack-test (0.6.2)
Using actionpack (4.0.2)
Using mime-types (1.25.1)
Using polyglot (0.3.3)
Using treetop (1.4.15)
Using mail (2.5.4)
Using actionmailer (4.0.2)
Using activemodel (4.0.2)
Using activerecord-deprecated_finders (1.0.3)
Using arel (4.0.1)
Using activerecord (4.0.2)
Using bcrypt-ruby (3.1.2)
Using orm_adapter (0.5.0)
Using thor (0.18.1)
Using railties (4.0.2)
Using warden (1.2.3)
Using devise (3.2.2)
Using bundler (1.5.2)
Using hike (1.2.3)
Using tilt (1.4.1)
Using sprockets (2.10.1)
Using sprockets-rails (2.0.1)
Using rails (4.0.2)

A: So I figured it out that engines (possibly just --mountable) do not include jquery to do things like :delete or :post so my fix was  to include jquery-rails
engine.gemspec
+ s.add_dependency "jquery-rails"

app/assets/javascripts/engine/application.js
+//= require jquery
+//= require jquery_ujs
+//= require_tree .

A: Same problem here.
I just add:
#layouts/application.html.haml
= javascript_include_tag "application"


text:
Q: Don't allow user to use their dupehammer to reopen their own question There was recently a question on Stack Overflow that was a duplicate of a previous question. I voted to close as dupe, and as I have dupehammer privileges in a relevant tag, it was closed immediately. The OP then used his dupehammer to reopen it.
It seems to me that you shouldn't be able to reopen your own question with a dupehammer.

A: I disagree. The dupe-hammer is a special privilege for trusted users that are experts in a certain tag. If a question of such user gets closed as duplicate and OP edits his question to clarify it is not a duplicate, than he should be able to reopen it.
If a user misused his privilege, like it seems in this case, proper action should be taken, maybe by a moderator.

A: Why not? What harm can be done?
The gold dupe hammer can work only one single time to each direction.
If the question is really a duplicate, other users can still close it again and the OP won't be able to fight it anymore.
Users with enough experience on the site are trusted to use their power wisely, same way as moderators, so in my opinion should not be blocked when it comes to their own questions/answers.


text:
Q: Registering sidebar with or without hook I'm little bit confused on it. When registering sidebar in a function file of Wordpress, we use register_sidebar() function and pass arguments in it.
Without using any action hook, the sidebar works very fine. However, in the codex i've seen a action hook named 'widget_init' is used to register sidebar. So, my confusion is what is the standard approach to register a sidebar, with or without action hook ?

A: I found this interesting piece on registering sidebars which says

Bad sidebar code
There are some common things I would like to see changed within
themes. Not all of these things are technically incorrect, but they
can present some unintended consequences or are just needless bits of
code.
Problem #1: Randomly dropping code into functions.php
If you're a theme developer, you should be familiar with WordPress'
built-in hooks. Not only should you be familiar with them, you should
actually be using them.
The biggest issue I see is sidebar code just being dropped into
functions.php. You should create a sidebar registration function and
hook it to widgets_init. You can see an example of this in the
"Registering a dynamic sidebar" section above.
The reason this is important is so that child themes (and even
plugins) can know exactly when a sidebar was registered. This gives
child themes the opportunity unregister a sidebar if needed. Plus, not
doing it this way is just plain sloppy.

As a sidenote to this: You should never just drop code into
functions.php. Always use the hooks WordPress provides to execute your
functions when they should be executed in the WordPress flow.


text:
Q: Why do we want to define a $k$-scheme to be birational if the rational map (and its inverse) to $\Bbb A_k^n$ is over $k$? Two varieties $X,Y$ are said to be birational if there exist rational maps in each direction such that either composition is the identity on a open dense subset. Note that here the morphisms aren't assumed to be over any base scheme.
However, to say that an integral finite type $k$-scheme is rational (i.e. birational to $\Bbb A_k^n$), one imposes that the rational map (and its inverse) to $\Bbb A_k^n$ be over $k$. Why?
An integral finite type $k$-scheme, by definition, can be covered by finitely many $U_i =\operatorname{Spec}k[x_1,...,x_{n_i}]/I_i$, but, if I understood everything correctly so far, there is no restriction on how $k$ maps into $k[x_1,...,x_{n_i}]/I_i.$ I suppose that it doesn't even have to land in $k$ as shows the example $\phi:\Bbb Q(\sqrt 2)\rightarrow\Bbb Q(\sqrt 2)[x_1]/(x_1^2-2)$ by $1\mapsto 1, \sqrt2\mapsto x_1$.
EDIT: I realize now that what I said in the last paragraph is not entirely correct. For a finite type $k$-scheme, one can actually find affine opens $\operatorname{Spec} B_i$ such that $B_i$ is a finitely generated $k$-algebra. This means that $k$ maps into $B_i=k[x_1,...,x_{n_i}]/I$ in the obvious (standard) way. This doesn't mean, however, that you cannot find other $A_j$, also of the form $k[x_1,...,x_{n_j}]/J$ into which the map induced by $\operatorname{Spec}k\rightarrow X$ maps $k$ into $A_j$ in a non-standard way (as in my example above).

A: Which source are you reading? When dealing with varieties over a field $k$, of course one only considers morphisms over $k$. This applies - in particular - to birational maps. They are (partially defined) $k$-morphisms.
When you consider morphisms not over $k$, you actually leave the category of varieties and work in the larger category of schemes. So we have a(nother) secret application of a forgetful functor.


text:
Q: How can I accept requests from anyone on the Internet? I have a simple HTTP server implemented on Node, though I have tried to do the same thing with other languages and could not figure out how to.
I can pick some port on localhost, say, 1337, and respond to requests just fine on my machine. I then want to access the server from the browser on my smartphone. Leaving it listening on localhost doesn't work (which is just as I expect). Then I try either my own IP, which I get googling my ip, or 192.168.1.1, which I understand refers to the LAN. I try these with several ports.
Both of those give errors indicating that these addresses cannot be bound.
Now, I suppose I am misunderstanding how networks and IP addresses work. How can I make this work? That is, how can I make my HTTP server accept requests from other hosts in the LAN, and then from anyone on the Internet?

A: For your local network, jump on the host computer and open your terminal.  For windows, type ipconfig or for Unix, type ifconfig.  Identify your computers IP here.  You'll be able to connect from your phone now using this IP.
For anyone to connect, you need to port forward your router to the IP you just found.  How to do this varies on the router model, you might need to Google for your specific router.


text:
Q: Getting warning when using `addres of` operator with array as an initializer to a pointer I am learning C and I am having some troubles to truly understand arrays and pointers in C, after a lot of research (reading the K&R book (still reading it), reading some articles and some answers here on SO) and taking tons of notes along the way, I've decided to make a little test / program to prove my understanding and to clear some doubts, but I'm yet confused by the warning  I am getting using this code:
#include <stdio.h>

int main(int argc, char **argv) {
    char a[3] = {1, 2, 3};
    char *p   = &a;

    printf("%p\n", a);       /* Memory address of the first element of the array */
    printf("%p\n", &a);      /* Memory address of the first element of the array */
    printf("%d\n", *a);      /* 1 */
}

Output compiling with GNU GCC v4.8.3:
warning: initialization from incompatible pointer type
char *p   = &a;
            ^
0x7fffe526d090
0x7fffe526d090
1

Output compiling with VC++:
warning C4047: 'initializing' : 'char *' differs in levels of indirection from 'char (*)[3]'

00000000002EFBE0
00000000002EFBE0
1

Why am I getting this warning if &a and a are supposed to have the same value and compiling without warnings when using just a as an initializer for p?

A: &a is the memory address of the entire array. It has the same value as the address of the first element (since the whole array starts with the first element), but its type is a "pointer to array" and not "pointer to element". Hence the warning.

A: You are trying to initialize a char* with a pointer to a char[3], which means a char(*)[3].
Unsurprisingly, the compiler complains about the mismatch.
What you wanted to do is take advantage of array-decay (an array-name decays in most contexts to a pointer to its first element):
char* p = a;

As an aside, %p is only for void*, though that mismatch, despite being officially Undefined Behavior, is probably harmless.


text:
Q: Why does VS Code not offer methods with autocompletion? I noticed that VS Code doesn't know very many methods and doesn't offer them at autocompletion, for instance:

Did I break something? No one's ever had this problem?

A: Javascript is not a statically typed language, so a IDE or Text editor cannot infer what is the type of your variables. In some cases, it does infer, when you use classes, for instance, but note that it is not a limitation of vscode, it is a limitation of dynamically typed languages, like Javascript.
 I suggest that you take a look at TypeScript, a language that can be transpiled to Javascript and that let you statically type you variables, providing the ability to have this kind of feature.
https://www.typescriptlang.org/


text:
Q: How to use system clipboard in VIM Here is scenario, In VIM, I copy the string(e.g. /home/redhat) from the file, and then use this command :! cd XXX(the path I have copied from the buffer, in this case it should be /home/redhat).
My question is, what command should I use to paste the string?

A: "+y is copy from system clipboard in vim, and "+p is paste from system clipboard, you can map them to normal key bindings.
noremap <C-C> "+y
noremap <C-V> "+p

" Note that mapping <C-V> to paste from system clipboard conflicts with vertical mode I suggest you remap vertical mode to <C-Q>
noremap <C-Q>       <C-V>

for other mappings, you can check mswin.vim
If you do not care about system clipboards, y is copy and p is paste in normal mode.

A: You don't need the system clipboard at all for your use case:
:!cd <C-r>"

In insert mode and in Vim's command-line, <C-r>{register} inserts the content of that register at the cursor. Since you yanked /home/redhat, the content of the unnamed register, " (see :help registers), is /home/redhat and it's inserted right where you typed <C-r>":
:!cd /home/redhat

FWIW, you can also insert the file path under the cursor without yanking and pasting:
:!cd <C-r><C-f>

A: After :, you're in command-line mode. Like in insert mode, you can insert register contents at the cursor position by pressing Ctrl + R, followed by the register name. So, if you simply yanked the /home/redhat, that would be " for the default register; for the system clipboard, use + instead.
In the command-line, you can also press Ctrl + F to switch to the command-line window, in which you can use all Vim commands, like in any other buffer, so you could also paste via the usual p / P from normal mode.
Learn how to look up commands and navigate the built-in :help; it is comprehensive and offers many tips. You won't learn Vim as fast as other editors, but if you commit to continuous learning, it'll prove a very powerful and efficient editor. The help topics for the commands mentioned here are :help c_CTRL-R and :help c_CTRL-F.

A: With :new /path/to/file you go to new file. Then paste the information with P (always out of mode Insert).


text:
Q: how to kill a zombie process? I got a two processes during the network drive failure.
1 D     0  1199     1  0  80   0 - 19101 wait_o pts/21   00:00:01 rsync
1 Z     0  1226  1199  0  80   0 -     0 exit   pts/21   00:00:00 rsync <defunct>

How to kill them?
thanks Arman

A: Send a SIGCHILD signal to the parent process and if that doesn't work kill the parent.
http://en.wikipedia.org/wiki/Zombie_process


text:
Q: SQL - Extract the CITY from the string I have a field which is a ticket journey which always doesn't start with the CITY code and it varies from ticket to ticket.
Good Example:
HAM EK X/DXB EK DUR M/IT EK X/DXB EK HAM M/IT

However, there are some cases where it starts with "I-" or dates like "18JAN" or "18JAN16" or "18JAN2016". Below few examples:
I- HAM EK X/DXB EK DUR M/IT EK X/DXB EK HAM M/IT
18JAN HAM EK X/DXB EK DUR M/IT EK X/DXB EK HAM M/IT
18JAN16 HAM EK X/DXB EK DUR M/IT EK X/DXB EK HAM M/IT
18JAN2016 HAM EK X/DXB EK DUR M/IT EK X/DXB EK HAM M/IT

Hence, I wanted to have some assistance to only retrieve the 1st CITY from the string which in the above cases is "HAM"

A: Try this:
Declare @tblTest AS Table
(
   Ticket VARCHAR(100)
)

INSERT INTO @tblTest VALUES ('I- HAM EK X/DXB EK DUR M/IT EK X/DXB EK HAM M/IT')
INSERT INTO @tblTest VALUES ('18JAN HAM EK X/DXB EK DUR M/IT EK X/DXB EK HAM M/IT')
INSERT INTO @tblTest VALUES ('18JAN16 HAM EK X/DXB EK DUR M/IT EK X/DXB EK HAM M/IT')
INSERT INTO @tblTest VALUES ('18JAN2016 HAM EK X/DXB EK DUR M/IT EK X/DXB EK HAM M/IT')

SELECT
    SUBSTRING
    (
        REPLACE
        (
            Ticket,
            SUBSTRING(Ticket,1,CHARINDEX(' ',Ticket)),
            ''
        ),
        0,
        CHARINDEX
        (
            ' ',
            REPLACE
            (
                Ticket,
                SUBSTRING(Ticket,1,CHARINDEX(' ',Ticket)),
                ''
            )
        )
    )
FROM @tblTest

A: For Sql Server, Use the below script.
DECLARE @data VARCHAR(150)='18JAN HAM EK X/DXB EK DUR M/IT EK X/DXB EK HAM M/IT'

SELECT CASE WHEN @data LIKE 'I_%' THEN SUBSTRING(@data,CHARINDEX(' ', @data),CHARINDEX(' ', @data,CHARINDEX(' ',@data) + 1) + 1-CHARINDEX(' ', @data))
            WHEN @data LIKE '[0-9]%' THEN SUBSTRING(@data,CHARINDEX(' ', @data),CHARINDEX(' ', @data,CHARINDEX(' ',@data) + 1) + 1-CHARINDEX(' ', @data))
            ELSE SUBSTRING(@data,1,CHARINDEX(' ', @data)) END

A: You could use SUBSTRING, if you know where you are selecting from which would work if you always new the length of the prefix, however there is little point of this as if you are searching 'cities' then you will be driving this from somewhere (either a cities table or hard codes values). SO I imagine you will search for something like
WHERE field = "%HAM%" or WHERE field IN ('list','of','cities')

and then use this to inform the query outputs.
My advice is, don't think about selecting from the string that you are searching from but instead use the inputs that searching with to inform the output. I hope this makes sense. If you have queries to look at I will try and make some suggestions.


text:
Q: proxy settings ignored by apt-get manager in Ubuntu 13.04 I am using Ubuntu 13.04 in company network, http proxy works fine with my user account but still I cannot install or update anything with apt-get :
Proxy Authentication Required ( Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.  )
I have system-wide proxy in System configuration > Network > Network Proxy > manual configured properly and : env | grep proxy shows both http_proxy, https_proxy variables with proper settings.
but still apt-get still fails to connect.
What to try next ?

A: Edit "/etc/apt/apt.conf" and add below entry:
Acquire::http::Proxy "http://username:password@proxyhost:port/";

Reference Link

A: That probably is an issue to do with the ISA proxy setup in your organization. I had the same issue when configuring a virtual server for my organization.
Open the terminal. In the terminal type in the following command:
sudo nano /etc/apt/apt.conf

This command is meant to open up the apt.conf file and make it available for configuration. If you are prompted for your password, enter it.
Add the following lines into the file:
Acquire::http::proxy "http://[username]:[password]@[proxy_address]:[port]";
Acquire::https::proxy "https:// [username]:[password]@[proxy_address]:[port]";
Acquire::ftp::proxy "ftp:// [username]:[password]@[proxy_address]:[port]";
Acquire::socks::proxy "[username]:[password]@[proxy_address]:[port]";

Where: username - Your proxy username password - Your proxy password proxy_address - The address of the proxy server port - The port on the address server through which traffic is allowed
Save the apt.conf file. Try and run the apt-get command and it should give you something similar to this
sudo apt-get install [package]
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
………
Do you want to continue? [Y/n] y:

If you see this response, that means that the package is ready to install.


text:
Q: What is "sepdflatexmk"? A colleague gave me a .tex file and said it needed to be compiled with sepdflatexmk, which she had on her Mac. She didn't know anything more about this compiler. I did some Googling and it seems specific to TeXShop on Macs, relating to makefiles (about which I know essentially nothing). My questions:

*

*What exactly is sepdflatexmk?

*I have a Windows machine running TeXLive- is there something comparable to this compiler for Windows pc's? I looked in the bin folder and didn't see anything promising.

A: Let me expand on that answer. TeXShop ships with several engines based on the use of the latexmk pearl program. The pdflatexmk engine uses pdflatex as the typesetting engine without enabling shell-escape. The sepdflatexmk engine adds the shell-escape flag to pdflatex.

A: From http://macosx-tex.576846.n2.nabble.com/eps-to-pdf-conversion-td7580188.html

I would create an engine, sepdflatexmk, that is essentially identical
  to the pdflatexmk engine but includes the --shell-escape flag. That
  way you can use pdflatex with the --shell-escape flag set when you
  need it and other engines if you don't need it. I.e., only use the
  flag with ``trusted'' documents.
Good Luck,
Herb Schulz

A: Recent versions of TeXShop contain updated latexmk engines that allow you to set up shell-escape using TeXShop's parameter' directive. See the documentation and installation instructions in~/Library/TeXShop/Engines/Inactive/Latexmk. Note: you can open~/Library/TeXShopusing theTeXShop->Open ~/Library/TeXShop` Menu Item and go from there.


text:
Q: Return value of Gorm complex query Let's say I have:
type A struct {
  ID   string `gorm:"primary_key"`
  Name string
}

type B struct {
  ID   string `gorm:"primary_key"`
  AId  string
  A    A `gorm:"foreignkey:AId"`
  Val  string
}

If I wanted to do a normal query on A or B, I can just expect the A or B struct back. But if I wanted to do a join, what struct should I expect in go?
For example if my query were:
select * from a join b on a.id = b.a_id;

What does GORM return as a struct?

A: Converting the query
select * from a join b on a.id = b.a_id;

into gorm:
db.Tables("a").Select("a.id as aid, a.name as aname, b.id as bid, b.a_id as baid, b.val as bval").Joins("JOIN b ON a.id = b.a_id").Find(&result)

We can just create a temporary result struct that houses all fields from both tables a and b.
result := []struct {
    ID   string `db:"aid"`
    Name string `db:"aname"`
    BId  string `db:"bid"`
    AId  string `db:"baid"`
    Val  string `db:"bval"`
}{}

Then, repackage this result struct as needed, or return this struct for the client to use.


text:
Q: iOS Photo No Longer Optimising Storage I have always kept Optimise iPhone Storage under iCloud for Photos on. Since last week however, it has stopped optimising and saving space locally on my phone.
One possible cause is the use of Google Photo's backup and sync function. I turned that on in Google Photos again after a long time last week in order to share an album with Android users. Google search suggests that Google photos would download the full res photos from iCloud in order to upload them. My iPhone's free space did plummet from more than 10GB free to now less than half a GB free.
Yesterday, I turned off backup and sync in Google Photo and later uninstalled the app. But Photo is still taking up 34GB of my local iPhone storage. Now I have 80/200GB free on iCloud, less than 500mb free on my phone, Photo app is telling me it has stopped updating because I am low on storage.
I have kept my phone plugged in all night and on a fast wifi. The Photos storage remained at 34GB after 12 hours unfortunately.
How do I make the Photo & iCloud optimisation runs again to free up my phone storage?
PS: My iCloud photo library is up to date. Yet in my iPad, my photo library is taking up less than 3GB of space. So somehow it has to be the full size download in my iPhone that is taking up a whooping 30GB of space.

A: This happens on occasion. For some reason Photos stops removing full-resolution versions of photos. If your iCloud Photo Library is up to date, go into Settings / Photos & Camera and disable iCloud Photo Library.
This process may take a long time, and will leave all your full-resolution downloads on your device.
You can open the Photos app to see the number of photos decrease. Don't do anything until it's stabilized. Once it has, wait a few more minutes just to be sure, then delete all remaining photos. Remove them from Recently Deleted as well.
You can now reboot and turn iCloud Photo Library back on with Optimize Storage enabled.


text:
Q: How to get product image by product Id in magento2 I am not able to get the absolute path of the image by product id in Magento 2. Can anybody help me?
I am able to get media path so far by directoryList class by doing this:
$this->directory->getPath('media');

How to get product image full path?
Please note that I don't want an image URL, I want the image path directory.

A: You can Product image path from Magento\Catalog\Api\ProductAttributeMediaGalleryManagementInterface
If you have sku then from this interface's getList() you get media image.
from media image you get image path.
<?php
/**
 * User: amit-pc
 * Date: 1/1/19
 */

namespace Devbera\Test;

class Test
{

    /**
     * @var \Magento\Catalog\Api\ProductAttributeMediaGalleryManagementInterface
     */
    private $productAttributeMediaGalleryManagement;

    public function __construct(
        \Magento\Catalog\Api\ProductAttributeMediaGalleryManagementInterface $productAttributeMediaGalleryManagement
    )
    {

        $this->productAttributeMediaGalleryManagement = $productAttributeMediaGalleryManagement;
    }
    public function getMediaPath()
    {
        $media = $this->productAttributeMediaGalleryManagement->getList($sku = 'ab2');
        foreach ($media as $image)
        {
            print_r(['value_id' => $image->getId(),
            'file' => $image->getFile(),
            'label' => $image->getLabel(),
            'position' => $image->getPosition(),
            'disabled' => $image->isDisabled(),
            'types' => $image->getTypes(),
            'media_type' => $image->getMediaType()
                ]);
            echo $image->getFile();
        }
    }
}

A: try the below code
     $itemsid = 2;
     $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $product = $objectManager->create('Magento\Catalog\Model\Product')->load($itemsid);
        echo $imageUrl = $this->helper('Magento\Catalog\Helper\Image')
                                                    ->init($product, 'product_base_image')
                                                    ->constrainOnly(TRUE)
                                                    ->keepAspectRatio(TRUE)
                                                    ->keepTransparency(TRUE)
                                                    ->keepFrame(FALSE)
                                                    ->resize(150, 150)->getUrl();


text:
Q: What does "show up or cancel" mean in this sentence?
A credit card number will be needed to hold the reservation, but will
  not be charged unless you do not show up or cancel in advance of the
  tour.
  (https://gocity.com/san-antonio/en-us/attractions/texas-hill-country-lbj-ranch-tour)

The bold part is confusing. Does it mean:

There are two instances where the card will be charged, which are:

*

*when you do not show up on the day of the tour

*when you do not cancel in advance of the tour

A:
A credit card number will be needed to hold the reservation, but will not be charged unless you do not show up or cancel in advance of the tour.

This makes perfect sense to me.
"..unless you do not show up or cancel in advance" is a case statement which becomes true if:

*

*you do not show up, or

*you do not cancel in advance.

The meaning of the entire statement is:

*

*You must provide credit card details to make a reservation, but you will not be charged at that point. You will presumably be charged later when you meet that reservation.

*The credit card will be charged if you either a) do not show up (so you simply do not arrive for the tour and never contacted them to tell them you would not be there), or b) fail to cancel in advance (for example, if you contacted them on the day of the tour to cancel that is not advance notice).
Presumably, if you did attend as intended you may be able to offer an alternative means of payment (ie a different card) which is why they can rightly say your card used for the reservation will only be charged in the circumstances above. Of course, you could use the same card for final payment.

A: Actually, it is the opposite. The card will be charged:

*

*if you show up, because you have to pay the fee anyway;

*if you cancel - you will probably pay a cancellation fee.

Now there is a question left: what will happen if you do not show up, but you do not explicitly cancel wither? Maybe this will count as a cancellation too, but the sentence does not clarify.

As @Jan stated in another answer, the triple negation is a total mess and should normally be avoided at all costs. If the situation is real, you are better off sending an email ans asking for a clarification of the statement.

A: This is really confusing because it's kind of triple negative 1) not be charged, 2) unless, 3) do not show up.
The two negatives (will not be charged + unless) make a positive: will be charged. So, your interpretation seems to be right: The card will be charged if you do not show up or if you do not cancel in advance.
If we take that their sentence is correct, it means you will be charged up despite not showing up. Like they say, it's not our business if you show up or not; we will charge you in any case, because you signed in and you didn't cancel. I think, this is realistically possible, because they usually charge you (or not) in the office, not at the place where you show up.


text:
Q: iOS Dev - how to deploy different builds of the same app onto the same device? I would like to install different build of the same app onto the same device so I can keep the older builds around to verify bug fixes.  I don't want to modify the bundle id or code sign it with a different provisioning profile each time if I can avoid it.  What's the quickest way to achieve this?

A: Best to modify the Bundle ID but then best to create different targets for a beta so you can just bash out the extra build.
See this for a good guide on it..
http://www.benzado.com/blog/iphonedev-good-practices

A: I am not sure but the best possible way is to change the identifier.
You can easily try com.yourCompanyName.appName and change appName...