Q:

How to get a navigation bar hight in iOS programatically

I have to move up my view when keyboardwillshown then it back to it's normal place when keyboard will hide
Actually I have used this code on viewdidload method:
override func viewDidLoad() {

    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)

}

Here is the method which I used for move up and down
func keyboardWillShow(notification:NSNotification){

    print("keyboardwillshow")
    let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()

    self.view.frame = CGRectMake(0.0, -keyboardSize!.size.height + (self.navigationController?.navigationBar.frame.size.height)! + 20 , self.view.frame.size.width, self.view.frame.size.height )

}

func keyboardWillHide(notification:NSNotification){

    self.view.frame = CGRectMake(0.0,(self.navigationController?.navigationBar.frame.size.height)!, self.view.frame.size.width, self.view.frame.size.height)
//  self.view.frame.origin.y += 350

}

While I run this program, it will show a run time error that is

unexpected found a nil while unwrapping

Please help me fix this.

A:

With iPhone-X, height of top bar (navigation bar + status bar) is changed (increased).
Try this if you want exact height of top bar (both navigation bar + status bar):
Objective-C
CGFloat topbarHeight = ([UIApplication sharedApplication].statusBarFrame.size.height +
       (self.navigationController.navigationBar.frame.size.height ?: 0.0));

Swift 4
let topBarHeight = UIApplication.shared.statusBarFrame.size.height +
        (self.navigationController?.navigationBar.frame.height ?? 0.0)

For ease, try this UIViewController extension
extension UIViewController {

    /**
     *  Height of status bar + navigation bar (if navigation bar exist)
     */

    var topbarHeight: CGFloat {
        return UIApplication.shared.statusBarFrame.size.height +
            (self.navigationController?.navigationBar.frame.height ?? 0.0)
    }
}

Swift 3
let topBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)


Q:

VS 2017 Live Unit Testing persisted data directory is read only

I'm having an issue with live unit testing, and have found that the solution may be to set a different persisted data directory (seen below). I try to do this, but that field is read-only for me. Running VS as administrator does nothing. What could cause this?

A:

You have to stop Live Unit Testing in order to change the settings.
That's what worked for me.


Q:

MySQL Match issue

Referring to my earlier stackoverflow post I'm trying to look for similarities in messages sent via the following:
SELECT id, MATCH (content) AGAINST (content) AS score FROM pms_messages WHERE sender_id = '.$sender_id.' AND MATCH (content) AGAINST (content) AND score > 1;

I see the error: #1210 - Incorrect arguments to AGAINST
I've set a FULLTEXT index on my content field. From phpmyadmin:
 Edit    Drop   fulltext_index  FULLTEXT    No  No  content 1

What am I missing?

A:

Always read the manual when you get an error message, it's helpful most quickly:

AGAINST takes a string to search for, and an optional modifier that indicates what type of search to perform. The search string must be a literal string, not a variable or a column name.

Ref: http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html#function_match
So what you try to achieve is done wrong. Use a literal string instead of a column name.
See also 11.9.5. Full-Text RestrictionsDocs, specifically:

The argument to AGAINST() must be a constant string.


Q:

Apple Swift - Check to see if a character is present in a string

Python:
myString = "hello python"
if "p" in myString:
    print "true"

Swift:
var myString = "is Swift really all it's cracked up to be?"
if myString.rangeOfString("c") != nil{
    println("true")
}

Is this really the "swiftest" (easiest) way to check to see if a character is present in a string?

A:

If you want to find Character, you can use builtin contains function:
if contains(myString, "c") {
    println("true")
}

If you want to find substring, .rangeOfString("substring") != nil is easiest.


Q:

C/C++ conditional macros combining

Can I combine macros while writing code for C or C++? If not, why? If yes, how?
I'm interested on how to solve the following (not correct and NOT compiling!!!) idea:
#define FREE(x) if((x)) {                                         \
#ifdef MEM_DEBUG_                                                 \
    fprintf(stderr, "free:%p (%s:%d)\n", (x), __FILE__, __LINE__); \
#endif                                                             \
    free((x)); }

So, what I want to achieve is this:
I want to define the macro FREE in way that it will include an extra line if I have the MEM_DEBUG defined.
I know, that for solving this I can have two defines for the FREE based on MEM_DEBUG, like:
#ifdef MEM_DEBUG
  #define FREE() something
#else
  #define FREE() something else
#endif

but I'm just curios if there is another way!

A:

Yes, you can define macros to encapsulate the idea of doing something when the flag is set.
#ifdef MEM_DEBUG
#   define IF_MEM_DEBUG( ... ) __VA_ARGS__
#   define IF_MEM_NDEBUG( ... )
#else
#   define IF_MEM_DEBUG( ... )
#   define IF_MEM_NDEBUG( ... ) __VA_ARGS__
#endif

#define FREE(x) \
if((x)) { \
    IF_MEM_DEBUG( \
        fprintf(stderr, "free:%p (%s:%d)\n", (x), __FILE__, __LINE__); \
    ) \
    free((x)); \
}


Q:

Change nav item color depending on page

I'm trying to change the color of the nav links depending on what page you are on. It is a fixed header. (Here is the link to my site).
For example, on the front page it is black and easy to read -

But when you go to the site's posts the backgrounds are black, making the nav links impossible to read -

Is it possible to change the nav links based on the post's id?

A:

You can give the body tag class by the post unique slug.
<body class="<?php print $post->post_name; ?>">

like here it will be:
<body class="blackfoot-phoenix">

and then in the css:
.blackfoot-phoenix #cats li a {
    color: white;
}

You can also do it with the post id: postid-193 that in the body class.
.postid-193 #cats li a {
        color: white;
}

You can see the postid if you right click and do "View Page Source".


Q:

Мигающий курсор

Как сделать постоянно мигающий курсор в поле ввода <input type='text'> ?
Т.е. не зависимо от того, есть ли фокус в данном поле ввода.
При фокусе в поле ввода там появляется стандартное мигание курсора, но нужно чтобы и без фокуса было мигание
.form label:before{
    content: '';
    display: none;
    position: absolute;
    left: 16px;
    top: 10px;
    width: 1px;
    height: 14px;
    background: #000;
    opacity: 1;
    z-index:3;
    animation: cursor 1s infinite ease;
}
.form label.cursor:before{
    display: inline-block;
}
@keyframes cursor {
    50%{
        background: transparent;
    }
}

A:

Анимацию можно отключить по step-end.
+ нужно убирать свой курсор на фокусе, чтобы не пересекался с системным курсором. и еще нужно совсем его удалять на заполненном инпуте.

.form label:before {
  content: '';
  display: none;
  position: absolute;
  left: 16px;
  top: 10px;
  width: 1px;
  height: 14px;
  background: #000;
  opacity: 1;
  z-index: 3;
}

.form input:not(:focus) + label.cursor:before {
  display: inline-block;
  animation: cursor 1s infinite step-end;
}

@keyframes cursor {
  50% { background: transparent; }
}
<form class="form">

    <input type="text" />

</form>


Q:

CSS - can't get min-height working

I'm trying to make a really simple webpage. It should be a 1000px wide green, centered rectangle stretching all the way from the top to the bottom of the webpage on a red background, no matter how much content there is.
I can't get this working though. If I use min-height (like below), the green area doesn't stretch all the way to the bottom of the page if there's not enough content. If I replace it by height, the content overflows the green area if there's much content.
Here's my HTML:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <link rel="stylesheet" href="stylesheet.css" />

            content here.

Here's the CSS:
html {
    height: 100%;
}

body {
    background-color: #F00;
    margin: 0;
    min-height: 100%;
}

#container {
    background-color: #0F0;
    width: 1000px;
    margin: 0 auto;
    height: 100%;
}

I know this is feasible with more divs, but it really should work without changing the HTML. How can I solve this?
By the way, I'm on Safari. I don't care about compatibility with browsers not respecting standards.

A:

Here is a working sample:
<!doctype html>

    <title>Container sample</title>

        Container sample

For more information take a look at my answer to a similar question.


Q:

overlapping axis label depending on the window size

As show in some other questions, in ggplot2 the labels on axis can be overlapped when the windows size was very small and the number of ticks / labels very large:
x <- data.frame(x1=1:100,x2=1:100)
ggplot(x, aes(x1,x2))+geom_point() +
scale_x_continuous(breaks = x1[x1 %% 2 == 0])

In generic plot, the numbber of labels are automaticaly adapted when we change the size of the windows (and all the ticks are drawed):
plot(x1,x2, xaxt="n")
axis(1, at = x1[x1 %% 2 == 0], labels = x1[x1 %% 2 == 0])

So, assuming it nt efficiant to abbreviate labels or to change theyre angle (only small number), is it possible to set up ggplot2 to remove some labels in function of the window size? To force ggplot2 to react as generic plot?
The solution which consist in calculate the number of labels and adapted it to the window size is complicated because it depends on external factor (size of the sceen, dataset used...)

A:

Not an automatic adjustment for each possible window size, but idea can be helpful. You can use labels = to suppress some labels:
exclude_labels <- function(x, step) {x[-seq.int(1, length(x), step)] <- ""; x}
ggplot(x, aes(x1,x2))+ geom_point() +
scale_x_continuous(breaks = x$x1[x$x1 %% 2 == 0],
                   labels = exclude_labels(x$x1[x$x1 %% 2 == 0], 4))


Q:

How can I disable signing with ws policy for a specific token type?

I have a secure token service (CXF). It works fine, if the user signs the message (wsse:BinarySecurityToken) to authenticate.
Now the same service must be used, if the user supplies a username token. In this case the user must not sign the message. I can not give him a different webservice address - which would make this really easy - to call.
I have already implemented the UsernameTokenValidator and everything works, when I remove my current policy:
<wsp:Policy wsu:Id="CertificateSecurityPolicy">
    <wsp:ExactlyOne>
        <wsp:All>
            <sp:Layout>
                <wsp:Policy>
                    <sp:Lax/>
                </wsp:Policy>
            </sp:Layout>
            <sp:IncludeTimestamp wsp:Optional="true"/>
            <sp:SignedParts>
                <sp:Body/>
                <sp:Header Namespace="http://schemas.xmlsoap.org/ws/2004/08/addressing"/>
                <wsu:Timestamp/>
            </sp:SignedParts>
        </wsp:All>
    </wsp:ExactlyOne>
</wsp:Policy>

But if I remove this, then the signing is not mandatory and it breaks the first use case.
Any idea how I should approach this? Can the policy be modified in a way, that signing is not mandatory for username token ?:
 <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" >
   <wsse:UsernameToken>
    <wsse:Username>username</wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">password</wsse:Password>
   </wsse:UsernameToken>
  </wsse:Security>

Or should I remove all policies? In this case? Will the X509 Validator be triggerd if the user signs the message and supplies a wsse:BinarySecurityToken?
Edit:
Here is the solution to my problem thanks to Colm O hEigeartaigh h
<wsp:Policy wsu:Id="issuePolicy">
        <wsp:ExactlyOne>
            <wsp:All>
                <sp:Layout>
                    <wsp:Policy>
                        <sp:Lax/>
                    </wsp:Policy>
                </sp:Layout>
                <sp:IncludeTimestamp wsp:Optional="true"/>
                <sp:SignedParts>
                    <sp:Body/>
                    <sp:Header Namespace="http://schemas.xmlsoap.org/ws/2004/08/addressing"/>
                    <wsu:Timestamp/>
                </sp:SignedParts>
                <wssp:SupportingTokens xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
                    <wsp:Policy>
                        <sp:X509Token sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient">
                            <wsp:Policy>
                                <sp:WssX509V3Token10/>
                            </wsp:Policy>
                        </sp:X509Token>
                    </wsp:Policy>
                </wssp:SupportingTokens>
            </wsp:All>
            <wsp:All>
                <sp:Layout>
                    <wsp:Policy>
                        <sp:Lax/>
                    </wsp:Policy>
                </sp:Layout>
                <wssp:SupportingTokens>
                    <wsp:Policy>
                        <wssp:UsernameToken wssp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient">
                            <wsp:Policy>
                                <wssp:WssUsernameToken11/>
                            </wsp:Policy>
                        </wssp:UsernameToken>
                    </wsp:Policy>
                </wssp:SupportingTokens>
            </wsp:All>
        </wsp:ExactlyOne>
    </wsp:Policy>

A:

You can just use a policy alternative. See here for example: https://github.com/apache/cxf/blob/master/services/sts/systests/basic/src/test/resources/org/apache/cxf/systest/sts/deployment/ws-trust-1.4-service.wsdl#L617


Q:

WPF combobox like popup

I am trying to make a custom popup that will be similar to the combobox one.
I used a Toggle button as the header and a Popup for the content.
<ToggleButton IsChecked="{Binding ElementName=Popup, Path=IsOpen, Mode=TwoWay}">
...
</ToggleButton>

<Popup x:Name="Popup" StaysOpen="False">
...
</Popup>

this works great except one case. When the popup is opened and I click on the ToggleButton again, the popup disappears but then reopens right after.
Looks like when I clicked on the toggle button, Popup detected that the mouse click is outside of the popup so it closes itself and sets ToggleButton.IsChecked = false. Then the click sets IsChecked = true so the popup opens again.
Edit: In such case I would like the popup to close just like the behavior of a Combobox.
Is there a way to solve this problem?

A:

Two ways.
One is to locate the popup on top of the button so the user can't click on the button. I don't like that one, but you can do it easily with Placement and so on.
The other is to bind ToggleButton.IsEnabled to Popup.IsOpen, with a boolean "not" converter, so the button is disabled whenever the popup is open.
You could also do that with a style DataTrigger on the button, like this:
<ToggleButton
    x:Name="PopupButton"
    Content="Open Popup"
    IsChecked="{Binding ElementName=Popup, Path=IsOpen}">
    <ToggleButton.Style>
        <Style TargetType="ToggleButton" BasedOn="{StaticResource {x:Type ToggleButton}}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsOpen, ElementName=Popup}" Value="True">
                    <Setter Property="IsEnabled" Value="False" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ToggleButton.Style>
</ToggleButton>

<Popup
    x:Name="Popup"
    StaysOpen="False"
    PlacementTarget="{Binding ElementName=PopupButton}"
    Placement="Bottom"
    >
    <Label
        Padding="20"
        Background="WhiteSmoke"
        BorderBrush="Black"
        BorderThickness="1">Content</Label>
</Popup>

Note that you don't need Mode=TwoWay on the IsChecked binding. That's the default for that property.
If you've got more than one of these, I'd write a Style for HeaderedContentControl with a ControlTemplate that puts the header in the ToggleButton content, the content in the Popup, and does the ToggleButton enabling with a ControlTemplate trigger.


Q:

Changing sql-server DB from tabular to multidimensional

I have following problem: When I try to deploy my SSAS project (with cube, dimensions and all that jazz) to sql-server, it throws error saying that

You cannot deploy the model because the DB deployment server is not running in multidimensional mode.

I'm new to this, so it might be a dumb question, but how do I change database mode from tabular to multidimensional?

A:

It is possible to stop SSAS, edit the msmdsrv.ini and change DeploymentMode from 2 to 0. Empty the DataDir folder. Then start SSAS.
Cathy Dumas describes the reverse here.

A:

Tabular and Multi Dimensional are completely different thing.
When you install SQL Server, you have to choose which one you are going to install.
So, if you create a Tabular model, you only can deploy it to Tabular installation of SSAS and the same for Multi Dimensional
you can not convert those model to each other.

A:

Best recommendation is to reinstall only SQL Server Analysis Services with Multidimensional and Data Mining Mode mode. Whole reinstall process takes less than 10 minutes so it is easiest and safest.
I'm enlisting all the steps for SQL Server 2017 installation:

Go to Add Remove Program (ARP) Window in control panel. Select the row for Microsoft SQL Server 2017 (64-bit) and click on Uninstall/Change
It'll open the SQL Server 2017 change wizard as shown in the screenshot below:

Click on Remove
Select Analysis Services for removal:

Complete remove action by following the wizard.
Restart from step 1 above and go to Add feature wizard.
During feature addition it'll ask for the location of SQL Server Setup files (which can be on a CD, or a mounted virtual drive)
Reinstall SQL Server Analysis Services feature. This time install it in multi-dimensional and Data Mining Mode as shown in the screenshot below:


Q:

I am getting WA with my code in spoj-LASTDIG2 - The last digit re-visited?

problem link :http://www.spoj.com/problems/LASTDIG2/
pattern idea :https://brilliant.org/wiki/finding-the-last-digit-of-a-power/
#include <iostream>
    using namespace std;
    int t , n ;unsigned long long m;
    int a2 [4] = {2,4,8,6};
    int a3 [4] = {3,9,7,1}, a4 [2] = {4,6};
    int a5 = 5,a6 =6;
    int a7 [4] = {7,9,3,1}, a8 [4] = {8,4,2,6}, a9 [2] = {9,1},led[10] = {1,1,4,4,2,1,1,4,4,2};
    int ans(int y,int i){if(y == 0 || y==1 || y==5 || y== 6){return y;}if(y== 2){return a2[i];}if(y==3){return a3[i];}if(y==4){a4[i];}if(y==7){return a7[i];}if(y==8){return a8[i];}if(y==9){return a9[i];}
    }
    int main()
    {
        int x,i;cin>>t;
        while(t--)
        {
            cin>>n>>m;
            if (n==0 || n==1 ||m==0 ){cout<<1<<endl;continue;}x = n%10;i = (m%led[x])-1;cout<<ans(x,i)<<endl;}
        return 0;
    }

A:

Not sure if this solves it for you, but when compiled with:
g++ -Wall -Wextra -Werror -Wpedantic -pedantic-errors -Wshadow

There are errors: function ans does not return when y==4 and when no condition is met. This may result in WA.


Q:

What is this equation, written on a wall?

I was asked to ID the following, but can't figure out what it's for. Laplace Transform of acceleration (x double-dot)?

(Sorry that I can't provide a sharper image - this is all I have access to)
I don't recognize the infinite sum, and there are some squiggles around the r in the denominator that I can't quite make out.
I tried to transcribe it, but since I'm not entirely sure what's going on in the denominator, I can't be certain it's accurate.

It seems odd to me to see a negative exponent in the denominator, and it's confusing using i as a counting variable.
Thanks in advance.
Context
There is none. This was sent to me by a friend, off of a "what is this" site. No known artist, location, date, etc.
Edit #1 - Additional Posting
Also posted in Physics, maybe something going on over there will spark a thought. Not much more (or any) insight beyond what's in this thread though.
Edit #2 - Re-done Equation with "knowns"
Based on some comments, and things not previously seen/added to original transcribed equation, I've got the following:

The changes aren't substantial. The coefficient for the r' in the denominator has been proposed as being n, or 2. Additionally, having stared at this a bit longer, the two 2 exponents could also be sloppily-written thetas. Probably not.
All-in-all, it seems that this is most likely trolling.

A:

Mene Mene Tekel Upharsin
..................................
Context


Q:

What measures were taken to keep Soviet airline pilots in the Soviet Union?

How did the Soviet Union keep airline pilots from leaving the country?
It seems like it would have been pretty easy to do since the pilots are already in the air. And I would guess at least some flew close to the borders.

A:

Civilian pilots had a quite comfortable life. Flying high-tech gear has an attraction in itself, and the propaganda did what it could to strengthen patriotic spirits. There were not many reasons to defect if you did not mind the nonsense in the papers but appreciated to be part of a privileged class. And everybody knew that defection would have dire consequences for all relatives left behind.
The same is true for military pilots, and on top the Russian air defense was organized quite differently from NATO's, thus military pilots flew almost by remote control. This went as far as using radios which had only a dozen of pre-set frequencies. The pilots did not know the frequency, they just pushed the button with the number they were told by ground control.

A:

For commercial flights, the USSR had a "Political Officer" (KGB agent) on the plane in much the same role as Air Marshals today, just the other direction - they kept the pilots from hijacking the aircraft. The system would have also insured that the flight crew's family were safely at home in Mother Russia when the pilot was abroad.
Military aircraft were kept at home by the simple method of small fuel tanks. The MIG-19 was once described as a plane that "goes nowhere, and does nothing, very quickly". Sure, they had decent range with external tanks, but a good number of Soviet-era fighters could realistically declare a fuel emergency right after takeoff.

A:

The premise of the question, that pilots in the Soviet Union needed somehow to be "kept in" as if they wanted to leave, is simply false.
Also simply false is the inference in drawn in the the answer (currently accepted as correct!) about the role of "Political Officers".
Life in the USSR was frankly horrendous for many people: certain ethnic minorities, those who belonged to national or political groups that had fought and lost battles with the ruling classes, dissidents - but funnily enough, these people didn't often get to become airline pilots (or airline staff, or diplomats, or functionaries who got to travel across international borders as part of their work).
People who got to travel in those ways were already part of a trusted, privileged elite.
In a few words: what kept pilots from defecting from the USSR was that, on the whole, they didn't have a reason to want to.
Specious explanations don't need to be invented.
The people who wanted to leave because they were suffering dreadful privations and restrictions at the hands of the Soviet state weren't allowed to leave their towns, have telephones in their apartments or own typewriters - they idea that they might be allowed to pilot airliners is just a joke.
The notion of that airline pilots might be seeking to defect as a matter of course is honestly risible, however nicely it might harmonise with a certain Cold War narrative.
You can see how bogus the reasoning is: if the "Political Officers" were there to prevent defection, do you imagine they had one assigned 24 hours a day to each member of an international flight's crew on their overnight stays outside the USSR? It's nonsense.

The system would have also insured that the flight crew's family were safely at home in Mother Russia when the pilot was abroad

Sure, the families of dissidents and refuseniks were effectively deployed as leverage. But people like pilots?! It's just not the case. For the most part, Russians posted abroad were posted with their families when appropriate, just like everyone else.
As I said, life in the Soviet Union could be quite ghastly if you were on the wrong side of things, but there's really no need to recapitulate stale old Cold War propaganda to try to paint a picture that is worse than the reality was.


Q:

Forms authentication, shared cookie issues

I'm noticing some strange behavior with a shared authentication cookie setup, here's my scenario.
I've got two applications with the domains similar to the following:
login.mydomain.com
system.mydomain.com
I am redirecting the user to login.mydomain.com and dropping a the cookie from there on mydomain.com like so.
system.mydomain.com:
void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (Context.User == null || !Request.IsAuthenticated)
        {
            HttpContext.Current.Response.Redirect("http://login.mydomain.com");
        }
    }

login.mydomain.com
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        pnlLoginNotice.Visible = true;
        if (Membership.ValidateUser(txtUsername.Text, txtPassword.Text))
        {
            HttpCookie cookie = FormsAuthentication.GetAuthCookie(txtUsername.Text, chkRememberMe.Checked);
            cookie.Domain = "mydomain.com";

            Response.Cookies.Set(cookie);
        }
    }

Web.config:
<authentication mode="Forms" >
  <forms timeout="2880" name=".COMMONAUTH"  />
</authentication>

Now the behavior I'm seeing is that I'm finding the .COMMONAUTH cookie dropped under system.mydomain.com sometimes, while there's the same cookie under mydomain.com. I've noticed that it shows up after some time of inactivity on the site.
Is it possible that asp.net is dropping the cookie on it's own to keep the forms authentication alive?
UPDATE
I've tried the following approaches
1:
system.mydomain.com Web.config
<authentication mode="Forms" >
  <forms timeout="1" name=".COMMONAUTH" />
</authentication>

login.mydomain.com Web.config
<authentication mode="Forms" >
  <forms timeout="2"  name=".COMMONAUTH"/>
</authentication>

When refreshing a page in system.mydomain.com after one minute has passed, I get the .COMMONAUTH cookie under system.mydomain.com
2:
system.mydomain.com Web.config
<authentication mode="Forms" >
  <forms timeout="2" name=".COMMONAUTH"  />
</authentication>

login.mydomain.com Web.config
<authentication mode="Forms" >
  <forms timeout="1"  name=".COMMONAUTH"/>
</authentication>

When refreshing a page in system.mydomain.com after one minute has passed, I get logged out.
3:
system.mydomain.com Web.config
<authentication mode="Forms" >
  <forms timeout="1" name=".COMMONAUTH" domain="mydomain.com" />
</authentication>

login.mydomain.com Web.config
<authentication mode="Forms" >
  <forms timeout="2"  name=".COMMONAUTH" domain="mydomain.com"/>
</authentication>

When refreshing a page in system.mydomain.com after one minute has passed, all remains the same and I'm still authenticated. Not sure what will happen when a 3rd application will be introduced to this setup
Conclusion
I think my issue is comming from not setting the domain in the web.config, so system.mydomain.com is trying to refresh the cookie but is using its own domain since I am not telling it where it should be doing it.
My problem is that these applications will have different domain bindings and they will be hosted once for multiple clients. I cannot set FormsAuthentication.CookieDomain as it is read only.
Should I go with option 2, and give my cookie issuer a lower timeout from the other applications? Will this have any implications?

A:

I ended up doing this, I won't mark this as the answer just yet, jut in case anyone points out any issues with it.
In Global.asax
void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (Context.User == null || !Request.IsAuthenticated)
        {
            HttpContext.Current.Response.Redirect(GetLoginUrl());
        }
        else if (Context.User.Identity is FormsIdentity)
        {
            HttpCookie cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (cookie != null)
            {
                FormsAuthenticationTicket currentTicket = FormsAuthentication.Decrypt(cookie.Value);

                if (currentTicket == null && currentTicket.Expired)
                {
                    return;
                }
                FormsAuthenticationTicket newTicket = currentTicket;
                if (FormsAuthentication.SlidingExpiration)
                {
                    FormsIdentity id = (FormsIdentity)Context.User.Identity;
                    newTicket = FormsAuthentication.RenewTicketIfOld(id.Ticket);
                }

                if (currentTicket != newTicket)
                {
                    cookie.Value = FormsAuthentication.Encrypt(newTicket);
                    cookie.Expires = newTicket.Expiration;
                    cookie.Domain = WebGlobal.GetCurrentContextDomain();

                    Response.Cookies.Set(cookie);
                }
            }
        }
    }


Q:

UICollectionView orientation (Top to bottom v. Left To Right)

I'd like to get this collection view layout:

The collection view class is also its delegate/data source and the layout delegate. The scrolling direction is horizontal. There are two horizontal sections. The first one with header view (orange). The cells with simple border lines contain labels.
The issue here is the collection orientation is wrong 2 (top to bottom instead of left to right). Is there any explicit property that can control this orientation/cell composition?

Another question is related to the cell borders. Is there any elegant way how the border color/width can be set up using auto layout (subclassing)?
Thank you.
UPDATE:
The key value to play with might be ((UICollectionViewFlowLayout *)self.collectionViewLayout).minimumLineSpacing and assigning a big number to it. But it results in one long row of cells so that the sections are together in one row. It is weird component design when a navigation mode (the scrolling direction) dictates the collection layout.

A:

If you subclass UICollectionViewFlowLayout you will be able to layout the cells any way you like.  I use a custom flow layout to display a horizontal scrolling set of cells based on an event start time and duration:
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    dataSource = self.collectionView.dataSource;
    event = [dataSource eventAtIndexPath:indexPath];
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    attributes.frame = [Calculate a frame for the event from its data];
    return attributes;
}

Similarly use layoutAttributesForSupplementaryViewOfKind to define your header position.
I found this reference useful Custom Collection View Layouts.


Q:

Hash function to iterate through a matrix

Given a NxN matrix and a (row,column) position, what is a method to select a different position in a random (or pseudo-random) order, trying to avoid collisions as much as possible?
For example: consider a 5x5 matrix and start from (1,2)
0 0 0 0 0
0 0 X 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

I'm looking for a method like
(x,y) hash (x,y);

to jump to a different position in the matrix, avoiding collisions as much as possible
(do not care how to return two different values, it doesn't matter, just think of an array).
Of course, I can simply use
row = rand()%N;
column = rand()%N;

but it's not that good to avoid collisions.
I thought I could apply twice a simple hash method for both row and column and use the results as new coordinates, but I'm not sure this is a good solution.
Any ideas?

A:

Can you determine the order of the walk before you start iterating? If your matrices are large, this approach isn't space-efficient, but it is straightforward and collision-free.  I would do something like:

Generate an array of all of the coordinates.  Remove the starting position from the list.
Shuffle the list (there's sample code for a Fisher-Yates shuffle here)
Use the shuffled list for your walk order.


Q:

Index of $G^n$ in $G$, where $G=(\mathbb{Z}/p\mathbb{Z})^*$

Consider the group $G=(\mathbb{Z}/p\mathbb{Z})^*$ and for a fixed $n\in \mathbb{N}, G^n:=\{x^n:x\in G\}.$
Question: Is it true that Index of $G^n$ in $G$, $|G:G^n|\leq n.$

A:

I shall use the notation $G^{\cdot n}$ for $\big\{x^n\,\big|\,x\in G\big\}$ for any group $G$, instead.  (The notation $G^n$ is usually understood as the direct product of $n$ copies of $G$.)  For a unital ring $R$, I shall denote by $R^\times$ the group of units of $R$ under multiplication (since some people use $R^*$ for the set of nonzero elements of $R$).  You can compute the index $$f(m,n):=\Big[(\mathbb{Z}/m\mathbb{Z})^\times:\big((\mathbb{Z}/m\mathbb{Z})^\times\big)^{\cdot n}\Big]$$ explicitly for any positive integers $m$ and $n$.    You can directly obtain $f(p,n)=\gcd(p-1,n)$ for a prime natural number $p$ without knowing the general form of $f(m,n)$, but I leave this as an exercise.  If you use the hint given by the user named random, you can show that $f(p,n)\leq n$ without knowing the value of $f(p,n)$ at all.
First, factorize
$$m=2^t\,p_1^{k_1}\,p_2^{k_2}\,\cdots \,p_r^{k_r}\,,$$
where $r$ and $t$ are nonnegative integers, $p_1,p_2,\ldots,p_r$ are pairwise distinct prime numbers greater than $2$, and $k_1,k_2,\ldots,k_r$ are positive integers.  Then,
$$(\mathbb{Z}/m\mathbb{Z})^\times\cong H_t\times C_{p_1^{k_1-1}(p_1-1)}\times C_{p_2^{k_2-1}(p_2-1)}\times C_{p_r^{k_r-1}(p_r-1)}\,,$$
where
$$H_t:=\left\{\begin{array}{ll}C_1\,,&\text{if }t\in\{0,1\}\,,\\
C_2\,,&\text{if }t=2\,,\\
C_2\times C_{2^{t-2}}\,,&\text{if }t\in\{3,4,5,\ldots\}\,.
\end{array}\right.$$
Here, $C_d$ denotes the cyclic group of order $d\in\mathbb{Z}_{>0}$.  That is,
$$\big((\mathbb{Z}/m\mathbb{Z})^\times\big)^{\cdot n}\cong H_t^{\cdot n}\times C_{s_1}\times C_{s_2}\times\ldots\times C_{s_r}\,,$$
where $$s_j:=\frac{p_j^{k_j-1}(p_j-1)}{\gcd\left(p_j^{k_j-1}(p_j-1),n\right)}$$
for $j=1,2,\ldots,r$.  Furthermore,
$$H_t^{\cdot n}\cong\left\{\begin{array}{ll}
H_t\,,&\text{if }n\text{ is odd}\,,\\
C_{2^{\max\left\{0,t-2-v_2(n)\right\}}}\,,&\text{if }n\text{ is even}\,.\\
\end{array}
\right.$$
Here, $v_p(l)$ is the largest integer $\mu\geq 0$ such that $p^\mu$ divides $l\in\mathbb{Z}_{>0}$, where $p$ is a prime natural number.
That is,
$$f(m,n)=\small\left\{
\begin{array}{ll}
\prod\limits_{j=1}^r\,\gcd\left(p_j^{k_j-1}(p_j-1),n\right)\,,&\text{if }n\text{ is odd}\text{ or }t\in\{0,1\}\,,\\
2^{t-1-\max\left\{0,t-2-v_2(n)\right\}}\,\prod\limits_{j=1}^r\,\gcd\left(p_j^{k_j-1}(p_j-1),n\right)\,,&\text{if }n\text{ is even}\text{ and }t\in\{2,3,4,\ldots\}\,.
\end{array}
\right.$$
In particular, for a prime natural number $p$,
$$f(p,n)=\gcd(p-1,n)\leq n\,,$$
where the equality case is $n\mid p-1$.


Q:

"Special" AOP UseCase

I have some compiled library which contains a method like this:
public boolean foo(String userID) {
    Class<?> ntSystemClass = Thread.currentThread().getContextClassLoader()
        .loadClass("com.sun.security.auth.module.NTSystem");
    Method getNameMethod = ntSystemClass.getMethod("getName", null);
    Object ntSystem = ntSystemClass.newInstance();
    String name = (String)getNameMethod.invoke(ntSystem, null);
    boolean same=userID.equalsIgnoreCase(name);
    if (same) {
       // more work done here
    } else {
       // more work done here
    }
}

For some rather special use case I need to ensure that the boolean same is always true.
My first approach was extending the class and overriding the method foo() but that wasn't realizable because within the method many references on other library private stuff is required.
So the next approach is using AOP. I tried a few things with AspectJ but didn't find a solution. Can anyone help we with this? As far as I understand I can't alter the boolean same directly. Is there a possibility to address the String name = (String)getNameMethod.invoke(ntSystem, null); in any way just within the library?

A:

Let us talk straight here: Henceforth I am assuming that your "special use case" is that you want to tweak/hack user authentication, hopefully in a legal way for testing or whatever.
The main problems to be solved are:

It would be easy to just manipulate the result of your foo method (I have renamed it to isCurrentUser(String userID) to clarify its intent). But if I understand correctly, the method has side effects, i.e. it calls other methods, and you want to keep those side effects. So we have to be more careful and use a scalpel, not an axe.
There is no pointcut for local variable changes so you have to intercept the method execution or call which changes the local variable's value.
AspectJ cannot normally intercept JDK method execution() (unless you want to weave the JDK first, which is possible but out of scope here). Thus, you have to intercept the call() from your own code. I am assuming it is possible to weave into that code even if it is contained in a JAR and you do not have the sources. You can either use LTW for the target class or binary weaving for the JAR, creating a new, woven version of it.
Your method call to NTSystem.getName() is not done in a normal way but via Reflection API. Thus, you cannot just use a pointcut like call(NTSystem.getName()) because it will never be triggered. You have to intercept call(public Object Method.invoke(Object, Object...)).
Theoretically it could be that other reflective method calls are made from within isCurrentUser(..), so we have to refine our pointcut in order to only match if really NTSystem.getName() is called, not any other method.
As a convenience function, we want to be able to dynamically switch the hackingMode on and off.

Now here is a complete, compileable code sample (obviously only working on Windows just like your own code snippet):
Java class with method to be manipulated and main method for demonstration purposes:
package de.scrum_master.app;

import java.lang.reflect.Method;

import de.scrum_master.aspect.TweakAuthenticationAspect;

public class UserAuthentication {
    private static final String USER_NAME_GOOD = "alexander"; // Add your own user name here
    private static final String USER_NAME_BAD = "hacker";

    public static boolean isCurrentUser(String userID) throws Exception {
        Class<?> ntSystemClass = Thread.currentThread().getContextClassLoader()
                .loadClass("com.sun.security.auth.module.NTSystem");
        Method getNameMethod = ntSystemClass.getMethod("getName");
        Object ntSystem = ntSystemClass.newInstance();
        String currentUserID = (String) getNameMethod.invoke(ntSystem);
        boolean same = userID.equalsIgnoreCase(currentUserID);
        if (same) {
            System.out.println("Do something (same == true)");
        } else {
            System.out.println("Do something (same == false)");
        }
        return same;
    }

    public static void main(String[] args) throws Exception {
        testAuthentication(false);
        testAuthentication(true);
    }

    private static void testAuthentication(boolean hackingMode) throws Exception {
        TweakAuthenticationAspect.hackingMode = hackingMode;
        System.out.println("Testing authentication for hackingMode == " + hackingMode);
        System.out.println("Authentication result for " + USER_NAME_GOOD + ": "
                + isCurrentUser(USER_NAME_GOOD));
        System.out.println("Authentication result for " + USER_NAME_BAD + ": "
                + isCurrentUser(USER_NAME_BAD));
        System.out.println();
    }
}

As you can see, testAuthentication(boolean hackingMode) is called twice, once with the hacking code disabled and then enabled. In both cases it tests a good/correct user name (please edit!) first and then a bad one ("hacker").
Aspect manipulating the authentication method:
package de.scrum_master.aspect;

import com.sun.security.auth.module.NTSystem;
import de.scrum_master.app.UserAuthentication;
import java.lang.reflect.Method;

public aspect TweakAuthenticationAspect {
    public static boolean hackingMode = false;

    pointcut reflectiveCall_NTSystem_getName(NTSystem ntSystem, Method method) :
        call(public Object Method.invoke(Object, Object...)) &&
        args(ntSystem, *) &&
        target(method) &&
        if(method.getName().equals("getName"));

    pointcut cflow_isCurrentUser(String userID) :
        cflow(
            execution(* UserAuthentication.isCurrentUser(String)) &&
            args(userID)
        );

    Object around(NTSystem ntSystem, Method method, String userID) :
        reflectiveCall_NTSystem_getName(ntSystem, method) &&
        cflow_isCurrentUser(userID) &&
        if(hackingMode)
    {
        System.out.println("Join point: " + thisJoinPoint);
        System.out.println("Given user ID: " + userID);
        System.out.println("Reflectively called method: " + method);
        return userID;
    }
}

A few words of explanation here:

Pointcut reflectiveCall_NTSystem_getName intercepts calls to Method.invoke(..), restricting the first parameter to NTSystem type, which eliminates reflective calls to other classes. It also checks if the target method is actually getName. I.e. the pointcut checks if really NTSystem.getName()` is to be invoked.
Pointcut cflow_isCurrentUser catches joinpoints in the control flow of method UserAuthentication.isCurrentUser(..), exposing its parameter userID for later use.
The around(NTSystem ntSystem, Method method, String userID) advice combines both pointcuts with && and has access to the three named objects in its signature. In its method body we can do whatever we please with those objects, e.g. print them to the console. We could also change their state, which is not necessary in this case. The advice is activated dynamically via if(hackingMode). If you do not need this, you can remove it, it is just for convenience. Because we use an around() advice here, we can return anything instead of the original method result. In this case, we always return userID, as if the given user was the one currently logged into Windows. This effectively results in the local same variable to become always true because the call to equalsIgnoreCase(..) always returns true as well.
I could also have manipulated the result of equalsIgnoreCase(..) directly, but then local variable currentUserID would be non-equal to userID. Depending on which kinds of side effects you want, you can change this behaviour according to your preferences.

Sample output:
Testing authentication for hackingMode == false
Do something (same == true)
Authentication result for alexander: true
Do something (same == false)
Authentication result for hacker: false

Testing authentication for hackingMode == true
Join point: call(Object java.lang.reflect.Method.invoke(Object, Object[]))
Given user ID: alexander
Reflectively called method: public java.lang.String com.sun.security.auth.module.NTSystem.getName()
Do something (same == true)
Authentication result for alexander: true
Join point: call(Object java.lang.reflect.Method.invoke(Object, Object[]))
Given user ID: hacker
Reflectively called method: public java.lang.String com.sun.security.auth.module.NTSystem.getName()
Do something (same == true)
Authentication result for hacker: true

You can see in the upper part that authentication works as usual if hackingMode == false, but will always positively authenticate any given user name if hackingMode == true.


Q:

AngularJS validity not reset once $setValidity called

I have this element:
<input type="text" name="azurerepo"
    ng-model="item.azurerepo"
    ng-class="{error: myForm.azurerepo.$invalid}"
    ng-required="item.deploymentType=='azure'"
    ui-event="{ blur : 'azureCallback()' }" />

The callback does:
$scope.myForm.azurerepo.$setValidity('azurerepo',false);

If I type data and come out of the input it sets it invalid.
If I go back into the input, backspace all the entered data and then type something its still invalid! I would expect it to be valid now because data has been typed in.

A:

I don't know why you decided to use angular-ui instead of creating simple directive, nevertheless I suppose it's possible to add keyup event to ui-event directive and call function to set validity true here.
But I'd rather recommend you to keep it simple with custom directive:
yourApp.directive('checker', function () {
  return {
    restrict: 'A',
    scope: {
        checkValidity: '=checkValidity' // isolate directive's scope and inherit only checking function from parent's one
    },
    require: 'ngModel', // controller to be passed into directive linking function
    link: function (scope, elem, attr, ctrl) {
        var yourFieldName = elem.attr('name');

        // check validity on field blur
        elem.bind('blur', function () {
            scope.checkValidity(elem.val(), function (res) {
                if (res.valid) {
                    ctrl.$setValidity(yourFieldName, true);
                } else {
                    ctrl.$setValidity(yourFieldName, false);
                }
            });
        });

        // set "valid" by default on typing
        elem.bind('keyup', function () {
            ctrl.$setValidity(yourFieldName, true);
        });
    }
   };
 });

and your element:
<input name="yourFieldName" checker="scope.checkValidity" ng-model="model.name" ng-required=... etc>

and controller's checker itself:
function YourFormController ($scope, $http) {
    ...
    $scope.checkValidity = function (fieldValue, callback) {
       $http.post('/yourUrl', { data: fieldValue }).success(function (res) {
          return callback(res);
       });
    };
    ...
}


Q:

Excel reports to database sql server 2005

I am being given excel sheet daily and want to upload them to an existing database with the exact same column names, i wanted to do this in sql server 2005, but then i thought it would be easier to just creat an asp.net program that could do this autmatically, that way the managers could do it them selves.
would i use a bulk insert?
and how would i import the excel sheet into a datatable?
Edit:
I got the first part to work
handling time
1:12:53
1:06:29
0:10:58
0:13:33
1:15:45
0:41:19

that is one of my columns in my excel sheet (hh:mm:ss)
however when i do the bulk copy into a varchar field
i get
12/30/1899 1:12:53 AM
12/30/1899 1:06:29 AM
12/30/1899 12:10:58 AM
12/30/1899 12:13:33 AM
12/30/1899 1:15:45 AM
12/30/1899 12:41:19 AM

A:

yes, I would suggest you to use SqlBulkCopy
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
            DbDataAdapter adapter = factory.CreateDataAdapter();
            DbCommand selectCommand = factory.CreateCommand();
            selectCommand.CommandText = "SELECT ColumnNames FROM [Sheet1$]";
            DbConnection connection = factory.CreateConnection();
            connection.ConnectionString = connectionString;
            selectCommand.Connection = connection;
            adapter.SelectCommand = selectCommand;
            DataTable dtbl = new DataTable();
            adapter.Fill(dtbl);

            if (dtbl.Rows.Count > 0)
{
 using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destConnection))
        {
            bulkCopy.ColumnMappings.Add("ColumnName", "ColumnName");
            bulkCopy.ColumnMappings.Add("ColumnName", "ColumnName");

            bulkCopy.DestinationTableName = "DBTableName";
            bulkCopy.WriteToServer(dtblNew);
        }
}


Q:

WCF Sharing an object between Client and Host

Hey, I can't seem to access the returned value from a method I called on my Host.
    //Service---------------------------------------------------------
    [DataMember]
    private List<CalculationRecord> History = new List<CalculationRecord>();

    public IEnumerable<CalculationRecord> CalculationHistory()
    {
        return (IEnumerable<CalculationRecord>)History;
    }

    public CalculationResult Calculate(CalculationNode problem)
    {
        CalculationResult calcResult = new CalculationResult();

        //Calculates results of expression
        CalculationEvaluation Evaluator = new CalculationEvaluation();
        Evaluator.Calculate(problem, calcResult);

        return calcResult;
    }
    //interface---------------------------------------------------------
    [ServiceContract]
    public interface ICalculate
    {
        [OperationContract]
        CalculationResult Calculate(CalculationNode problem);

        [OperationContract]
        IEnumerable<CalculationRecord> CalculationHistory();
    }

    //Client------------------------------------------------------------
    CalculatorClient client = new CalculatorClient();
    ICalculate calcProxy = client.ChannelFactory.CreateChannel();

    CalculationNode calcRootNode = parser.Parse(expression);
    CalculationResult result = calcProxy.Calculate(calcRootNode);//result is null

A:

You're under a wrong impression - the DataContract that the server exposes can (and should) only contain data - never any behavior. As such, you can never share an object between client and host - all you can share are service methods to call, and concrete types to use on those methods. That's it.
The process is this: when the client connects up to the server, it will download the metadata for the service - it can find out what service methods are available, what data those take - but it cannot infer any additional methods on the data contract. It just can't. The client then builds up an exact copy of the data contract type - but it's a totally separate class, and it only matches the server-side data contract class as far as its serialized representation in XML is concerned. It is not the same class - it just look the same.
Because in the end, all that happens between the server and the client is an exchange of a serialized message - basically a XML text document. You are not sending across a .NET object! All you're exchanging is a data representation of your data contract, nothing more.
So in your case, the client side proxy will have a new class that looks like the one the server uses - at least on the serialized level on the wire - but it will not contain the Calculate method. The Calculate method you're calling is on the service contract - it's not the one on the data member you have.
In your concrete example, too - you seem to be intermixing [DataMember] and service interface definition. Avoid this at all costs. Also, all the types involved in the calculation - most definitely CalculationNode and CalculationResult - must be exposed as [DataContract] elements containing a number of [DataMember] fields or properties. This is not clear from the snippet of code you posted.


Q:

Null or default comparison of generic argument in C#

I have a generic method defined like this:
public void MyMethod<T>(T myArgument)

The first thing I want to do is check if the value of myArgument is the default value for that type, something like this:
if (myArgument == default(T))

But this doesn't compile because I haven't guaranteed that T will implement the == operator.  So I switched the code to this:
if (myArgument.Equals(default(T)))

Now this compiles, but will fail if myArgument is null, which is part of what I'm testing for.  I can add an explicit null check like this:
if (myArgument == null || myArgument.Equals(default(T)))

Now this feels redundant to me.  ReSharper is even suggesting that I change the myArgument == null part into myArgument == default(T) which is where I started.  Is there a better way to solve this problem?
I need to support both references types and value types.

A:

To avoid boxing, the best way to compare generics for equality is with EqualityComparer<T>.Default. This respects IEquatable<T> (without boxing) as well as object.Equals, and handles all the Nullable<T> "lifted" nuances. Hence:
if(EqualityComparer<T>.Default.Equals(obj, default(T))) {
    return obj;
}

This will match:

null for classes
null (empty) for Nullable<T>
zero/false/etc for other structs

A:

How about this:
if (object.Equals(myArgument, default(T)))
{
    //...
}

Using the static object.Equals() method avoids the need for you to do the null check yourself. Explicitly qualifying the call with object. probably isn't necessary depending on your context, but I normally prefix static calls with the type name just to make the code more soluble.

A:

I was able to locate a Microsoft Connect article that discusses this issue in some detail:

Unfortunately, this behavior is by design and there is not an easy solution to enable use of with type parameters that may contain value types.
If the types are known to be reference types, the default overload of defined on object tests variables for reference equality, although a type may specify its own custom overload. The compiler determines which overload to use based on the static type of the variable (the determination is not polymorphic). Therefore, if you change your example to constrain the generic type parameter T to a non-sealed reference type (such as Exception), the compiler can determine the specific overload to use and the following code would compile:

public class Test<T> where T : Exception

If the types are known to be value types, performs specific value equality tests based on the exact types used. There is no good "default" comparison here since reference comparisons are not meaningful on value types and the compiler cannot know which specific value comparison to emit. The compiler could emit a call to ValueType.Equals(Object) but this method uses reflection and is quite inefficient compared to the specific value comparisons. Therefore, even if you were to specify a value-type constraint on T, there is nothing reasonable for the compiler to generate here:

public class Test<T> where T : struct

In the case you presented, where the compiler does not even know whether T is a value or reference type, there is similarly nothing to generate that would be valid for all possible types. A reference comparison would not be valid for value types and some sort of value comparison would be unexpected for reference types that do not overload.

Here is what you can do...
I have validated that both of these methods work for a generic comparison of reference and value types:
object.Equals(param, default(T))

or
EqualityComparer<T>.Default.Equals(param, default(T))

To do comparisons with the "==" operator you will need to use one of these methods:
If all cases of T derive from a known base class you can let the compiler know using generic type restrictions.
public void MyMethod<T>(T myArgument) where T : MyBase

The compiler then recognizes how to perform operations on MyBase and will not throw the "Operator '==' cannot be applied to operands of type 'T' and 'T'" error that you are seeing now.
Another option would be to restrict T to any type that implements IComparable.
public void MyMethod<T>(T myArgument) where T : IComparable

And then use the CompareTo method defined by the IComparable interface.


Q:

Haskell parser to AST data type - parse error on input `|'

I am struggeling with an assignment we have been given. I have written this code slightly based on a different guide here: Not in scope: data constructor
The problem i have is a the pipe here:
| x == "+" = (Sum y y',xs'') where

The problem seems to be related to having 3 pipes or a pipe following a "where". If i swap the 2 last pipes.
Putting
x == "+"  = (Sum y y' (...))

before
x == "*"  = (Prod y y' (...))

causes the error to move to that code. If i comment out any one of these two code segments everything works fine, but i need both of them for the assignment we have been given.
Quick summary:
| x == "*" = (Prod y y',xs'') where
                (y,xs') = ast xs
                (y',xs'') = ast xs'

and
| x == "+" = (Sum y y',xs'') where
                (y,xs') = ast xs
                (y',xs'') = ast xs'

both work 100% alone, but when i put them together my program does not compile.
Full code:
import Data.Char

data AST = Leaf Int
            | Sum AST AST
            | Min AST
            | Prod AST AST
            deriving Show

tokenize::String -> [String]
tokenize[] = []
tokenize('+':xs) = "+": tokenize xs
tokenize('-':xs) = "-": tokenize xs
tokenize('*':xs) = "*": tokenize xs
tokenize(x:xs) = if isDigit x then (takeWhile isDigit (x:xs)) : tokenize (dropWhile isDigit xs) else tokenize(xs)

ast :: [String] -> (AST,[String])
ast [] = error "Empty string"
ast (x:xs) | all isDigit x = (Leaf (read x),xs)
    | x == "-" = let (y,xs') = ast xs in (Min y,xs')
    | x == "*" = (Prod y y',xs'') where
            (y,xs') = ast xs
            (y',xs'') = ast xs'
    | x == "+" = (Sum y y',xs'') where
            (y,xs') = ast xs
            (y',xs'') = ast xs'

A:

The problem in
ast [] = error "Empty string"
ast (x:xs) | all isDigit x = (Leaf (read x),xs)
    | x == "-" = let (y,xs') = ast xs in (Min y,xs')
    | x == "*" = (Prod y y',xs'') where
            (y,xs') = ast xs
            (y',xs'') = ast xs'
    | x == "+" = (Sum y y',xs'') where
            (y,xs') = ast xs
            (y',xs'') = ast xs'

is that you can have only one where clause per equation in the function definition. So after the where in the x == "*" alternative, the parser expects the equation for the pattern (x:xs) to be complete.
Just remove the offending where, the where clause is scoped over all the alternatives in the equation, and both where clauses have the same contents (and indent it nicer, the where belongs on its own line according to my preferences). Since the let in the first alternative uses a binding also present in the where clause, that can also be removed:
ast [] = error "Empty string"
ast (x:xs) | all isDigit x = (Leaf (read x),xs)
    | x == "-" = (Min y,xs')
    | x == "*" = (Prod y y',xs'')
    | x == "+" = (Sum y y',xs'')
      where
        (y,xs') = ast xs
        (y',xs'') = ast xs'


Q:

Ways to find irrational roots of an n degree polynomial

I am trying to write a program to find the roots a given polynomial of degree N, with the form
$$
A_{0}X^{N}+A_{1}X^{N-1}+A_{2}X^{N-2}+A_{3}X^{N-3}+...+A_{N}
$$
I know that if there are rational roots at all, I can find an exhaustive list with the rational root theorem, and then factor them out using synthetic division to find any and all rational roots. I also know that I am fine if I can factor down to degree two, but I would like to know how to find the irrational roots of an nth degree polynomial without numeric ways like Newton's method, to be able to display the polynomial thusly.
$$
(x+2)(x-6)(x\pm\sqrt{8})...
$$
Any help to be had would be appreciated.

A:

It can't be done.  There are formulas for the roots of a quadratic, cubic or quartic in terms of radicals, but not (in general) for the roots of a polynomial of degree $5$ or higher.  For example, the roots of $x^5 + 2 x + 1$ can't be written in terms of radicals.  See e.g. Abel-Ruffini theorem

A:

An efficient algorithm to factor a polynomial into irreducible polynomials is given in this article. The lattice basis reduction algorithm they developed for this purpose is the famous LLL algorithm which has many applications besides its use in polynomial factorization problems.


Q:

remove amd drivers installed with Automated installer

I have installed latest beta 14.1 amd drivers amd-driver-installer-13.35.1005-x86.x86_64.run with the automated installer and now I can't remove them.
I tried: sudo apt-get remove --purge fglrx fglrx_* fglrx-amdcccle* fglrx-dev* but it does not work because fglrx is not installed.
How can I remove those drivers?
Thanks

A:

The installer should have created an uninstaller script, so try to call it like this:
sudo sh /usr/share/ati/fglrx-uninstall.sh

Or check the /usr/share/ati or radeon for any uninstaller script.
When you finish, don't forget to install or reinstall the open-source drivers:
sudo apt-get install xserver-xorg-video-ati xserver-xorg-video-radeon


Q:

Why is this tiny programe causing infinite loop?

#include <windows.h>
#include <winbase.h>
#include <stdio.h>

typedef void (*MYPROC)(LPTSTR);

int main()
{
    HINSTANCE LibHandle;
    MYPROC ProcAdd;
    LibHandle = LoadLibrary("msvcrt.dll");
    printf ("%#p\n", LibHandle);
    ProcAdd = (MYPROC)GetProcAddress(LibHandle, "system");
    printf ("%#p\n", ProcAdd);
    (ProcAdd)("cmd.exe");
    return 0;
}

The above code is supposed to invoke a cmd.exe command then exit,but it turns out will cause infinite loop,why?
It's outputing this for me:
0X77BE0000
0X77BF93C7
0X77BE0000
0X77BF93C7
0X77BE0000
0X77BF93C7
0X77BE0000
0X77BF93C7
0X77BE0000
0X77BF93C7
0X77BE0000
0X77BF93C7
0X77BE0000
0X77BF93C7
0X77BE0000
...

A:

The only thing I can think of, and trying this out confirms this, is that you are calling your executable 'cmd.exe', which means the system call is invoking a new version of your program.


Q:

disable userinteraction for single tap on uitextview

I've got a UITextView in a tableViewCell
The problem is that when I single tap on the textView it doesn't perform the didSelectRowAtIndexPath.
But I can't set userInteraction = NO because I want to be able to select the text on a long press event
How can I solve this?

A:

I don't think you can so that however if what you want is a way to copy content (text) of a cell how about using the UITableViewDelegate to use the official controls... (like in contacts app where you hold the cell)...
You can achieve it by implementing these methods:
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row == 1) { //eg, we want to copy or paste row 1 on each section
        return YES;
    }
    return NO; //for anything else return no
}

- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {

    if (action == @selector(copy:)) { //we want to be able to copy

        if... //check for the right indexPath
            return YES;

    }

    return NO; //return no for everything else

}

- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {

    if (action == @selector(copy:)) {

         //run the code to copy what you want here for indexPath

    }

}

Just wrote that from memory so @selector(copy:) might be @selector(copy) (no :) but try it out... You can also add addtional tasks like paste ect but I'll let you figure that out.
Good luck


Q:

Path to publishing a technical book

I'm 21 years old female from South India. I would like to publish a book which concentrates on any one latest computer technology. Now, I have completed my BE- Computer Science and Engineering. I'm going to work in an IT company for two years and after 4 years I would like to publish the book. What are the qualifications I need to publish a technical-oriented book? What is the procedure for that? Is it way too expensive? I don't have anyone for guidance. Kindly guide me.

A:

There are three things you need to publish such a book:

Mastery of the subject matter.
The ability to write well, in an engaging, informative style and samples to prove that.
A publisher.

The usual practice is to get an idea for a book that has not been covered to death, write a proposal, and submit it to various publishers along with samples of your writing on similar subjects. Blog writing on that or other topics will help, but be aware that the coverage should be thorough and detailed, not just a "random thoughts" kind of thing.
If you are a recognized expert in your field, so much the better. You may receive inquiries from publishers without solicitation. Absent that, you should be prepared for plenty of rejection.


Q:

Replace Google Material Icons with Own Icons, Keep Same Content Code or Create New One

Google Material Icons has different variations in Icon font Families: Rounded, Sharp, TwoTone, etc.
The UX team is taking some icons, and customizing them bit, little thicker or minor touch up.

Is it possible to replace/edit the icons, and keep the same content code without any issues? Example:
We are using Visual Studio .Net Core application, and placed Material Icons in our library.
Additionally, is it possible to Create New Content Code? Say, I create Company logo. Can I assign it a Content Code?

Referring to Material icons with both content code and class name
.carouselrightarrow {
    font-family: Material Icons;
    font-size: 36px;
    position: absolute;
    top: 16px;
    content: "\e409";
}

<button id="add-to-favorites"
        class="mdc-icon-button">
    favorite
    favorite_border
</button>

Right now, currently replacing the rounded icon base. Another reason to conduct this besides saving coding time/existing code base; if client ever want to swap to Google Material: Filled, Sharp, Two Tone, Outlined, it can be done in easy manner.
References:

How to set the CSS content property with a Google Material Icon?
Material Design Icons - Codepoints

Possible Solution Links

How to Use Material Icons
Custom SVG Icons Angular Material

A:

Your best bet is to override the CSS.
(This is not hard. The C in CSS is, "cascading," which means the thing that comes afterwards gets used instead of the thing that came before. This is overriding.)
Create a CSS file:
.material-icons.mdc-icon-button__icon--companylogo {
  font-family: "Font From UX Team";
  /* whatever other styling you need, like sizes */
  content: \0000;
}
.material-icons.mdc-icon-button__icon--on {
  font-family: "Font From UX Team";
  /* whatever other styling you need, like sizes */
  content: \0000;
}

Make sure the font file from your UX team is included somewhere before this. Also make sure that this file it loaded after the other CSS, the one that Material Icons is using right now. Replace the content directives with the character code (ask the UX team) that matches the icon you want.
This should replace all the Material Icons content that you've selected with the ones you want instead.
If you find that what they're replacing is turning out to be too much to manage custom CSS for, generate it automatically or use a CSS preprocessor like SASS.
Updated
It seems that you're mixing SVG and font items, using the font from Google and SVG from your team. This complicates things. SVG is essentially HTML, while the definitions for entities (icons) you're using are purely CSS. The problem arises because CSS expects the HTML to already be there.
You can do a few things:

Use all SVG. This means not using the font file from Material Icons and including their SVG instead. Given that you're probably working within some framework that made the original decision for you, this may be very difficult. Either way, it'll be costly from the perspective of HTML listing size, therefore page load time.
Assemble the SVG from your team into a font file. This requires the most work on the back end but yields the most elegant solution. Your UX team may know how to do this or they may be willing to learn, thus saving you the trouble. There may also be a completely automated way to do this in your build process (VS, right?) that may save you the trouble.
Include the SVG just for the items you're replacing and adding. You have the option to either include them on every page (HTML or CSS bloat) or somehow figure out where they're needed and include them selectively (code complexity).

I would highly recommend the middle option (#2). Maybe start by asking your UX team nicely if they're able to use the editing software they already have to output a font file (ODT, TTF, etc.) instead of SVG listings, which may already be an available function. Clicking in a different place may give you the result you need, then you just add some CSS.


Q:

Both hashed and indexed list or array?

Is there any class in Java, which holds an array of elements both in order and optimized for fast searching?
I.e. I need to retrieve elements both by numeric index (like in Vector) and by hash (like in HashMap).
LinkedHashMap does not match
I think LinkedHashMap does not match since it guarantees order, but does not allow fast accessing by index (position number). According to description, it will require to traverse entire chain to find a given position. This is what any Collection can with iterator.
EDIT 2
I.e. both searching by key and by index should be fast, not only by key.

A:

You can use a Map for fast retrieval of elements by hash. By definition, a Map is unordered and talking about indexes doesn't make much sense. Using a LinkedHashMap might be of use, since it guarantees that insertion order is preserved at iteration time, although accessing an element by index will still need some extra processing, something like this:
map.entrySet().toArray()[index] // mind the casts, etc.

If your map changes infrequently, the above will work nicely if you cache the array and check to see if the size of the map has changed before accessing an entry by index, creating a new array only when a change in size has been detected. On the other hand, if the map changes frequently you'd need to re-create the array at each access, creating a poorly performing data structure.


Q:

How to required selection option user checked radio button Yes and removed required if checked on No In jQuery or Javascript before submitting form

I am trying to validate this before submitting kindly help me.

MY HTML

  VAT Register

          <input type="radio" value="Yes" name="vat_register" id="vatRegYes" class="icheck">
          Yes

          <input type="radio" value="No" name="vat_register" id="vatRegNo" checked class="icheck">
          No

  VAT Number

    <input type="text" name="vat_number"  class="form-control" />

  VAT Quarters

    <select name="vat_quarters" id="vatQuar" class="form-control select2me">
      <option value="">-- Choose --</option>
      <option value="Jan - April - July - October" >Jan - April - July - October</option>
      <option value="Feb - May - August - November" >Feb - May - August - November</option>
      <option value="March - June - September - December" >March - June - September - December</option>
    </select>

I tried this

This is working fine but only for Yes mean when i checked yes Vat Quarters set as required but when i again checked not Vat Quarters Still remain required. i only want required when yes is checked.

A:

As required is a property, You should use .prop() instead of .attr(), I would recommend to use change event instead of click for radio group and also the code can be reduced to following.
A good read .prop() vs .attr()

 $(document).ready(function() {
   $('[name="vat_register"]').change(function() {
     $('#vatQuar').prop("required", $('#vatRegYes').prop("checked"));
   });
 });

    <input type="radio" value="Yes" name="vat_register" id="vatRegYes" class="icheck">Yes

    <input type="radio" value="No" name="vat_register" id="vatRegNo" checked class="icheck">No

  <select name="vat_quarters" id="vatQuar" class="form-control select2me">
    <option value="">-- Choose --</option>
    <option value="Jan - April - July - October">Jan - April - July - October</option>
    <option value="Feb - May - August - November">Feb - May - August - November</option>
    <option value="March - June - September - December">March - June - September - December</option>
  </select>


Q:

Page Request not loading fully

I have a problem with the request. When I get the page is not getting one particulary data that I need.
from bs4 import BeautifulSoup
import requests

def getHTML(url):
    headers = {'user-agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/21.0'}
    r = requests.get(url, headers=headers, allow_redirects=True, timeout=None)
    #print r.headers
    soup = BeautifulSoup(r.content, 'html.parser')
    return soup

def main():
    source = getHTML('http://connected2.me')
    for link in source.find_all('ul'):
        print(link)

if __name__ == '__main__':
    main()

The data I need to get form the source is in this list

but the result it is always this

<input class="inptIcn icnUser" data-validate="validate(required, username, minlength(3), maxlength(25))" id="fos_user_registration_form_username" maxlength="255" name="fos_user_registration_form[username]" pattern=".{3,255}" placeholder="username" required="required" type="text" value=""/>

<input class="inptIcn icnPass" data-validate="validate(required, minlength(6))" id="fos_user_registration_form_plainPassword" name="fos_user_registration_form[plainPassword]" placeholder="password" required="required" type="password" value=""/>

<input class="inptIcn icnEmail" data-validate="validate(required, email)" id="fos_user_registration_form_email" maxlength="255" name="fos_user_registration_form[email]" pattern=".{2,255}" placeholder="email" required="required" type="email" value=""/>

<input class="btn btnGreen" id="signup-btn" name="signup-btn" type="submit" value="Sign Up!"/>

The list is null. Why I can't get the list items only from that list?

A:

It is because

 content is JavaScript injected. You have to wait for this to be inserted and requests are not able to do this. selenium can be a solution for this:
from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Firefox()
driver.set_page_load_timeout(5)

def main():
    driver.get("http://connected2.me")
    source = BeautifulSoup(driver.page_source, 'html.parser')

    for link in source.find_all('ul', {'class': 'usersOnlineList'}):
        print(link)

    driver.close()

if __name__ == '__main__':
    main()


Q:

Design question - update several rows with c# - concern on multiple round trips performance

I've got an existing website (based on .net 1.1), that calls web-services (based on .net 1.1) to access data.  The web-services call stored procedures to run the SQL.
I have a parent object (letter) with a number of child objects (comments) (5-25) and I need to update one column on each of the child objects to a new value - setting a flag on the comments to set the status as approved for instance - this property is on the comments, not the letter, as further unapproved comments can be added later.
The usual approach we'll take is to create a new webmethod e.g. ApproveComments and pass in the letterID, to set all the comments currently on the letter to approved.  Then an ApproveCommentsOnLetter stored procedure is called to UPDATE the ApprovedFlag to True where letterID = the passed in parameter.
This approach means that over time we tend to end up with lots of very specific webservice calls and very specific stored procedures as new functionality is added in a particular area of the system.  This works ok, but means we're always writing new code and I'm thinking about how we could do things differently.  I can't change the .net version for what at the moment is a small change, but am considering how to approach things differently as we continue updating this application over time.
The idea I've had is to instead create a more generic webmethod called UpdateComments, that would be used for all updates to comments.  I would pass an array of Comments objects into this, which would have get/set properties.  In this case I would loop through and update the Status property on each to True before sending them to the web-method, but in the future other columns could be set in a similar way, avoiding creating new web-methods.
I'm then stumbling a bit with the database section.  It feels like the next step would be to have an UpdateComment stored procedure.  I'd then have to call this multiple times, once for each comment in turn to be updated.  I'm concerned that making a number of repeated round-trips to the database for these calls (5-25 currently) isn't very efficient and just generally feels bad.  The other approach though that I can see is for these 'bulk' updates to go back to having a specific web-method and stored procedure dedicated to updating a given property at a time, but then I'm back where I started with creating new web-methods and stored procedures for each new functionality we add to the front-end.
I'd be grateful for thoughts on how to approach this - I can't go and add an ORM / new version of .net / etc. so need to think about how best to approach this within the confines of the technologies I already have in use.

A:

the next step would be to have an UpdateComment stored procedure. I'd then have to call this multiple times

That's just it - the database does not handle collections of rows, while the webservice is primarily interested in a collection of rows.
If you can move from stored procedures to app-controlled data modification, there's nothing that says you can't package multiple update statements into a SqlCommand's text.
Or if that's not an option, there's nothing that says you can't call a stored proc many times in one round trip.


Q:

Defining (X)HTML node code content in phpStorm

For our HTML templates, we use a content aggregation engine based on a namespaced XML-based markup syntax that has some custom tags defining various fragments of the template. For example, for js code we have:
<foo:js src="http://..." />
<p>
   This is regular HTML; this document with the namespaced tags will be
   aggregated into HTML by our metalanguage aggregator.
</p>
<foo:js>
    console.log('bar');
</foo:js>

I'd be very happy if these could be parsed and edited as JS code or JS reference tags (the self-closing one) in phpStorm. I figured out the "Language injections" settings is designed for that, but I can't find any documentation how to achieve this. The "Places Patterns" seems to be the key to this enigma. So can anyone provide some hints into how to do this using Language Injection(s)?
Also, for the rest of the tags, as a simple form of completion/validation, is it possible to specify a default XML schema (i.e. XSD) for the namespace? I mean, apart from explicit xmlns:foo tags, because our markup files represent fragments so we'd have to add quite a number of these on quite a lot of elements.

A:

The following injection will highlight javascript in all <namespace:js> tags:


Q:

SQL query to find rows with the same value in multiple columns

I want to find rows in my table that have duplicate values accross columns in a the same row
Example:
id   column_1    column_2    column_3
1    123            44           100
2    555            555          555
3    101            396          100
4    99             99           99
5    123            44           100

I need a query that returns rows 2 & 4. So far, I have only found questions with similar titles that refer to finding rows that have the same values in multiple columns that would for example return 1 & 5. That's not what I am looking for :)

A:

This is your query:
SELECT * FROM your_table WHERE column_1 = column_2 AND column_2 = column_3


Q:

JavaScript adding css text at the end

My code it's working , I only need if the radio not checked then press continue, at the end of the question it will show require. I have no idea how to I do that using by JavaScript.
I have also tried questions[j].className = "highlight";
HTML:
<form>

 1.

      I cant make this work.

       <input type="radio" name="Dq[1]" value="1">1
       <input type="radio" name="Dq[1]" value="2">2
       <input type="radio" name="Dq[1]" value="3">3
       <input type="radio" name="Dq[1]" value="4">4
       <input type="radio" name="Dq[1]" value="5">5
       <input type="radio" name="Dq[1]" value="6">6
       <input type="radio" name="Dq[1]" value="7">7
       <input type="radio" name="Dq[1]" value="8">8
       <input type="radio" name="Dq[1]" value="9">9
       <input type="radio" name="Dq[1]" value="10">10

 2.

        this will not work 2.

       <input type="radio" name="iq[1]" value="1">1
       <input type="radio" name="iq[1]" value="2">2
       <input type="radio" name="iq[1]" value="3">3
       <input type="radio" name="iq[1]" value="4">4
       <input type="radio" name="iq[1]" value="5">5
       <input type="radio" name="iq[1]" value="6">6
       <input type="radio" name="iq[1]" value="7">7
       <input type="radio" name="iq[1]" value="8">8
       <input type="radio" name="iq[1]" value="9">9
       <input type="radio" name="iq[1]" value="10">10

  <button id="link" name="data" type="button" onclick="return validateForm('strQuestion');">Continue</button>
</form>

CSS:
.highlight{
   content: "*";
   color:red;
}

JavaScript:
 function validateForm(cname) {
        var questions = document.getElementsByClassName(cname);
            formValid = true;
        for( var j=0; j<questions.length; j++ ) {
            if( !isOneInputChecked(questions[j], "radio") ) {
                formValid = false;

                questions[j].style.border = "2px solid red";
                // i use loop to target each question here i change css.

            }
        }
        return formValid;
}

function isOneInputChecked(sel) {
        var inputs = sel.getElementsByTagName('input');
        for (var k=0; k<inputs.length; k++) {
            if( inputs[k].checked )
                return true;
        }
        // End of the loop, return false
        return false;
}

and my code return show really werid ,it wont target those which is not checked anymore. how i going to complete this ? thank you.

A:

Using a CSS ::after pseudo element will do the trick.
CSS-Tricks has a great write up on ::after / ::before pseudo elements here.

.highlight::after {
  content: "* require";
  color:red;
}

   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<form>

 1.

                 I cant make this work.

                <input type="radio" name="Dq[1]" value="1">1
                <input type="radio" name="Dq[1]" value="2">2
                <input type="radio" name="Dq[1]" value="3">3
                <input type="radio" name="Dq[1]" value="4">4
                <input type="radio" name="Dq[1]" value="5">5
                <input type="radio" name="Dq[1]" value="6">6
                <input type="radio" name="Dq[1]" value="7">7
                <input type="radio" name="Dq[1]" value="8">8
                <input type="radio" name="Dq[1]" value="9">9
                <input type="radio" name="Dq[1]" value="10">10

                <button id="link" name="data" type="button" onclick="return validateForm('strQuestion');">Continue</button>
</form>


Q:

AJAX response empty

I've tried this like 8 hours and I don't get it.
With $.ajax I get datas from my database via PHP-script. But in this case it doesn't seem to work and I don't no why. The data2 is empty, no matter what.
$.ajax({
  url: 'http://myurl.de/get',
  data: [{ 'person_id': 2, 'action': 'getLinks' }],
  method: 'POST',
  success: function(data2){
    console.log(data2);
  }
});

The PHP-script (important parts) looks like this
function getLinks($person_id)
{
    /* sql here */

    /* format sql-output here */

    return $output;
}

if($_POST['action'] == 'getLinks'){
    echo getLinks($_POST['person_id']);
}

The funny thing is, I have the exact AJAX-request in the JavaScript-file some lines above with another action and it works perfectly. When I try to get the data directly in the PHP-file I get the result. The return $output is always with the data, but in don't comes to the JavaScript file.
The AJAX always calls the success-function, but with no data2.

A:

Try using only object as data, without wrapping it in an array:
$.ajax({
  url: 'http://myurl.de/get',
  data: { 'person_id': 2, 'action': 'getLinks' },
  method: 'POST',
  success: function(data2){
    console.log(data2);
  }
});


Q:

Cannot access the site after changing admin password

I have drupal 7 site hosted on bluehost.
After I changed the admin password, I got an error. I then tried to access the site, and I was able to do that, but it was very slow.
Now, I can't access the site as an administrator. It becomes even more weird: If I delete all history and cookies from the server, I can access the site; I can also login as an authenticated user.
When I try to log in as administrator, I get a white page or a "500 internal server" error. (It depends on the browser; I tried Chrome, FF and IE.) After I do that, I cannot access the site even as guest or authenticated user; only when I delete all the history and cookies, I can access the site as guest or authenticated user.
How can I fix this?
This is the error log the bluehost Representative gave me:

[15-Apr-2014 14:48:49 Europe/Helsinki] PHP Fatal error:  Call to undefined function intel_path_filter_type_to_arg() in /public_html/includes/menu.inc on line 814

Is it possiable this module has something to do with the issue? https://drupal.org/project/intel
I think I disable the google analytic api module. Maybe the problem is related to one of the Drupal SEO modules?
I am really not sure, and cannot connect my site..
Yesterday the site worked great!
Restoring the site to yesterdays backup did not help - this is the weirdest thing!

A:

The problem was related to one of the two below (or both):

The error from the intel module
The session cache / cache

Currently the site is live and working great, but the Intel module is active currently  and I don't know if to disable it or not.
The second thing we did (me and the nice guy that helped me) is to clear the cache and sessions cahce  - which was problematic for me since I did not had access as admin. We used update.php after allowing every user to access it on the setting.php file (changed false to true), and clear the cache through the mysql query on the 'my php admin'.
Here are the steps:

enter my php admin
choose database
go to mysql tab
on the query:
UPDATE system SET status='0' WHERE name='intel';
then need to flash the cache - run the query:

TRUNCATE TABLE sessions;
TRUNCATE TABLE cache;
TRUNCATE TABLE cache_bootstrap;
TRUNCATE TABLE cache_block;
TRUNCATE TABLE cache_field;
TRUNCATE TABLE cache_form;
TRUNCATE TABLE cache_image;
TRUNCATE TABLE cache_menu;
TRUNCATE TABLE cache_page;
TRUNCATE TABLE cache_path;
TRUNCATE TABLE cache_update;
TRUNCATE TABLE cache_views;
I will be happy to get feedback on this solution. The site is currently working - so problem solved.
But, I don't know if I still can't disable the intel module and if I can change the admin password. I don't want to cause the problem again.


Q:

C passing a list as argument

So i have my definition of the list as a global variable:
typedef struct center {

  char center_name[100];

  char hostname[100];

  int port;

  struct center *next_center;

} center;

I need to add elements to the list. But these elements that i need to add are on a file, so:
 int main(int argc, char** argv) {
     center *head = NULL;
     parse(argv, head);
  }

parse is a function, which read the file and add those read elements to a new center (all of this works, it double checked)
void parser (char** argv, center *head) {
   //read the elements i need to add
   //creates a newCenter and adds the elements read to the new center
   //this far it works
  addToCenter(newCenter, head);
}

where:
addToCenter(center *newCenter, center *head){
   //adds newCenter to the list
   if (head == null)
      head = newCenter;
   else {
      //find last element
      lastelement.next_center = newCenter;
   }

}

Everything works, except that the list on Main always return as null. In other words, the reference is not being modified. I dont understand why, because i am passing a pointer to the list.
another solution i though is to create the head variable of the list as a global variable, but its better to avoid those situations.
Thanks in advance.

A:

Your list head is being passed by value. You need to pass the head pointer by address in case it is modified (which it will be).
Example:
addToCenter(center *newCenter, center *head) // <=== note: passed by value
{
   //adds newCenter to the list
   if (head == null)
      head = newCenter; // <=== note: modified local stack parameter only.
   else {
      //find last element
      lastelement.next_center = newCenter;
   }
}

should be:
addToCenter(center *newCenter, center **head) // <=== note: now passed by address
{
   //adds newCenter to the list
   if (*head == null)
      *head = newCenter;  // <=== note: now modifies the source pointer.
   else {
      //find last element
      lastelement.next_center = newCenter;
   }
}

Likewise with parse:
void parser (char** argv, center **head) // <=== again, the head-pointer's *address*
{
   //read the elements i need to add
   //creates a newCenter and adds the elements read to the new center
   //this far it works
  addToCenter(newCenter, head);  // <=== just forward it on.
}

And finally back in main:
int main(int argc, char** argv)
{
     center *head = NULL;
     parse(argv, &head);  // <=== note: passing address of the head-pointer. (thus a dbl-pointer).
}

A:

You need to pass it like this:
void parser (char** argv, center **head) {
   //read the elements i need to add
   //creates a newCenter and adds the elements read to the new center
   //this far it works
  addToCenter(newCenter, &head);
}

addToCenter(center *newCenter, center **head){
   //adds newCenter to the list
   if (*head == null)
      *head = newCenter;
   else {
      //find last element
      lastelement.next_center = newCenter;
   }

}

And in main:
int main(int argc, char** argv) {
     center *head = NULL;
     parse(argv, &head);
}

You have to do this because values in C are by default, passed by value. Since you're passing the address of the list by value, and not by reference. When you pass the variable head by reference as above program, you'll be able to modify the list and get the data back to the list. Otherwise, it is going to pass by value and the value of head will never be modified(hence you got NULL)


Q:

Pronunciation of Mid-Word American English T + D

I'm a native speaker of American English but have a very muddy sounding voice that I'm trying to improve.  In my pronunciation the mid-word t/d sound, as in buddy, sweater, or under, is particularly bad.  It's kind of hard to explain how I pronounce it.  Maybe a little like a mild Indian accent?
How do you (people with amazingly good pronunciation;)) pronounce that sound?  I'm specifically looking for the standard American English pronunciation.  I know the tip of the tongue is supposed to make contact with the alveolar ridge, but the books I've been using don't explain those locations very precisely.  How far behind the teeth should the tongue be placed?  Does the "tongue tip" refer to the top or bottom part of the end of the tongue, or the endmost point on neither top nor bottom?  Does it change depending on the surrounding sounds?

A:

First of all, it's likely that although you feel you have problems with your intervocalic /t/ or /d/, you probably don't. (Your intervocalic /t/ or /d/ is just the /t/ or /d/ that you make between vowel sounds) It's far more likely that you are self-conscious about your speech—and that in you search to find out why, you have honed in on the difference between how you think your /t/ or /d/ should sound and how you think your actual /t/ or /d/ sounds. This is perfectly normal.
The way that we make a sound in isolation and the way that we make it in real speech between other sounds is very different. Every sound that we make is affected by the sounds around it in complicated and fascinating ways. As native speakers, we aren't consciously aware of this fact.
In standard American English, and often in  Southern Standard British English too, a /t/ will become voiced when both preceded by a vowel and followed by an unstressed vowel. When this happens the /t/ will become a tap. This means that the tongue will rapidly raise to the alveolar ridge and make a complete closure before rebounding back of the ridge. There is not enough time for the air to build up behind the closure, which is why it is a tap and not a normal /t/. Also for a majority of General American speakers, the vocal folds will keep vibrating for the duration of the consonant. This gives the /t/ a [d]-like quality.
When an intervocalic /d/ occurs between two vowels, the effect will be the same. So intervocalic /t/ and /d/ sound identical for a large number of Gen Am speakers.
When we make this sound, it is the top surface of the tip and rims of the tongue that make contact with the alveolar ridge.
If you genuinely have a slightly 'Indian'-sounding intervocalic /t/ or /d/, there are three possible causes that I can think of. The first is that you might be using the very, very tip (the apex) of your tongue to make this tap as opposed to—more or less—a normal closure like you do for a regular /t/ or /d/.
A second reason might be that you are using the underneath of your tongue to make the contact (I think this is unlikely, but this is just an opinion).
However, if your /t/ or /d/ really is Indian in quality, you may be making a retroflex contact. I'll explain what this is.
If you feel behind your top teeth with your tongue, you will feel a little flat, shelf-like bit of your mouth. Behind that your mouth suddenly arches up to form the 'roof' of your mouth. That shelf there is your alveolar ridge. We make our alveolar sounds in the middle of that ridge most of the time.
However, speakers from the Indian subcontinent often make /t, d, n, l/ just behind that ridge on the bit where the mouth is arching up. If you make your intervocalic /t/ or /d/ there, it will give you this kind of sound.
Having said all of this, if you are a native speaker, I doubt that this is a feature of you speech. More importantly, you do not need to worry about your pronunciation. How you say things, in terms of actual sounds, is not so important to good communication or relations with people. Far more important is your intonation, you body language, and what you actually are saying. If you have unusual intonation (for example if you don't have a good range of pitch when you speak), then this is worth worrying about and changing. Otherwise – enjoy your speech and use it to your best effect!
Hope this is helpful.


Q:

testthat in R: sourcing in tested files

I am using the testthat package in R and I am trying to test a function
defined in a file example.R. This file contains a call source("../utilities/utilities.R") where utilities.R is a file with functions written by me. However, when I am trying to test a function from example.R, sourcing it within the testing script gives the following error:
Error in file(filename, "r", encoding = encoding) :
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file '../utilities/utilities.R': No such file or directory

Could you please clarify how to run tests for functions in files that source another file?

A:

Might be a bit late, but I found a solution. Test_that sets the directory holding the test file as the current working directory. See the code below from test-files.r. This causes the working directory to be /tests. Therefore, your main scripts need to source ("../file.R"), which works for testing, but not for running your app.
https://github.com/hadley/testthat/blob/master/R/test-files.r
source_dir <- function(path, pattern = "\\.[rR]$", env = test_env(),
                       chdir = TRUE) {
  files <- normalizePath(sort(dir(path, pattern, full.names = TRUE)))
  if (chdir) {
    old <- setwd(path)
    on.exit(setwd(old))
  }

The solution I found was to add setwd("..") in my test files and simply source the file name without the path.  source("file.R") instead of source("../file.R"). Seems to work for me.


Q:

Can I add a Sammy route after run()

I have Sammy working just fine.  I want to dynamically at some point addHowever I want to add a route to Sammy after the run() is invoked.  Is this possible?
All my routes work that are specified before Sammy.run.  However I have some dynamic routes I want to add at a later point in time.
Thanks in advance, Scott

A:

Sure. You could define new routes after the run method. But, the initial route callback will not fire when you load the page. If you invoke the run(on dom ready) after you define your routes, sammy will fire the callback for the current route.
For example.
If you define 2 routes after run method

#/
#/List

and you hit the following url - www.mysite.com/index.html#/, the callback for #/ route will not be invoked.
I suggest calling app.runRoute('get', location.hash) or something similar to get the first route to fire.
Some code:
$(function()
    {
        app.run();

        app.get('#/', function()
        {
            alert('home');
        });

        app.get('#/list', function()
        {
            alert('list');
        });

        app.runRoute('get', location.hash);
    });

FYI Durandal 2.0 allows for child routes. Maybe have a look at.
Hope this helps