text:
Q: Spring MVC annotated controller in groovy I have this in src/main/groovy/...
package com.mycompany.web;
// imports....

@Controller
class GroovyController {

    @RequestMapping("/status_groovy")
    public @ResponseBody String getStatus() {
        return "Hello World from groovy!";
    }
}

Using maven 3 and spring 3.1 (Milestone). Spring MVC works perfectly well for java controllers and everything is set up fine. The groovy class compiles fine and can be found in the classes directory along with the java controller classes.
I have similar controller written in java (JavaController) in same package but under src/main/java and its getting picked up properly by spring and mapped and I can see the response on screen when I hit the url.
package com.mycompany.web;
// imports....

@Controller
class JavaController {

    @RequestMapping("/status")
    public @ResponseBody String getStatus() {
        return "Hello World!";
    }
}

Jetty starts normally with no error in log but in I dont see groovy url getting mapped whereas i can see the java one.
2011-09-23 16:05:50,412 [main] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/status],methods=[],params=[],headers=[],consumes=[],produces=[]}" onto public java.lang.String com.mycompany.web.JavaController.getStatus()

All the setting are fine as other parts of app are working just fine with annotations (component-scan etc.), Just that I can not get the url mapped in GroovyController
Can anyone explain what needs to be done in order to get Controllers written in groovy working?
PS: I am avoiding GroovyServlet to run the scripts because it has major downside when it comes to bean injection and url path mappings.

A: With all due respect to Ben (whom I work with), the problem here isn't that Spring is creating a cglib proxy. Rather, it's creating a dynamic JDK (or interface-based) proxy. This method of creating proxies can only implement methods declared in the target's implemented interfaces. You actually want Spring to create a cglib proxy, which creates a proxy that is a subclass of the target object and can therefore recreate all of its public methods. Unless you specify otherwise, Spring will create a cglib proxy if the target object doesn't implement any interfaces, and an interface-based proxy otherwise. Since all Groovy objects implement GroovyObject, you're getting an interface-based proxy, even though you didn't explicitly implement any interfaces in your Groovy controller. Ben's solution is correct in that if you create an interface with all your controller methods, you'll get the expected behavior. An alternative is to create a BeanFactoryPostProcessor which instructs Spring to create cglib proxies for classes that implement GroovyObject and only GroovyObject.  Here's the code:
/**
 * Finds all objects in the bean factory that implement GroovyObject and only GroovyObject, and sets the
 * AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE value to true.  This will, in the case when a proxy
 * is necessary, force the creation of a CGLIB subclass proxy, rather than a dynamic JDK proxy, which
 * would create a useless proxy that only implements the methods of GroovyObject.
 *
 * @author caleb
 */
public class GroovyObjectTargetClassPreservingBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    private static final Logger logger = LoggerFactory.getLogger(GroovyObjectTargetClassPreservingBeanFactoryPostProcessor.class);

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        for (String beanDefName : beanFactory.getBeanDefinitionNames()) {
            BeanDefinition bd = beanFactory.getBeanDefinition(beanDefName);
            //ignore abstract definitions (parent beans)
            if (bd.isAbstract())
                continue;
            String className = bd.getBeanClassName();
            //ignore definitions with null class names
            if (className == null)
                continue;
            Class<?> beanClass;
            try {
                beanClass = ClassUtils.forName(className, beanFactory.getBeanClassLoader());
            }
            catch (ClassNotFoundException e) {
                throw new CannotLoadBeanClassException(bd.getResourceDescription(), beanDefName, bd.getBeanClassName(), e);
            }
            catch (LinkageError e) {
                throw new CannotLoadBeanClassException(bd.getResourceDescription(), beanDefName, bd.getBeanClassName(), e);
            }

            Class<?>[] interfaces = beanClass.getInterfaces();
            if (interfaces.length == 1 && interfaces[0] == GroovyObject.class) {
                logger.debug("Setting attribute {} to true for bean {}", AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, beanDefName);
                bd.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, true);
            }
        }
    }
}

Just include a bean of this type in your context, and voila! You can have Groovy controllers without needing to define interfaces.

A: I beg to differ. There is no need to implement an interface. The problem here is that the default AnnotationMethodHandlerAdapter does not read annotations from proxies. Hence we would have to create this proxy aware AnnotationMethodHandlerAdapter which extends the default AnnotationMethodHandlerAdapter of spring. We also need to instantiate a bean for this ProxyAwareAnnotationMethodHandlerAdapter in the Spring Configuration xml file.
Note: This feature is not available in Spring 3.x but since spring 4.0 would support groovy beans, this feature should be covered.
//ProxyAwareAnnotationMethodHandlerAdapter.java

    package name.assafberg.spring;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.springframework.aop.TargetSource;
    import org.springframework.aop.framework.Advised;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;

    /**
     * Add proxy awareness to AnnotationMethodHandlerAdapter.
     *
     * @author assaf
     */
    public class ProxyAwareAnnotationMethodHandlerAdapter extends AnnotationMethodHandlerAdapter {

        /**
         * @param request
         * @param response
         * @param handler
         * @return
         * @throws Exception
         * @see org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
         */
        @Override
        public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            handler = unwrapHandler(handler);

            return super.handle(request, response, handler);
        }

        /**
         * @param handler
         * @return
         * @see org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#supports(java.lang.Object)
         */
        @Override
        public boolean supports(Object handler) {
            handler = unwrapHandler(handler);

            return super.supports(handler);
        }

        /**
         * Attempt to unwrap the given handler in case it is an AOP proxy
         *
         * @param handler
         * @return Object
         */
        private Object unwrapHandler(Object handler) {
            if (handler instanceof Advised) {
                try {
                    TargetSource targetSource = ((Advised) handler).getTargetSource();
                    return targetSource.getTarget();

                } catch (Exception x) {
                    throw new RuntimeException(x);
                }

            } else {
                return handler;
            }
        }

    }

The spring configuration XML file must have the following. Instead of creating a bean of AnnotationMethodHandlerAdapter we must create a ProxyAwareAnnotationMethodHandlerAdapter bean.
<beans .........
...
...
      <bean class="full.qualified.name.of.ProxyAwareAnnotationMethodHandlerAdapter" />
...
...
      <lang:groovy script-source="classpath:com/example/mysample.groovy refresh-check-delay="1000" />
</beans>

Also Spring parses the configuration XML file using a SAX parser (based on event occurence). So, in order for spring to understand the annotations within the groovy scripts, the groovy beans (using  tag) must be created after the ProxyAwareAnnotationMethodHandlerAdapter.
Hope than helps
Reference: http://forum.springsource.org/showthread.php?47271-Groovy-Controller

A: Unfortunately, if you want to get this running in Groovy you'll have to create an interface for your Controller class and annotate the method definitions as well. Spring creates a proxy for your class using Cglib. However, without creating a custom interface for your controller Spring is proxying on groovy.lang.GroovyObject because all Groovy objects implement that interface by default.
interface GroovyControllerInterface {
    @RequestMapping("/status_groovy")
    @ResponseBody String getStatus()
}

@Controller
class GroovyController implements GroovyControllerInterface {
    @RequestMapping("/status_groovy")
    public @ResponseBody String getStatus() {
        return "Hello World from groovy!";
    }
}


text:
Q: Special relativity and Simultaneity I am struggling on a problem involving 2 events seen in different reference frames and could do with advice or a starting point for this question:

A spaceship approaches a galaxy travelling with a speed of 0.1c relative to the galaxy. The crew on the spaceship observe two supernovae directly ahead in the galaxy. From the relative brightness, they determine that the supernovae are 10 light years apart, as measured in the spaceship restframe. The crew observed the supernovae at exactly the same time.
  a) Did the supernovae explode simultaneously in the spaceship rest frame? If not,which 1 exploded first, and what was the time delay between them in the spaceship
  rest frame?
  b) Astronomers on a planet in the rest frame of the supernovae at the midpoint between
  them also observe the supernovas. Did the supernovae explode simultaneously
  in their rest frame? If not, which one do they observe first?<

I assumed in the spaceships restframe there would just be a time difference of 10 years. However I am completely unsure if I am thinking about this question in the right way, and have little idea of how to tackle part b) as the planet being at a midpoint has thrown me off. Any advice, or a link to a similar already answered question would be much appreciated.

A: Your time difference answer is correct. They did explode at a time difference of 10 years in the spaceship frame. This question isn't a relativity question at all till now and what is given till now is just the data in a clever form to be able to do the part B of the question.
Now coming to part B,
Astronomers are in the middle in the rest frame of the supernovae, hence, for rest frame of the supernovae, Now, for them you've to find the coordinates between the events for the supernovae frame. For them the spaceship is moving at 0.1 c(assuming supernovae are at rest w.r.t. galaxy, this assumption is not from the question), the spatial difference between events for the spaceship is 10 light years for the space ship and time difference between the events is 10 years for the spaceship.
Now you can do the lorentz transformation, and if you find delta t between the two explosions to be non zero for the supernovae frame. It isn't simultaneous in the astronomer's frame. I think the time difference would come out to be something like ~11.8 years. The midpoint of the planet is w.r.t. the galaxy/supernovae frame according to the question.
Also, one can see that since light from first supernovae just manage to catch up with the second supernovae, hence these events are on the light like seperated w.r.t. the spaceship observer. Hence, they can't be simultaneous/time-like for any observer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Will restarting SQL Server clear my transaction log? I have a client that restarts his SQL Server instance to clear an application problem he is encountering.
I find this is very odd, I don't think you should ever restart the database in normal operation. I believe his transaction log is simply full and restarting may be counting as a checkpoint? Is this a valid theory? He's in simple recovery mode - what I can do to check if this is the case?
Do we know of any other reasons why restarting the SQL Server service would make a problem disappear for a few days?

A:
I believe his transaction log is simply full and restarting may be counting as a checkpoint? Is this a valid theory?

No, this is not right. That is the most brutal thing you can do to sql server to just clear out the log (which makes things worse). If there is a long running transaction, then restarting your sql server will put that database in recovery until the rollback happens.
since you are running in simple recovery mode, ONLY a CHECKPOINT - manually or sql server running it at regular intervals will allow SQL Server to reuse the transaction log (the log will be marked for truncation).
Note that TRUNCATE_ONLY is not supported in sql server 2008 and up, but that was used to do a FORCE log truncation (sql server 2005 and earlier versions) - BACKUP LOG <database_name> WITH TRUNCATE_ONLY
Please read  - Why Does the Transaction Log Keep Growing or Run Out of Space? (putting it in bold to emphasis to read it until you fully understand and digest the 2 best answers).
Also, make sure you have a good auto growth setting for your database.

Do we know of any other reasons why restarting the MS SQL service would make a problem disappear for a few days?

You should start with How to analyse SQL Server performance


text:
Q: Integrable increasing function Let $f$ Lebesgue integrable function.Then, is there measurable function $h$ such that $h$ is increasing, $\lim _{x\to \infty } h(x)=\infty $, and $fh$ is integrable ?
I guess when $n$ is large, $h_n(x):=\log{\log {\cdots \log{x}}}=\log^n{x}$ satisfies. But I cannot prove it.

A: Assuming that all these functions are on $\mathbb{R}^d$, $h$ cannot be lebesgue integrable if it goes to $\infty$ as we go far away from the origin. If $f$ is integrable, we know that $\int_{B^c}|f|<\epsilon$ for a sufficiently large ball $B$ around the origin. Take a sequence of such increasing balls $\{B_n\}$ such that the integral of $|f|$ over $B_n-B_{n-1}$ is less than $\epsilon/2^n$. Now, build $h$ such that $h$ is equal to $2^{n/2}$ in the region between $B_{n-1}$ and $B_n$. Define $h$ to be $0$ inside $B_1$. This function $h$ is increasing and goes to infinity as we go away from the origin. Also, $fh$ is integrable as the sum $\sum \frac{\epsilon}{2^{n/2}}$ is finite.
If all these functions are defined on $\mathbb{R}$ and we want $h$ to be increasing in the usual sense, then we can just take $h'$ instead of $h$, where $h'=h$ for the positive real line, and $h'=-h$ for the negative real line. $h'$ is now increasing and satisfies the other conditions.

A: One can write down such a function $h$ explicitly in terms of $f$. First assume that $|f|>0$. define $h(x)=\frac 1 {\sqrt {\int_x^{\infty} |f|}}$ if $x \geq 1$ and $0$ otherwise. Clearly. $h(x) \to \infty$ as $x \to \infty$. Now let $g(x)= {\int_x^{\infty} |f|}$. Then $\int |f|h =\int_0^{\infty} \frac {-g'(x)} {\sqrt {{g(x)}}}=2\sqrt {g(1)}$ so $|f|h$ is integrable. For the general case replace $f$ by $|f|+e^{-|x|}$. The function $h$ which works for this also works for $f$.


text:
Q: Overriding Bootstrap with using my external stylesheet I am trying to learn Bootstrap and wanted to make an exercise by building this site on my own:
https://konect.co.za/
I am seriously having trouble with overriding to Bootstrap and also adding my custom font. To add my custom Google font, I've tried this, but did not work;
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

and in css
html{
font-family:"Roboto", "Arial";
font-size:20px;
font-weight:300;}

Here's the img that I cannot style;

And the styling;
section img .profile-pic{
margin-left:150px;

}

A: Try to add in Body
 body {
  font-family: 'Roboto', sans-serif !important;
}

The html styles will apply to all document but it has very low precedence. it will work only until and unless their is not specified styles inside body. but in your case bootstrap added their own styles in body tag.
body {
    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
    font-size: 14px;
    line-height: 1.42857143;
    color: #333;
    background-color: #fff;
}

Thats why your style was not working

A: You need to put "!important" with your custom CSS style to override any bootstrap styles. Also, CSS will always use the most specific style to style an element so if you put your styles in html{} it will be overridden by p{} h1{} etc. Remember that style sheets are cascading so any styles at the top will be overwritten by styling the same element below.

A: You need to put "!important" with your custom css style to override bootstrap css.
One more thing if you are using external custom css file than import after bootstrap css file.
See, below example for more.

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

 testing bootstrap overriding

Konect

Technology & Data Management Specialists

without custom style


text:
Q: Nodejs - Socketio not working with https server, what could be the reason? I tried debugging using http server, and socket.io worked, however when I try to use https socket.io stopped working
// create server for http and https
//var httpserver = http.createServer(app).listen('3000', '127.0.0.1');
var https_server = https.createServer(options, app).listen('4000', '127.0.0.1');
// let the backend listens to this server
UserServer.listen(https_server);
//UserServer.listen(httpserver);

exports.listen = function(server){

    io = socketio.listen(server);
    io.sockets.on('connection', function(socket){
        console.log("Socket is connected, sweet ");
    });
}

When
var httpserver = http.createServer(app).listen('3000', '127.0.0.1');
UserServer.listen(httpserver);

Print out
Socket is connected, sweet "

When
var https_server = https.createServer(options, app).listen('4000', '127.0.0.1');
UserServer.listen(https_server);

There are no output
Here are my set up for https
var express = require('express'),
    https = require('https'),
        fs = require('fs');

var options = {
  key: fs.readFileSync('./key.pem', 'utf8'),
  cert: fs.readFileSync('./cert.pem', 'utf8')
};

I was able to display the https page, so I am guessing https setup was not the problem
Any advice would be appreciated, thanks

A: First of all, you need to run Node.js Server with SSL.
Server.js
var fs = require('fs');
var options = {
    key: fs.readFileSync('ssl/private/domain.com.key'),
    cert: fs.readFileSync('ssl/certs/domain.com.crt'),
    ca: fs.readFileSync('ssl/certs/domain.com.cabundle')
};
// You can do this easily if you are on windows
// var options = { pfx: fs.readFileSync('/home/mydir/secure.pfx'); };
var app = require('https').createServer(options, handler),
    io = require('socket.io').listen(app);

//Recommended Production settings
io.enable('browser client minification');  // send minified client
io.enable('browser client etag');          // apply etag caching logic based on version number
io.enable('browser client gzip');          // gzip the file
io.set('log level', 1);                    // reduce logging
io.set('flash policy port', 3300); //==>  override Flash Policy Port
io.set('transports', [                     // enable all transports (optional if you want flashsocket)
    'websocket'
  , 'flashsocket'
  , 'htmlfile'
  , 'xhr-polling'
  , 'jsonp-polling'
]);
function handler(req, res) {
    res.writeHead(200);
    res.end("welcome sir!");
};
io.sockets.on('connection', function (socket) {
    socket.on('message', function (data) {
        socket.broadcast.emit('message', data);
    });
});
app.listen(3300);

Client.js
   //socketAddress is server uri  ex. https://www.domain.com:3300
   var socket = io.connect(socketAddress, {'flash policy port':3300} );
   socket.on('connect', function (data) {
      //....
   });
   socket.on('message', function (data) {
      //....
   });


text:
Q: Running a python program from a terminal issue Basically this is something that I had an issue with running C programme and I'm trying to run a python program from a terminal but the problem arises again. after tying an exact file in a exact directory the terminal doesn't seem to run the program and just skip it.
Is there something that I'm doing wrong to run and display on a terminal
command?
$ ls
hello_world.py
$ python hello_world.py
$

This below 'script' is how I run the code with sublime text. Basically from my point of view there is no problem in script itself..
print('Hello Python world!')

A: If your python is properly installed then there is no problem with the terminal. Python interpreter executes code line by line.It is completing the file and coming out of it.

A: Whenever I have this kind of problem it is because the file I'm trying to run is not the same I am changing. I recommend using something (like cat) to check the content of the file before actually running it.
So, in your case, pop up your terminal and run:

$ cat hello_world.py

The output should be
$ cat hello_world.py
print("Hello Python World!")

If the output is blank, there is your problem. Try to open that exact file with sublime. Probably with
$ sublime hello_world.py

A: At the top of your .py file
Add
#!/usr/bin/python3

Then when you need to give your file permissions
chmod +x hello_world.py

Then to run
./hello_world.py

This will run it in python3 if you want python2 just change that in the usr/bin


text:
Q: download pdf from a web page's html using vue js In my application, there is an option to download pdf using URL input of same domain(intranet site). There are 3 pages in my application(http://example.com/about, http://example.com/home, http://example.com/htmltopdf)
In htmltopdf page, there is a text input field and button download pdf. If we give input url (http://example.com/about), It should download pdf of about page's html. For this, i have tried couple of things but it is converting pdf from the index.html of public folder.
I am using vue js in my application and i have tried like this
Approach -1
    downloadHtml() {
  let url = this.urlInput;  // input text v-model value
  fetch(url)
    .then((res) => res.text())
    .then((html) => this.downloadAsFile("report.pdf", html)); // by this name it is downloading
},
downloadAsFile(name, text) {
  const link = this.createDownloadableLink(name, text);
  const clickEvent = new MouseEvent("click");
  link.dispatchEvent(clickEvent);
},
createDownloadableLink(fileName, content) {
  let link = document.createElement("a");
  link.href = `data:attachment/text,${content}' + encodeURIComponent(document.documentElement.outerHTML);
  link.target = '_blank';
  link.download = fileName;
  return link;
},

Approach -2 (based on answer of another post)
    async fetchHTML() {
   let url = this.urlInput
let content = await fetch(url).then(resp => resp.text());

let file = new Blob([content],{type:'text/html'});
let href = window.URL.createObjectURL(file);
let a = document.createElement('a');

a.href = href;
a.setAttribute('download', 'report.pdf');
document.body.appendChild(a);
a.dispatchEvent(new MouseEvent('click'));

}

For these two approaches, it is downloading the pdf of public/index.html not the actual one. After checking or searching more, i got some suggestions to use puppeteer or nuxt.js for this downloading pdf but i didn't get that any example for this scenario. I am not sure how to do this function workable in vue.js platform or how to use puppeteer in vue.js?
I have checked vue-htmltopdf npm package but how to send URL directly there to download pdf?
Please give me suggestion or example how to download pdf from given URL input of same domain?


text:
Q: IE8 automatically uses the "IE8 Compat View" browser mode and "IE7 Standards" document mode I built a website based on the HTML5 Boilerplate. I haven't changed anything in the boilerplate, other than adding my custom code to the Body part in the HTML. I'm targeting IE8 as the minimum IE version to support.
The problem is that when I open my page on IE8 it automatically uses the "IE8 Compat View" browser mode and the "IE7 Standards" document mode, instead of using the IE8 Standards for both browser and document modes.
Anyone has an idea why this might be happening and how to force it to use the right modes without requiring the user to change options in IE8?

A: You might be testing the site on a local network. In this circumstances, IE8 will by default use the modes described in the question. IE8 has a different default behaviour for sites coming from a local network or intranet.
If the page you're testing is hosted outside the local network, then IE8 will use the correct standard modes.
If you need to test the website locally, just use IE8's developer tools to switch to the IE8 standard browser mode.

A: <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

Use the above meta tag to force IE to use the latest rendering engine it has available.

A: The behavior chocobanana describes is also described here, see the entry "IE9 Compatibility View and Intranet Sites".
If you do not want to manually switch the browser/document modes in the developer tool all the time nor want to include a X-UA-Compatible-Tag you can undo the default setting that always renders intranet sites in compat mode by unchecking the respective checkbox in Tools > Compatibility View Settings.
Took me nearly a day to figure out why my local version in one IE8 tab looks fine while the intranet server version of the same page in another tab is all screwed up with regard to layout ... *sigh*
In any case, this only applies to your machine, so in order to force your clients to not fall into compat mode you will have to set the respective meta tag.

A: Please check the following things:
1) Using "View source", Make sure that you are using
<!DOCTYPE html>

at the top of your pages.
2) If the line appears at the top, make sure that there are NO spaces or newlines before this line. It has happened to me that some PHP has an extra new line after the ?> that is printed to screen and causes the doctype not to appear as the very first thing on the document.


text:
Q: how to move to popToViewController: from tabBarController I have my app is a TabBarController, and I have to take different actions depending on which tab is pressed, so, I delegate TabBarContoller, and I got it.
Now in case a tab which contents a NavigationController is pressed, depending on a database value, the view that should be shown is the first one or the last one, so in Tabs.m:
-(void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
 NSArray *viewArrays = [(UINavigationController*)viewController viewControllers];

switch (tabBarController.selectedIndex) {

    case 3:
    {
        NSString *query = @"SELECT * FROM login";
        sqlite3_stmt *statement = [[Database alloc] select:query];

        if(sqlite3_step(statement) == SQLITE_ROW) {
           [(UINavigationController*)viewController popToViewController:[viewArrays objectAtIndex:1] animated:YES];

        }
        sqlite3_finalize(statement);
        break;
    }
    default:
        break;
}

}
The problem is objectAtIndex:1 doesn't exist right now

A: You can popView only if you have done pushView atleast once. Print and see the objects inside self.navigationController.viewControllers using NSLog and if it contains some object then give your index appropriately(within the range), i am confused why you are doing (UINavigationController*)viewController, try this instead
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2] animated:YES];


text:
Q: WinForms C# DataGridView force refresh Baby steps rolling...  I have a form with a data grid bound to a table.  I have some textboxes on the form bound to the table[columns], so as I scroll the grid, the textboxes show corresponding data.
I go to an "Edit Mode" of the textboxes and change the content and hit a save button.  The grid doesn't refresh the changed context until I physically click in the cell which forces a call to the tables OnChanging and OnChanged events...
How can I FORCE whatever event to "flush" the table at the end of my edit and have it refreshed in the datagridview.
Thanks

A: Have you tried calling the dataGridView's Invalidate method?
this.dataGridView1.Invalidate();

A: Are you using a BindingSource?  If so, call its EndEdit method on the TextBox's Leave event.


text:
Q: Identifying the joint distribution from some values of $t \cdot X$ Suppose that $S$ is a subset of $\mathbb{R}^n$ and $X, Y$ are $\mathbb{R}^n$ valued RVs.  We already know that $X$ and $Y$ are equidistributed iff $t \cdot X=^d t\cdot Y$ for all $t \in \mathbb{R}^n$.  For which $S$ is it also true that $X$ and $Y$ are equidistributed iff $t \cdot X=^d t\cdot Y$ for all $t \in S$?
Since the set of $t$ for which one has $t \cdot X=^d t\cdot Y$ is closed under scalar multiplication and limits (thanks to studying the characteristic function) we have that any $S$ for which $\mathbb{R}S$ is dense in $\mathbb{R}^n$ works.  Is there a characterization?  Particularly, I am interested in the case $n=2$ with $S$ being all 2-vectors of the form $(1, k^{1/2})$ where $k \in \mathbb{N}$.  But if a general characterization is available that is interesting to me too.


text:
Q: usbtiny not working with avrdude I recently bought a USBtiny ISP programmer from gikfun on eBay. It is labeled Deek Robot v20 on the PCB. It was cheap.
Using avrdude I am unable to communicate with my atmega328p micro-controller. The drivers for USBtiny are loaded correctly.
I'm getting the error
avrdude: initialization failed, rc=-1
...

The 6 pin IDC connector from the USBtinyto atmega328p is wired up like this:
IDC pin      atmega328p
1            18 (MISO)
2             7 (Vcc)
3            19 (SCK)
4            17 (MOSI)
5             1 (RESET)
6             8 (GND)

A: Turns out the problem was the IDC cable that came with the USBtiny is made incorrectly. The connector on one end is on backwards, so after taking that into consideration I was able to get it to work.


text:
Q: PHP IF statement within MSSQL call Ok, I've spent entirely too long trying to add an if statement within a TSQL query string. Any help would be appreciated. Here's the string with a syntax error.
$sql = "SELECT tblCasesLawyers.CaseID, tblCasesLawyers.PLAINTIFFLASTNAME + ', ' + tblCasesLawyers.PLAINTIFFFIRSTNAME AS PatientName, tblProcedures.ApplicationSubmitted, tblProcedures.CPTCode, tblProcedures.ProcedureDescription, tblCenters.CenterID, tblProcedures.ProcedureDate, tblProcedures.ProcedureStatus, tblProcedures.LeinAmount, tblProcedures.DatePaid
FROM (tblCasesLawyers INNER JOIN tblCenters ON tblCasesLawyers.Center_ID__C = tblCenters.CenterID) INNER JOIN tblProcedures ON tblCasesLawyers.CaseID = tblProcedures.CaseID
WHERE (((tblCenters.CenterID)={$_SESSION['center']}) AND (tblProcedures.ApplicationSubmitted >= 2012-05-01)".if !empty($_GET['search']) echo ('AND tblCasesLawyers.PLAINTIFFLASTNAME='.{$_GET['search']}).")
";

Thank you all for chiming in. I'm relatively new at this but attempted to prevent injection using the following:
    function ms_escape_string($data) {
    if ( !isset($data) or empty($data) ) return '';
    if ( is_numeric($data) ) return $data;

    $non_displayables = array(
        '/%0[0-8bcef]/',            // url encoded 00-08, 11, 12, 14, 15
        '/%1[0-9a-f]/',             // url encoded 16-31
        '/[\x00-\x08]/',            // 00-08
        '/\x0b/',                   // 11
        '/\x0c/',                   // 12
        '/[\x0e-\x1f]/'             // 14-31

    );
    foreach ( $non_displayables as $regex )
    $data = preg_replace( $regex, '', $data );
    $data = str_replace("'", "''", $data );
    return $data;
    }

    function sanitize($data){
    $data=trim($data);
    $data=htmlspecialchars($data);
    $data=ms_real_escape_string($data);
    return $data;
    }

    $search = sanitize($_GET['search']);

A: What about an inline conditional?
<?php

$sql = "SELECT tblCasesLawyers.CaseID, tblCasesLawyers.PLAINTIFFLASTNAME + ', ' + tblCasesLawyers.PLAINTIFFFIRSTNAME AS PatientName, tblProcedures.ApplicationSubmitted, tblProcedures.CPTCode, tblProcedures.ProcedureDescription, tblCenters.CenterID, tblProcedures.ProcedureDate, tblProcedures.ProcedureStatus, tblProcedures.LeinAmount, tblProcedures.DatePaid
FROM (tblCasesLawyers INNER JOIN tblCenters ON tblCasesLawyers.Center_ID__C = tblCenters.CenterID) INNER JOIN tblProcedures ON tblCasesLawyers.CaseID = tblProcedures.CaseID
WHERE (((tblCenters.CenterID)={$_SESSION['center']}) AND (tblProcedures.ApplicationSubmitted >= 2012-05-01)"
.( (!empty($_GET['search'])) ? ' AND tblCasesLawyers.PLAINTIFFLASTNAME='.$_GET['search'] : '').")";

?>

A: I don't think it is syntactically legal to concatenate an if statement like that.  It doesn't evaluate to anything that the operator can undestand.  Use a ternary or chop your statement into three pieces (after writing a cleanse method based on this answer:
$cleanCenterID = cleanse($_SESSION['center']);
$clentSearch = cleanse($_GET['search']);

$sql = "SELECT tblCasesLawyers.CaseID, tblCasesLawyers.PLAINTIFFLASTNAME + ', ' +tblCasesLawyers.PLAINTIFFFIRSTNAME AS PatientName, tblProcedures.ApplicationSubmitted, tblProcedures.CPTCode, tblProcedures.ProcedureDescription, tblCenters.CenterID, tblProcedures.ProcedureDate, tblProcedures.ProcedureStatus, tblProcedures.LeinAmount, tblProcedures.DatePaid
FROM (tblCasesLawyers INNER JOIN tblCenters ON tblCasesLawyers.Center_ID__C = tblCenters.CenterID) INNER JOIN tblProcedures ON tblCasesLawyers.CaseID = tblProcedures.CaseID
WHERE (((tblCenters.CenterID)={$cleanCenterID}) AND (tblProcedures.ApplicationSubmitted >= 2012-05-01)";

if(!empty($cleanSearch)) {
    $sql .= 'AND tblCasesLawyers.PLAINTIFFLASTNAME='.{$cleanSearch});
}

$sql .= ")";

A: You could use an inline "if" to insert your conditional statement into the string, i.e.
$sql = 'Your sql '.(!empty($_GET['search']) ? 'some sql' : 'some other sql').' the rest of your sql';

A: I think that you need a single line if here :
 "AND (tblProcedures.ApplicationSubmitted >= 2012-05-01)".
((!empty($_GET['search']) ? 'AND tblCasesLawyers.PLAINTIFFLASTNAME=' . $_GET['search'] : '' ).
")

As stated in some comments concatenating a query in this way could lead to SQL Injection, to avoid SQL injection you can use prepared statements and parameterized queries, see this question to know the best way to avoid SQL injection ;-) .
Thanks
Went with
$sql = "SELECT tblCasesLawyers.CaseID, tblCasesLawyers.PLAINTIFFLASTNAME + ', ' + tblCasesLawyers.PLAINTIFFFIRSTNAME AS PatientName, tblProcedures.ApplicationSubmitted, tblProcedures.CPTCode, tblProcedures.ProcedureDescription, tblCenters.CenterID, tblProcedures.ProcedureDate, tblProcedures.ProcedureStatus, tblProcedures.LeinAmount, tblProcedures.DatePaid
FROM (tblCasesLawyers INNER JOIN tblCenters ON tblCasesLawyers.Center_ID__C = tblCenters.CenterID) INNER JOIN tblProcedures ON tblCasesLawyers.CaseID = tblProcedures.CaseID
WHERE (((tblCenters.CenterID)={$_SESSION['center']}) AND (tblProcedures.ApplicationSubmitted >= 2012-05-01)".( (!empty($search)) ? " AND tblCasesLawyers.PLAINTIFFLASTNAME='". $search . "'" : '').")";

A: Would it work if you replace your code:
.if !empty($_GET['search']) echo ('AND tblCasesLawyers.PLAINTIFFLASTNAME='.{$_GET['search']}).")

with this:
'AND (  tblCasesLawyers.PLAINTIFFLASTNAME='.{$_GET['search']}.' OR len('.{$_GET['search']}.') = 0 OR '.{$_GET['search']}.' is null)'


text:
Q: Removing leading spaces from a string I have a String like follows
 abc, def tgy, awed djdj

Now i want to get all the parts of this string seperated by comma. Best way i can image is doing the following
final String[] splits = country.split(",");

Now i should have a array with 3 strings. But i dont want the leading spaces in each string also. How can i remove them. Is there a special way to do that? Or i have to use the same old regex way to remove the leading spaces.

A: You can use this regex to remove leading/trailing spaces from split elements:
final String[] splits = country.trim().split(" *, *");

A: use this call on a string to remove leading and trailing spaces:
arbitraryVariable = arbitraryVariable.trim()

A: ,\s*

You can split by this as well.This will remove leading spaces.See demo.
http://regex101.com/r/jT3pG3/13


text:
Q: Order Precedence || Order of Operations I was working through some code in the classroom and came across the following:
int x 14;
int y 3;

x = x-- % y--'

The result after compiling is
'x = 2 '
'y = 2'
I am having a very difficult time understanding the order or operations for this particular scenario.
My logic based off of Oracles Operators Precedence
(Here)
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Would conclude:
x = (x = x -1 ) % ( y = y - 1)  (because of order precedence)
Therefore: x = 13 % 2
x = 1
y = 2
I am wrong please tell me why.  I have horse blinders on.
Thanks in advance.

A: This:
int x = 2;
println(x--);

prints 2 but leaves x at 1. Suffix increment and decrement give you the value before the variable is altered.
This:
int x = 2;
println(--x);

prints 1 and leaves x at 1. Prefix increment and decrement give you the value after the variable is altered.
EDIT:
If you assign to x in the same expression, the assignment happens last.
int x = 3;
x = 2*(x--);

The value of x-- is 3 (the value before x is decremented). So after the assignment, x ends up with the value 6 in this case.
So for your example:
int x = 14;
int y = 3;

x = x-- % y--;

The value of x-- is 14 (the value before x is decremented). The value of y-- is 3 (the value before y is decremented). So x gets assigned to 14%3==2. y is left at its decremented value, 2.

A: x-- return x and decrease after.
x = 14, y = 3
x = 14 % 3 → 2,  (x = x - 1 → 13 is done before the x receive  14 % 3 → 2)
y = y - 1 → 2

--x decrease and return x

A: I think this happens:
int temp = (x % y);
x--;
y--;
x = temp;


text:
Q: Facebook offline_access removal... Will some Android users need to login every 60 days? I received an email from Facebook saying offline access will no longer be available as of May 1, 2012.
It seems to me that, all new users of my Android app, unless the user has the Facebook for Android app installed on their device, will need to relogin every 60 days.
Am I correct?
Relevant links
http://developers.facebook.com/bugs/329021273822477?browse=search_4f757888330df1200687453
https://developers.facebook.com/roadmap/offline-access-removal/
https://developers.facebook.com/docs/mobile/android/build/#extend_token
https://github.com/facebook/facebook-android-sdk/

A: Why did you use the "offline_access" to begin with?
From what you described it does not seem like you need it at all.
The facebook android sdk provided you with the SSO which removes the need to login to facebook every time, if the user has the facebook application installed on his android.
Then, you can use the sdk Dialogs or api requests (even in async) to post on the users wall.
Since you are using the sdk it should already take care of the authentication process for you and will (if the user granted your facebook app the right permissions) have a valid access token that it will be using.
More than that, not all access tokens are valid for 60 days, only those created by a server-side flow or if you use the new end point facebook provided for those who used the "offline_access" permission. To read more about that check the Removal of offline_access Permission doc.


text:
Q: SQL: Creating ordinal columns from return set I have a MySQL table of the form...
record    timestamp
1         2014-07-10
2         2014-07-10
1         2014-07-11
2         2014-07-11
1         2014-07-12
2         2014-07-12

...and I want to query this in such a way that I return a set of the form...
record    1st time    2nd time    3rd time
1         2014-07-10  2014-07-11  2014-07-12
2         2014-07-10  2014-07-11  2014-07-12
...

I'm comfortable using MAX() and a subquery to achieve the most-recent timestamp, but this seems more suited to returning an iterable SQL object. For instance, if I could create the above with something like...
SELECT record, timestamp[0] AS "1st time", timestamp[1] AS "2nd time", timestamp[2] AS "3rd time"

...that would be great. Is this something PIVOT() could be used for?

A: For the above data set limited to 3 columns you can do like below
SELECT t1.record,
MAX(CASE WHEN t1.rownum = 1 THEN t1.timestamp  END) AS `1st time`,
MAX(CASE WHEN t1.rownum = 2 THEN t1.timestamp  END) AS `2nd time`,
MAX(CASE WHEN t1.rownum = 3 THEN t1.timestamp  END) AS `3rd time`
FROM (
  SELECT t.*,
  @r:= CASE WHEN @g= record THEN @r + 1 ELSE 1 END rownum,
  @g:=record
  FROM table t
  CROSS JOIN (SELECT @g:=0,@r:=0) t1
  ORDER BY `record`, `timestamp`
  ) t1
GROUP BY t1.record

Demo


text:
Q: jQuery Mobile pageCreate doesn't fire on page revisit Here is my scenario:  I'm building a web application for an embedded system user interface.  I'm planning on using jQuery Mobile because it is incredibly slick.  I have a single page per file pattern going on.  I have a file called processinputs.html that is shown below.  All it does is navigate you to input.html with a query param selecting the channel number.
The problem:  The first time I go from processinputs.html to inputs.html?i=3 everything works great.  The header and link gets modified.  Although, if I go back to processinputs.html and click on the 3rd input link again the event does not get fired and therefore my header does not get updated.
I'm assuming this has to do with AJAX loading a cached page and thereby not triggering the "pagecreate" event.  I have also tried "pageinit" and "pagebeforecreate".  In my project.js file I have tried to disable domCache and ajax but it does not appear to be working.  You'll see that I hardcoded "rel=external" for Input 1 on processinputs.html.  That works every time, but really jQMobile is so cool because of the ajax loading and animations.  If you can help me figure out how to get around the caching I would be much obliged.
$(document).bind("mobileinit", function(){
$.mobile.ajaxLinksEnabled=false;
$.mobile.ajaxFormsEnabled=false;
$.mobile.ajaxEnabled=false;
$.mobile.page.prototype.options.domCache = false;

});
Now for the promised processinputs.html

    <link rel="stylesheet" href="css/jquery.mobile-1.0rc2.css" />
    <link rel="stylesheet" href="css/styles.css" />

    <meta name="viewport" content="width=default-width, initial-scale=1" />

Process Inputs

            Home

Select an input

                Input 1
                Input 2
                Input 3
                Input 4
                Input 5
                Input 6
                Input 7
                Input 8

A Senior Design G13 Project

input.html takes the query param and uses it to modify the header of input.html as well as the query param for the three links on the page.  The code is shown below:
    <link rel="stylesheet" href="css/jquery.mobile-1.0rc2.css" />
    <link rel="stylesheet" href="css/styles.css" />

            Home

Select one.

                Equalization
                Compression
                Limiting

A Senior Design G13 Project

A: All JavaScript for each page should be in the root page (index.html or what ever page you load first)


text:
Q: Does the C standard consider that there are one or two 'struct uperms_entry' types in this header? Can you give chapter and verse from one of the three C standards (preferably C99 or C11) which indicates whether the following header file has one or two struct uperms_entry types in it?
#ifndef UPERMS_CACHE_INCLUDE
#define UPERMS_CACHE_INCLUDE

typedef struct mutex MT_MUTEX;

typedef struct uperms_cache
{
    MT_MUTEX            *cache_lock;
    int                  processing;
    struct uperms_entry *uperms_list;  // No prior struct uperms_entry
} uperms_cache_t;

typedef struct uperms_entry // Does this define a different struct uperms_entry?
{
    char                 username[32];
    int                  perms;
    struct uperms_entry *next;
} uperms_entry_t;

#endif /* UPERMS_CACHE_INCLUDE */

Adjunct questions:

*

*If there are two types, is there any way to get GCC to report the issue?

*If there are two types, does it ever matter in practice?

(I think the answers are 'yes — strictly there are two types', and then (1) No and (2) No.)
Context: internal code review — I'd like the order of the structures reversed, but I'm not sure whether I'm being completely overly pedantic.
Update:
Clearly, the answer to the initial question is 'there is one struct uperms_entry' and therefore the questions numbered 1 and 2 are moot.  I'm glad I checked before throwing a hissy fit in a code review.
Background thinking
This section was added long after the primary question was resolved.

Here are some extensive but relevant quotes from ISO/IEC 9899:2011:

§6.2.7 Compatible type and composite type
¶1 Two types have compatible type if their types are the same.
  Additional rules for determining whether two types are compatible are
  described in 6.7.2 for type specifiers, in 6.7.3 for type qualifiers,
  and in 6.7.6 for declarators.55) Moreover, two structure,
  union, or enumerated types declared in separate translation units are
  compatible if their tags and members satisfy the following requirements:
  If one is declared with a tag, the other shall be declared with the same
  tag.  If both are completed anywhere within their respective translation
  units, then the following additional requirements apply: there shall be
  a one-to-one correspondence between their members such that each pair of
  corresponding members are declared with compatible types; if one member
  of the pair is declared with an alignment specifier, the other is
  declared with an equivalent alignment specifier; and if one member of
  the pair is declared with a name, the other is declared with the same
  name.  For two structures, corresponding members shall be declared in
  the same order.  For two structures or unions, corresponding bit-fields
  shall have the same widths.  For two enumerations, corresponding members
  shall have the same values.
55) Two types need not be identical to be compatible.
§6.7.2.1 Structure and union specifiers
¶8 The presence of a struct-declaration-list in a
  struct-or-union-specifier declares a new type, within a translation
  unit.  The struct-declaration-list is a sequence of declarations for the
  members of the structure or union.  If the struct-declaration-list does
  not contain any named members, either directly or via an anonymous
  structure or anonymous union, the behavior is undefined.  The type is
  incomplete until immediately after the } that terminates the list, and
  complete thereafter.
§6.7.2.3 Tags
¶4 All declarations of structure, union, or enumerated types that have
  the same scope and use the same tag declare the same type.  Irrespective
  of whether there is a tag or what other declarations of the type are in
  the same translation unit, the type is incomplete129) until
  immediately after the closing brace of the list defining the content,
  and complete thereafter.
¶5 Two declarations of structure, union, or enumerated types which are
  in different scopes or use different tags declare distinct types.  Each
  declaration of a structure, union, or enumerated type which does not
  include a tag declares a distinct type.
¶6 A type specifier of the form
struct-or-union identifieropt { struct-declaration-list }
or
enum identifieropt { enumerator-list }
or
enum identifieropt { enumerator-list , }
declares a structure, union, or enumerated type.  The list defines the
  structure content, union content, or enumeration content.  If an
  identifier is provided,130) the type specifier also declares
  the identifier to be the tag of that type.
¶7 A declaration of the form
struct-or-union identifier ;

specifies a structure or union type and declares the identifier as a
  tag of that type.131)
¶8 If a type specifier of the form
struct-or-union identifier

occurs other than as part of one of the above forms, and no other
  declaration of the identifier as a tag is visible, then it declares an
  incomplete structure or union type, and declares the identifier as the
  tag of that type.131)
¶9 If a type specifier of the form
struct-or-union identifier

or
enum identifier

occurs other than as part of one of the above forms, and a declaration
  of the identifier as a tag is visible, then it specifies the same type
  as that other declaration, and does not redeclare the tag.
¶12 EXAMPLE 2 To illustrate the use of prior declaration of a tag to
  specify a pair of mutually referential structures, the declarations
struct s1 { struct s2 *s2p; /* ... */ }; // D1
struct s2 { struct s1 *s1p; /* ... */ }; // D2

specify a pair of structures that contain pointers to each other.
  Note, however, that if s2 were already declared as a tag in an
  enclosing scope, the declaration D1 would refer to it, not to the tag
  s2 declared in D2.  To eliminate this context sensitivity, the
  declaration
struct s2;

may be inserted ahead of D1.  This declares a new tag s2 in the inner
  scope; the declaration D2 then completes the specification of the new type.
129) An incomplete type may only by used when the size of
  an object of that type is not needed.  It is not needed, for example,
  when a typedef name is declared to be a specifier for a structure or
  union, or when a pointer to or a function returning a structure or union
  is being declared.  (See incomplete types in 6.2.5.)  The specification
  has to be complete before such a function is called or defined.
130) If there is no identifier, the type can, within the
  translation unit, only be referred to by the declaration of which it is
  a part.  Of course, when the declaration is of a typedef name,
  subsequent declarations can make use of that typedef name to declare
  objects having the specified structure, union, or enumerated type.
131) A similar construction with enum does not exist.
§6.7.3 Type qualifiers
¶10 For two qualified types to be compatible, both shall have the
  identically qualified version of a compatible type; the order of
  type qualifiers within a list of specifiers or qualifiers does not
  affect the specified type.

The discussion in §6.7.6 is related to pointer, arrays, and function
declarators and does not really affect structures or unions.

I was aware of Example 2 when I wrote the question.  This is some
thinking out loud about some of what the information above means.
Consider this example, which compiles cleanly:
#include <stdio.h>
struct r1 { int x; };

struct r1;

struct r1 p0;

//struct r1 { int y; };     // Redefinition of struct r1

extern void z(void);

void z(void)
{
    struct r1 p1 = { 23 };
    struct r1;
    //struct r1 p2;         // Storage size of p2 is not known
    struct r2 { struct r1 *rn; int y; };
    struct r1 { struct r2 *rn; int z; };
    struct r2 p = { 0, 1 };
    struct r1 q = { &p, 2 };
    p.rn = &q;
    printf("p.y = %d, q.z = %d\n", p.y, q.z);
    printf("p1.x = %d\n", p1.x);
}

The function illustrates when Example 2 applies, but is not sensible
code.  The declaration of p1 in the function is would be a structure
of the same type as the global variable p0.  Even though its type name
is struct r1, it is of a different (and incompatible) type from the
type of the local variable p.
The redefinition of struct r1 at the global level is not allowed,
regardless of whether the element is named x or y.  The prior
struct r1; is a no-op in this context.
One interesting issue is 'can function z pass p or q to any other
function (call it a)?  The answer is a qualified 'yes', and some of
the constraints are interesting.  (It would also be appalling coding
style to try it, verging on the insane.)  The function must exist in a
separate translation unit (TU).  The function declaration must be inside
function z (because if it is outside the function, its prototype must
refer to the struct r1 defined outside the function, not the struct
r1 defined inside.
In the other TU, a degree of sanity must prevail: the function a must
have the compatible structure types struct r1 and struct r2 visible
in its global scope.
Here's another example, but this one does not compile:
#include <stdio.h>

struct r1;
extern void z(struct r1 *r1p);
extern void y(struct r1 *r1p);

void y(struct r1 *r1p)
{
    struct r2 { struct r1 *rn; int y; };
    struct r1 { struct r2 *rn; int z; };
    struct r2 p = { r1p, 1 };
    struct r1 q = { &p, 2 };
    p.rn = &q;
    printf("p.y = %d, q.z = %d\n", p.y, q.z);
}

void z(struct r1 *r1p)
{
    struct r1
    struct r2 { struct r1 *rn; int y; };
    struct r1 { struct r2 *rn; int z; };
    struct r2 p = { r1p, 1 };
    struct r1 q = { &p, 2 };
    p.rn = &q;
    printf("p.y = %d, q.z = %d\n", p.y, q.z);
}

The warnings from GCC 4.7.1 on Mac OS X 10.7.4 are:
structs3.c: In function 'y':
structs3.c:13:10: warning: assignment from incompatible pointer type [enabled by default]
structs3.c: In function 'z':
structs3.c:22:12: warning: initialization from incompatible pointer type [enabled by default]
structs3.c:22:12: warning: (near initialization for 'p.rn') [enabled by default]

Lines 13 is the assignment p.rn = &q; in function y and line 23 is
the attempt to define and initialize struct r2 p in function z.
This demonstrates that within the functions, the rn element of struct
r2 is a pointer to the incomplete type struct r1 declared at the
global scope.  Adding a struct r1; as the first line of code inside
the function would allow the code to compile, but the initialization
referencing r1p->rn is derefencing a pointer to an incomplete type
again (the incomplete type is the struct r1 declared at the global
scope).
The function declarations and the preceding struct r1; line could
appear in a header as an opaque type.  The list of supporting functions
is incomplete; there'd need to be a way to get a pointer to an
initialized struct r1 to pass into the functions, but that's a detail.
To make the code work in this second TU, the types for struct r1 must
be complete in the global scope before the functions are defined, and
because of the recursive references, `struct r21 must also be complete.
#include <stdio.h>

/* Logically in a 3-line header file */
struct r1;
extern void z(struct r1 *r1p);
extern void y(struct r1 *r1p);

/* Details private to this TU */
struct r2 { struct r1 *rn; int y; };
struct r1 { struct r2 *rn; int z; };

void y(struct r1 *r1p)
{
    struct r2 p = { r1p,     1 };
    struct r1 q = { r1p->rn, 2 };
    p.rn = &q;
    printf("p.y = %d, q.z = %d\n", p.y, q.z);
}

void z(struct r1 *r1p)
{
    struct r2 p = { r1p,     1 };
    struct r1 q = { r1p->rn, 2 };
    p.rn = &q;
    printf("p.y = %d, q.z = %d\n", p.y, q.z);
}

This process of defining the structures in the implementation file while
leaving the type incomplete in the public header file can be repeated in
multiple implementation files if necessary, though if more than one TU
uses the complete structure definition, it would be better to place the
definitions in a private header file shared only between the files that
implement the structures.  I note that it does not matter whether the
private header precedes or follows the public header.
Maybe this was all obvious to you already.  I'd not needed to think it
through in this level of detail before.

A: In C1, they refer to the same type.  C99 §6.2.1 defines the scopes that exist:

2 For each different entity that an identifier designates, the
  identifier is visible (i.e., can be used) only within a region of
  program text called its scope. Different entities designated by the
  same identifier either have different scopes, or are in different name
  spaces. There are four kinds of scopes: function, file, block, and
  function prototype. (A function prototype is a declaration of a
  function that declares the types of its parameters.)

Function scope only applies to labels (as explicitly stated later in the same section).  Block scope applies to identifiers declared in blocks - blocks are created by compound-statements, iteration-statements and selection-statements (and not by struct declarations or compound initialisers).  Function prototype scope applies to identifiers declared within a function prototype declaration.
None of these apply to your example - all of the mentions of struct uperms_entry in your example are at file scope.
C99 §6.7.2.3 says:

1 All declarations of structure, union, or enumerated types that have
  the same scope and use the same tag declare the same type. The type is incomplete until the closing brace of the list defining the content, and complete thereafter.

This is pretty clear, and applies to your case.
Paragraph 8 of that section applies to the first mention of struct uperms_entry:

8 If a type specifier of the form struct-or-union identifier occurs
  other than as part of one of the above forms, and no other declaration
  of the identifier as a tag is visible, then it declares an incomplete
  structure or union type, and declares the identifier as the tag of
  that type.

So at that point it's declared as an incomplete type at file scope.  Paragraph 6 applies to the second mention of struct uperms_entry:

6 A type specifier of the form struct-or-union
  identifieropt { struct-declaration-list } or enum
  identifier { enumerator-list } or enum identifier { enumerator-list
  , } declares a structure, union, or enumerated type. The list defines
  the structure content, union content, or enumeration content. If an
  identifier is provided, the type specifier also declares the
  identifier to be the tag of that type.

So after the } at the end of that typedef declaration, it's now a complete type.
The adjunct questions are moot.

1. I believe that this is not the case in C++, however.

A: Well, C99 6.2.5.22 says

... A structure or union type of unknown content (as described in
  6.7.2.3) is an incomplete type. It is completed, for all declarations of that type, by declaring the same structure or union tag with its
  defining content later in the same scope.

Which would mean they're the same type for your case.


text:
Q: 2 different listed elements without the same members in TypeScript I just want to create data structure which I can use with syntax prediction in my IntellIJ IDE.
I need to create 2 or more structures which will have name the same as their value, but the names can't be the same on that 2 structures. And I need to know that on the TypeScript compiling time.
E.g
I was wondering about using Enums :
enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT",
}

But I need to somehow prevent of the duplicate of the members name of the all occurences of enums or "another, better solution structure" in that file.
Like :
enum Direction {
        Up = "UP",
        Down = "DOWN",
        Left = "LEFT",
        Right = "RIGHT",
}

enum HorizontalDirection {
    Left = "LEFT",
    Right = "RIGHT",
}

And after that I want to get an Error that the 'Left' and 'Right' field already exist with keeping separation of that structure. (I can't create one class/ enum with all that fields).
Like extending Enums but not overriding old values but gives an error.
Maybe there is a way to do so ?


text:
Q: Javascript Uncaught TypeError: Cannot read property '0' of undefined using a for loop to search an array I am working on a project where I make a table in HTMl and than draw the table in javascript using a 2D Array. Then I made a function that finds a * and makes them into letters where other * are touching it. Than once that is done is changes the letter to B and finds the next * in the array and makes all * touching it into B and so on. My problem is that my loop that finds all the * in the array comes up with an error. Any suggestions?
 var organismArray = [
    ["*","*","_"],
    ["-","_","*"],
    ["-","*","*"]
];

function drawOrganism() {
    var letter = 'A';
    var Organisms = 0;
    for (var col = 0; col < 2; col++) {
        for (var row = 0; row < 2; row++) {
            if (organismArray[col][row] == "*") { // This is where the Error occurs.
                organismArray = howManyOrganisms(col, row, letter);
                letter++;
                Organisms++;

            }`
        }
    }
    console.log(organismArray);
}
function howManyOrganisms(col,row,letter) {
    organismArray[col][row] = letter;

    if (col + 1 < organismArray.length) {
        if (organismArray[col + 1][row] == "*") {
            howManyOrganisms(col + 1, row, letter);
        }
    }
    if (col - 1 >= 0) {
        if (organismArray[col - 1][row] == "*") {
            howManyOrganisms(col-1, row, letter);
        }
    }
    if (row - 1 >= 0) {
        if (organismArray[col][row - 1] == "*") {
            howManyOrganisms(col, row - 1, letter);
        }
    }
    if (row + 1 < organismArray[col].length) {
        if (organismArray[col][row + 1] == "*") {
            howManyOrganisms(col, row + 1, letter);
        }
    }
}

A: Inside the for loops, if the condition is met, you re-assign the result of a void function to the original organism array.
if (organismArray[col][row] == "*") {
  organismArray = howManyOrganisms(col, row, letter);
}

The 'howManyOrganisms' function never returns anything, therefore, you're wiping the original organismArray.
So maybe try this:
if (organismArray[col][row] == "*") {
   howManyOrganisms(col, row, letter);
}

Hope this helps!

A: You are missing the return keyword in the howManyOrganisms() function, therefore this line:
organismArray = howManyOrganisms(col, row, letter);

assigns undefined to the organismArray. You have to add return to each of the recurrent calls and also at the end of the howManyOrganisms() function because it not always will end up in one of the ifs. Try this one:

 var organismArray = [
    ["*","*","_"],
    ["-","_","*"],
    ["-","*","*"]
];

drawOrganism();

function drawOrganism() {
    var letter = 'A';
    var Organisms = 0;
    for (var col = 0; col < 2; col++) {
        for (var row = 0; row < 2; row++) {
            if (organismArray[col][row] == "*") {
                organismArray = howManyOrganisms(col, row, letter);
                letter++;
                Organisms++;
            }
        }
    }
    console.log(organismArray);
}
function howManyOrganisms(col,row,letter) {
    console.log("workig");
    organismArray[col][row] = letter;

    if (col + 1 < organismArray.length) {
        if (organismArray[col + 1][row] == "*") {
            return howManyOrganisms(col + 1, row, letter); // return here
        }
    }
    if (col - 1 >= 0) {
        if (organismArray[col - 1][row] == "*") {
            return howManyOrganisms(col-1, row, letter); // return here
        }
    }
    if (row - 1 >= 0) {
        if (organismArray[col][row - 1] == "*") {
            return howManyOrganisms(col, row - 1, letter); // return here
        }
    }
    if (row + 1 < organismArray[col].length) {
        if (organismArray[col][row + 1] == "*") {
            return howManyOrganisms(col, row + 1, letter); // return here
        }
    }

    return organismArray; // and return here
}


text:
Q: linux + LVM + extent small disk by add another disk we have Linux machine redhat 7.2 LVM disk
disk -sdd with only 2G
we want to extend the size of /data to 20G by adding another disk - sde
/dev/sdd            2.0G  9.2M  1.9G   1% /data

expected results
/dev/sdd            20.0G  9.2M  1.9G   1% /data

what is the procedure that explain how to add another disk and join the new disk size to "sdd" ?

A: It does not look like your /dev/sdd is a member of LVM Group.
You cannot just extend your device. Expected result is not able to be done.
By the subject, I can assume, you would like to use LVM to extend /dev/sdd and keep your data from /dev/sdd on /dev/sdd and /dev/sde at /data mount-point.
If so, the procedure looks like that:

*

*Do reliable the backup of /data.

*Create physical-volume from /dev/sdd. (It will wipe-out your data from /dev/sdd)

*Create physical-volume from /dev/sde (It will wipe-out your data from /dev/sde)

*Create volume-group that consists of two PVs: /dev/sdd and /dev/sde.

*Create linear logical-volume, create filesystem on it, mount it on /data.

*Restore your backup.

References:

*

*https://wiki.archlinux.org/index.php/LVM

*https://linux.die.net/man/8/lvm


text:
Q: Xamarin Android Calendar Events I'm trying to implement calendar events in my app, and I was following example from xamarin site and their calander demo but it's not working. I can launch application and when I press button to add event nothing happens.Here is my code does anyone knows why it's not working.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Provider;
using Java.Util;

namespace Bingo
{
    [Activity(Label = "EventListActivity")]
     public class EventListActivity : ListActivity
  {
    int _calId;

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        SetContentView (Resource.Layout.EventList);

        _calId = Intent.GetIntExtra ("calId", -1);

        ListEvents ();

        InitAddEvent ();
    }

    void ListEvents ()
    {
        var eventsUri = CalendarContract.Events.ContentUri;

        string[] eventsProjection = {
            CalendarContract.Events.InterfaceConsts.Id,
            CalendarContract.Events.InterfaceConsts.Title,
            CalendarContract.Events.InterfaceConsts.Dtstart
        };

        var cursor = ManagedQuery (eventsUri, eventsProjection,
            String.Format ("calendar_id={0}", _calId), null, "dtstart ASC");

        string[] sourceColumns = {
            CalendarContract.Events.InterfaceConsts.Title,
            CalendarContract.Events.InterfaceConsts.Dtstart
        };

        int[] targetResources = { Resource.Id.eventTitle, Resource.Id.eventStartDate };

        var adapter = new SimpleCursorAdapter (this, Resource.Layout.EventListItem,
            cursor, sourceColumns, targetResources);

        adapter.ViewBinder = new ViewBinder ();

        ListAdapter = adapter;

        ListView.ItemClick += (sender, e) => {
            int i = (e as AdapterView.ItemClickEventArgs).Position;

            cursor.MoveToPosition(i);
            int eventId = cursor.GetInt (cursor.GetColumnIndex (eventsProjection [0]));
            var uri = ContentUris.WithAppendedId(CalendarContract.Events.ContentUri, eventId);
            var intent = new Intent(Intent.ActionView, uri);
            StartActivity(intent);
        };
    }

    void InitAddEvent ()
    {
        var addSampleEvent = FindViewById<Button> (Resource.Id.addSampleEvent);

        addSampleEvent.Click += (sender, e) => {
            // Create Event code
            ContentValues eventValues = new ContentValues ();
            eventValues.Put (CalendarContract.Events.InterfaceConsts.CalendarId, _calId);
            eventValues.Put (CalendarContract.Events.InterfaceConsts.Title, "Test Event from M4A");
            eventValues.Put (CalendarContract.Events.InterfaceConsts.Description, "This is an event created from Mono for Android");
            eventValues.Put (CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS (2015, 12, 15, 10, 0));
            eventValues.Put (CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS (2015, 12, 15, 11, 0));

            eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC");
            eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "UTC");

            var uri = ContentResolver.Insert (CalendarContract.Events.ContentUri, eventValues);
            Console.WriteLine ("Uri for new event: {0}", uri);
        };
    }

    class ViewBinder : Java.Lang.Object, SimpleCursorAdapter.IViewBinder
    {
        public bool SetViewValue (View view, Android.Database.ICursor cursor, int columnIndex)
        {
            if (columnIndex == 2) {
                long ms = cursor.GetLong (columnIndex);

                DateTime date =
                    new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds (ms).ToLocalTime ();

                TextView textView = (TextView)view;
                textView.Text = date.ToLongDateString ();

                return true;
            }
            return false;
        }
    }

    long GetDateTimeMS (int yr, int month, int day, int hr, int min)
    {
        Calendar c = Calendar.GetInstance (Java.Util.TimeZone.Default);

        c.Set (Java.Util.CalendarField.DayOfMonth, 15);
        c.Set (Java.Util.CalendarField.HourOfDay, hr);
        c.Set (Java.Util.CalendarField.Minute, min);
        c.Set (Java.Util.CalendarField.Month, Calendar.December);
        c.Set (Java.Util.CalendarField.Year, 2015);

        return c.TimeInMillis;
    }

}

}

A: I know this is a late entry but I just went through this on my xamarin forms app and had to cobble tips and guesses from all over to do what seems like a simple task.  My example is slightly different as I'm doing a dependency service but I think it should help the next guy.
This should pop the create event panel for your user and let them tweak the title and stuff before they hit save.  Also you shouldn't need the read/write calendar permissions in your manifest for this since we're writing from the calendar app.
Also this works in my emulator. API 24
 [assembly: Dependency(typeof(CalendarAppointmentService))]
namespace Foo.Droid.Services
{
    [Activity(Label = "CalendarAppointment")]
    public class CalendarAppointmentService : ICalendarAppointmentService
    {
        private readonly static DateTime referenceDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        public CalendarAppointmentService()
        {

        }

        public async Task<bool> AddAppointment(AddAppointmentModel model)
        {
            try
            {
                Intent eventValues = new Intent(Intent.ActionInsert);
                eventValues.SetData(CalendarContract.Events.ContentUri);
                eventValues.AddFlags(ActivityFlags.NewTask);
                eventValues.PutExtra(CalendarContract.Events.InterfaceConsts.Title, model.Title);
                eventValues.PutExtra(CalendarContract.Events.InterfaceConsts.Description, model.Description);
                eventValues.PutExtra(CalendarContract.ExtraEventBeginTime, GetDateAsAndroidMS(model.StartDateTimeUTC));
                eventValues.PutExtra(CalendarContract.ExtraEventEndTime, GetDateAsAndroidMS(model.EndDateTimeUTC));
                eventValues.PutExtra(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC");
                eventValues.PutExtra(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "UTC");
                eventValues.PutExtra(CalendarContract.Events.InterfaceConsts.EventLocation, model.Location);
                Android.App.Application.Context.StartActivity(eventValues);

                return await Task.FromResult(true);
            }
            catch (Exception)
            {   }
            return await Task.FromResult(false);
        }

        /// <summary>
        /// Converts a System.DateTime to an Android-expected long of milliseconds since 1970.
        /// </summary>
        /// <returns>The date as Android long value.</returns>
        /// <param name="date">Source DateTime.</param>
        public static long GetDateAsAndroidMS(DateTime date)
        {
            return (long)(date.ToUniversalTime() - referenceDate).TotalMilliseconds;
        }
    }
}

A: Make sure you have the READ_CALENDAR permission set in the Android Manifest. Described here.

A: I was facing the same problem but I resolved it, first check in manifest file for required permissions. Then, don't use your emulator to sync with the calendar, use an actual mobile device and then try syncing and it'll work perfectly.


text:
Q: How to set proxy AUTHENTICATION username:password using Python/Selenium I am using:

*

*Selenium 4

*python 3.7

*Firefox webdriver

I need to verify the username and password for my current project. I've been working day and night for days and I can't solve this problem. I've found a few extension on the internet, but it's from '13 year and I guess that's why it doesn't work. You can also see other methods I've tried below.
But doesn't work, because Proxy Authentication is not working anymore due to the Selenium bug..
alert_popup = browser.switch_to_alert()
    alert_popup.send_keys(
        "{username}{tab}{password}{tab}".format(
            username=proxy_username, tab=Keys.TAB, password=proxy_password
    )
)
alert_popup.accept()

I wanted to create a profile and save the proxy information manually and start selenium with that profile. However, firefox does not allow user name and password to be entered manually.

A: To use proxies with auth in python selenium you can use seleniumwire.
Fistly, install it with pip install selenium-wire
Then import webdriver from seleniumwire instead selenium

Check the original Answer here

    from seleniumwire import webdriver
options = {
    'proxy': {
        'http': 'http://username:password@host:port',
        'https': 'https://username:password@host:port',
        'no_proxy': 'localhost,127.0.0.1' # excludes
    }
}
browser = webdriver.Chrome(path_to_driver, seleniumwire_options=options)


text:
Q: SAS--How to identify the event occurred in three consecutive years? I am trying to identify traders who place transactions in the same month in each of three consecutive years in one company. Once a trader meets the criteria, these three transactions and all his subsequent transactions in that same month in that company should be identified.
Assume I have a sample data below.
data have;
input ID  STOCK   trandate $12.;
datalines;
1    1   10/15/2009
1    1   01/01/2010
1    1   01/10/2011
1    1   01/15/2012
1    1   01/01/2013
1    2   01/30/2011
1    2   01/30/2012
1    2   01/30/2012
1    2   01/30/2013
1    2   01/30/2014
1    2   01/30/2015
2    1   01/20/2010
2    1   01/15/2011
2    1   01/16/2012
2    1   02/01/2013
2    2   02/01/2010
2    2   02/10/2011
2    2   02/10/2012
2    2   02/10/2013
2    2   02/10/2014
2    2   01/10/2015
;
run;

What I need:
ID Stock  trandate type
1    1   10/15/2009 0
1    1   01/01/2010 1
1    1   01/10/2011 1
1    1   01/15/2012 1
1    1   01/01/2013 1
1    2   01/30/2011 1
1    2   01/30/2012 1
1    2   01/30/2012 1
1    2   01/30/2013 1
1    2   01/30/2014 1
1    2   01/30/2015 1
2    1   01/20/2010 0
2    1   01/15/2011 0
2    1   01/16/2012 0
2    1   02/01/2013 0
2    2   02/01/2010 1
2    2   02/10/2011 1
2    2   02/10/2012 1
2    2   02/10/2013 1
2    2   02/10/2014 1
2    2   01/10/2015 0

I used following code to achieve this:
proc sort data=have;
by id stock trandate;
run;

data have;
set have;
month=month(trandate);
year=year(trandate);
run;

proc sort data=have;
by  id stock month year;
run;

data have;
set have;
by personid secid month year;

  rungroup + (first.month or not first.month and year - lag(year) > 1);

run;

data temp;
  do index = 1 by 1 until (last.rungroup);
    set have;
    by rungroup;

    * distinct number of years in rungroup;
    years_runlength = sum (years_runlength, first.rungroup or year ne lag(year));
  end;

  do index = 1 to index;
    set have;
    if years_runlength >=4 then output;
  end;
run;

The above codes are used to identify traders with transactions in the past three consecutive years. Since I also need the subsequent transactions of these traders. The following codes are further applied.
proc sort data=temp;
by personid  secid   rungroup;
run;

data temp;
set temp;
by  rungroup;
if  first.rungroup then fyear=year;
run;

data temp(drop=fyear rename=(Locf=fyear));
 do until (last.personid);
   set  temp;
   by id stock;
   locf=coalesce(fyear,locf);
   output;
 end;
run;

data temp;
set temp;
by rungroup;
if first.rungroup then fmonth=month;
run;

data temp;
set temp;
gap=year-fyear;
run;

proc means data=temp;
var gap;
run;

data temp;
set temp;
if gap=3 then type2=1;
type1=1;
run;

The above codes are used to mark the first transaction after the three consecutive years. In this context, when the identified transactions combine with the original dataset, all transactions in that same month below the marked transaction could be identified. Thereby, I can achieve the objective that "these three transactions and all his subsequent transactions in that same month in that company should be identified". The following codes are used to achieve this.
proc sort data=have;
by id stock   rungroup;
run;
proc sort data=temp;
by id stock   rungroup;
run;

data combine;
merge have temp;
by id stock   rungroup;
run;

data combine;
set combine;
month=month(trandate);
run;

data combine1 (drop=fmonth rename=(Locf=fmonth));
 do until (last.personid );
   set  combine;
   by id stock;
   locf=coalesce(fmonth,locf);
   output;
 end;
run;

data combine2 (drop=type2 rename=(Locf=type2));
 do until (last.personid);
   set  combine1;
   by id stock;
   locf=coalesce(type2,locf);
   output;
 end;
run;

    data combine2;
    set combine2;
    if month^=fmonth then type2=.;
    run;

data combine2;
set combine2;
if type1=1 or type2=1 then type=1;
else type=0;
run;

I tried these codes, the results looks right, but I cannot 100% sure. Additionally, as you can see, my codes are relative long and complex. So could anyone give me some suggestions about the code?

A: Here is a bit of brute force way.  For this example I just limited it to the years 2009 to 2015 in your example, but you could just expand the pattern to allow more years. You could use macro logic to generate the wallpaper aspects of the code.
First generate an array you can index by YEAR and MONTH and populate the variables with 1 when the month it represents has a trade.  Then check if the series of values for the same month across the years ever has three 1's in a row.  You can use two DOW loops to process the data. The first one populates the array and the second tests the array and sets the new flag variable.
data want ;
 do until(last.stock) ;
   set have ;
   by id stock;
   array months [1:12,2009:2015]
     m1y2009-m1y2015 m2y2009-m2y2015 m3y2009-m3y2015 m4y2009-m4y2015
     m5y2009-m5y2015 m6y2009-m6y2015 m7y2009-m7y2015 m8y2009-m8y2015
     m9y2009-m9y2015 m10y2009-m10y2015 m11y2009-m11y2015 m12y2009-m12y2015
   ;
   months[month(trandate),year(trandate)]=1;
 end;
 do until(last.stock);
   set have;
   by id stock;
   select (month(trandate));
     when (1) flag=0 ne index(cats(of m1y:),'111');
     when (2) flag=0 ne index(cats(of m2y:),'111');
     when (3) flag=0 ne index(cats(of m3y:),'111');
     when (4) flag=0 ne index(cats(of m4y:),'111');
     when (5) flag=0 ne index(cats(of m5y:),'111');
     when (6) flag=0 ne index(cats(of m6y:),'111');
     when (7) flag=0 ne index(cats(of m7y:),'111');
     when (8) flag=0 ne index(cats(of m8y:),'111');
     when (9) flag=0 ne index(cats(of m9y:),'111');
     when (10) flag=0 ne index(cats(of m10y:),'111');
     when (11) flag=0 ne index(cats(of m11y:),'111');
     when (12) flag=0 ne index(cats(of m12y:),'111');
     otherwise ;
   end;
   output;
  end;
  drop m: ;
run;


text:
Q: slime-fancy not loading with emacs sbcl slime windows configuration I have slime with sbcl working in emacs 24.1 but can not get a slime repl to open.
I can use M-x slime to make a connection to sbcl in a inferior-lisp buffer but I can not invoke the slime-repl or get a nice lisp auto-indent when editing lisp files even though I am loading the slime-fancy contrib in .emacs.  I don't get any error messages during start-up.
When I try M-x slime-repl I get [No match].
my .emacs file:
(setq inferior-lisp-program "sbcl")
(add-to-list 'load-path "c:/home/bin/emacs/site-lisp/slime/")
(require 'slime)
(require 'slime-autoloads)
(slime-setup '(slime-fancy))

I used this method for the installation:
http://www.pchristensen.com/blog/articles/installing-sbcl-emacs-and-slime-on-windows-xp
I have noticed a pattern that almost everything I try with Python and Clojure works as described and almost nothing I try related to common lisp works.  I have also tried cusp with eclipse.  I am willing to try yet another approach if there is something more recent for common lisp in windows.

A: After playing with Sujoy's answer and trimming it down to get it to work, I realized my original problem was caused by the (require 'slime) statement. The following .emacs file gets the slime repl to open as expected.
(setq inferior-lisp-program "sbcl")
(require 'slime-autoloads)
(slime-setup '(slime-fancy))

A: Only 'slime-fancy will not setup the REPL. Try the below snippet. Put it in a buffer and eval.
Of course, you do not need to setup the hyperspec root as well, but that helps a lot :)
EDIT: missed out on the autoloads I am using, so here's the full config.
the keybinding (using minor-mode keymap, global mapping can be used just as easily)
(define-key my-keys-map (kbd "<f5>") 'slime)

the autoloads
;; slime mode
(autoload 'slime "my-slime" "Slime mode." t)
(autoload 'slime-connect "my-slime" "Slime mode." t)

Here's my-slime.el
(provide 'my-slime)
(eval-after-load "slime"
     (setq slime-lisp-implementations
     (slime-setup '(slime-asdf
                    slime-autodoc
                    slime-editing-commands
                    slime-fancy
                    slime-fontifying-fu
                    slime-fuzzy
                    slime-indentation
                    slime-mdot-fu
                    slime-package-fu
                    slime-references
                    slime-repl
                    slime-sbcl-exts
                    slime-scratch
                    slime-xref-browser))
     (slime-autodoc-mode)
     (setq slime-complete-symbol*-fancy t
           slime-complete-symbol-function 'slime-fuzzy-complete-symbol
           slime-when-complete-filename-expand t
           slime-truncate-lines nil
           slime-autodoc-use-multiline-p t)
     (add-hook 'lisp-mode-hook (lambda () (slime-mode t)))))
(require 'slime)


text:
Q: Make horizontal lines with pandas yearly data? I have a pandas object with yearly averages data in this form:
DatetimeIndex(['2005-12-31', '2006-12-31', '2007-12-31', '2008-12-31',
               '2009-12-31', '2010-12-31', '2011-12-31'],
              dtype='datetime64[ns]', freq='A-DEC')
2005-12-31    3.347463
2006-12-31    3.042220
2007-12-31    3.296574
2008-12-31    3.082333
2009-12-31    2.471380
2010-12-31    2.337974
2011-12-31    2.083004

I would like to draw horizontal lines from beginning of the year till the end of the year with the values currently associated to the last day of the year. Currently, when I plot this pandas object, I get linear interpolation between the points at the end of the year. I have tried adding indexes with:
new_index= ['2005', '2006', '2007', '2008','2009', '2010', '2011']
df_year.reindex(new_index)

which result in the same graph. Or adding the first day of each year (not good for automation though) with:
z=datetime.strptime('01-01-2005', '%d-%m-%Y')
indx.append(pd.Index([z]))
df_year.set_value(z,2)

which result in:
DatetimeIndex(['2005-12-31', '2006-12-31', '2007-12-31', '2008-12-31',
               '2009-12-31', '2010-12-31', '2011-12-31', '2005-01-01'],
              dtype='datetime64[ns]', freq=None)
2005-12-31    3.347463
2006-12-31    3.042220
2007-12-31    3.296574
2008-12-31    3.082333
2009-12-31    2.471380
2010-12-31    2.337974
2011-12-31    2.083004
2005-01-01    2.000000

However, it seems like it cannot detect that that date is before 2005-12-31 so its just draw a horizontal line from 2005 till 2011. I would really appreciate if you can help me.
Unfortunately, I am not able to upload the graphs, since I am working on a different server and I am not able to save images.
Thank you.
Edition:
Here is the code I used:
plt.figure()
plt.plot(df_month.index,  df_month, 'k')
plt.plot(df_year.index,  df_year, 'g')
plt.show()

A: If I understood correctly you want a bar plot or steps like plit for you values using dates as x axis.
DataFrame
If we set the DataFrameas follows:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame([["2005-12-31", 3.347463],["2006-12-31", 3.042220],["2007-12-31", 3.296574],["2008-12-31", 3.082333],["2009-12-31", 2.471380],["2010-12-31", 2.337974],["2011-12-31", 2.083004]])
df.columns = ["date", "value"]
df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d")
df = df.set_index(["date"])

Your DataFrame would be:
>>> df
               value
date
2005-12-31  3.347463
2006-12-31  3.042220
2007-12-31  3.296574
2008-12-31  3.082333
2009-12-31  2.471380
2010-12-31  2.337974
2011-12-31  2.083004

Note that we set the date column as index.
Using plot.bar
You can use plot.bar function. If it's not available due to pandas version you can try plot(kind="bar") instead. Below code would plot and show the desired graph:
df.plot.bar(width=1,fill=False)
plt.tight_layout()
plt.show()

And the output graph would result into:

Note that using width as 1 we get the bars with whole width. width by default is 0.5.
Using plot with steps-mid as linetyle
Otherwise you can use plot with steps-mid as linestyle with below code:
df.plot(ls="steps-mid")
plt.show()

You get as graph:


text:
Q: Set up a definite integral for the volume obtained by rotating the region between the curve $y^{2}=x$ and $y^{2}=2(x-1)$ about $y=3$ So I have a similar question from a bit before:

Set up a definite integral that represents the volume obtained by rotating the region between the curve $y^{2}=x$ and $y^{2}=2(x-1)$ about the line $y=3$

I get $\int\limits\limits_{-\sqrt{2}}^{\sqrt{2}} \pi((\frac{ (3-y)^2+2 }{ 2 })^{2})-\ (3-y)^4)dy$
Is that right?

A: Using the method of washers, the washers would be perpendicular to the axis of rotation, thus the integration would be performed along the $x$-axis.  However, because a line perpendicular to the axis of rotation (i.e. parallel to the $y$-axis) can intersect the region of interest in two disjoint intervals, we see that such an approach is not optimal.

Instead, the method of cylindrical shells is better suited.  In such a case, the integration would be performed along the $y$-axis, since the shells are nested within each other such that they all share the line $y = 3$ as the common axis.  We also note that for a representative shell, the "height" is measured as the horizontal distance between the two parabolic arcs and that horizontal lines never intersect the region of interest along more than one contiguous interval.

To this end, we first solve for the $y$-coordinates for which the parabolas intersect:  $$y^2 = x, \quad y^2 = 2(x-1)$$ implies that $(x,y) = (2, \pm \sqrt{2})$.  Then for a representative shell of radius $r(y) = 3-y$, the height of such a shell is $$h(y) = (y^2/2 + 1) - y^2 = 1 - y^2/2,$$ and the differential volume is $$dV = 2\pi r(y) h(y) \, dy = 2\pi (3-y)(1 - y^2/2) \, dy.$$  The total volume is then $$V = \int_{y=-\sqrt{2}}^{\sqrt{2}} \, dV = 2\pi \int_{y=-\sqrt{2}}^{\sqrt{2}} (3-y)(1-y^2/2) \, dy.$$

If we are interested in the volume of the same region if rotated about the $y$-axis (i.e. $x = 0$), then the method of washers would apply, but now the outer radius corresponds to the curve $y^2 = 2(x-1)$ and the inner corresponds to the curve $y^2 = x$, even though the cross-sectional intervals are the same as in the previous computation.  Thus the differential volume of a representative washer is $$dV = \pi((y^2/2 + 1)^2 - y^4) \, dy,$$ and the volume is $$V = \int_{y=-\sqrt{2}}^{\sqrt{2}} dV = \pi \int_{y=-\sqrt{2}}^{\sqrt{2}} -\frac{3y^4}{4} + y^2 + 1 \, dy.$$

A: OK, you must really sketch your region before deciding which method to use.  Sometimes it doesn't matter and sometimes one is much easier than the other.
In this case, without changing the coordinate plane (you could simply switch the $x$ and $y$ coordinate in this problem, then revolve around $x = 3$ and this this would be a very easy problem to sketch in what you normally think of as the $xy$-plane).
It helps to realize that the $y^2 = x$ is a "sideways" parabola.  It helps even further to realize that $y^2 = 2(x -1)$ is also a sidways parabola but shifted and stretched/compressed:

The sketch will show that the shell method is most appropriate here.  The washer method would work but it would require breaking the region into (at least) two parts.
Once the region is sketched, it's a matter of finding $r$, $h$, and $dr$.  $dr$ is easy, it's clearly $dy$.  $r$ is also fairly simple, it's clearly $3 - y$--which is nice since we have $dy$, this is already in the form we need.  Finally $h = \Delta x = x_R-x_L$.  $x_R$ is given by $y^2 = 2(x-1)$ and $x_L$ is given by $y^2 = x$ therefore:
$$
x_L = y^2
$$
and
$$
y^2 = 2(x_R - 1) \\
x_R = \frac{y^2}{2} + 1
$$
Therefore:
\begin{align}
\Delta x =&\ x_R - x_L\\
 =&\ \frac{y^2}{2} + 1 - y^2 \\
=&\ -\frac{y^2}{2} + 1
\end{align}
Summarizing this gives:
$$
r = 3-y \\
h = -\frac{y^2}{2} + 1 \\
dr = dy \\
dV = 2\pi rh dr = 2\pi (3-y)\left(1-\frac{y^2}{2}\right)dy
$$
Finally we must find the limits of integration what $y$ values does this region range from?  Simple, it's where $\Delta x = 0$:
$$
1 - \frac{y^2}{2} = 0 \\
y^2 = 2 \rightarrow y = \pm \sqrt{2}
$$
So finally the integral should be:
$$
2\pi\int\limits_{-\sqrt{2}}^{\sqrt{2}}\left((3-y)\left(1-\frac{y^2}{2}\right)\right)dy
$$

A: I wrote the following just to offer an alternative. Yet please do observe that at the end I get an extra $\;-2\pi\;$ instead of the $\;8\sqrt2\pi\;$ that you get doing the calculations as in the other answers. I'd like to know where I did go wrong:
Since the plane region that is going to be revolved about a line parallel to the $\;x\,-$ axis is symmetric with respect to this axis, I'd rather have the region revolved about the line $\;y=-3\;$ .
Thus, I can revolve the region $\;0\le x\le1\,- $ axis, with the functions:
$$\begin{cases}\text{Above:}\;\;y_1=\sqrt x+3\\{}\\\text{Below:}\;\;y_2=-\sqrt x+3\end{cases}\;\;,\;\;0\le x\le1\implies V_0=\pi\int_0^1(y_1^2-y_2^2)dx\implies$$
$$V_0=\pi\int_0^112\sqrt x\;dx=12\pi\cdot\frac23\cdot1^{3/2}=8\pi$$
and now the region $\;1\le x\le2\;$ , with the sum of the volumes for the functions:
$$V_1:\;y\ge 0\implies\;\begin{cases}\text{Above:}\;\;y_1=\sqrt x+3\\{}\\\text{Below:}\;\;y_2=\sqrt{2x-2}+3\end{cases}\;\;,\;\;1\le x\le2\implies V_1=\pi\int_0^1(y_1^2-y_2^2)dx$$
$$\implies V_1=\pi\int_1^2\left[-x+6\left(\sqrt x-\sqrt{2x-2}\right)\right]dx=$$
$$=\pi\left(\left.-\frac12x^2\right|_1^2+6\left(\left.\frac23x^{3/2}\right|_1^2-\left.\frac12\frac23(2x-2)^{3/2}\right|_1^2\right)\right)=$$
$$=\pi\left(-\frac32+6\left(\frac23(2\sqrt2-1)-\frac13(2\sqrt2-0)\right)\right)=\pi\left(-\frac32+4\sqrt2-4\right)=\left(4\sqrt2-\frac{11}2\right)\pi$$
and
$$V_2:\;y\le 0\implies\;\begin{cases}\text{Above:}\;\;y_1=-\sqrt{2x-2}+3\\{}\\\text{Below:}\;\;y_2=-\sqrt x+3\end{cases}\;,\;1\le x\le2\implies V_2=\pi\int_0^1(y_1^2-y_2^2)dx$$
$$\implies V_2=\pi\int_1^2\left[x-2+6\left(\sqrt x-\sqrt{2x-2}\right)\right]dx=$$
$$\pi\left[\left.\frac12x^2\right|_1^2-2+6\left(\left.\frac23x^{3/2}\right|_1^2-\left.\frac13(2x-2)^{3/2}\right|_1^2\right)\right]=$$
$$=\pi\left(\frac32-2+6\left(\frac23(2\sqrt2-1)-\frac13(2\sqrt2-0)\right)\right)=$$
$$=\pi\left(-\frac12+4\sqrt2-4\right)=\left(4\sqrt2-\frac92\right)\pi$$
so the final volume is
$$V=V_0+V_1+V_2=\left(8\left(1+\sqrt2\right)-10\right)\pi=\left(8\sqrt2-2\right)\pi$$

A: Rotating about the $y=3$
$$V=\pi\int^{2}_{0} ((3-\sqrt x)^2-(3-\sqrt{2x-1})^2)dx$$

A: Using the shell method,
$\hspace{.2 in}\displaystyle V=\int_{-\sqrt{2}}^{\sqrt{2}}2\pi r(y) h(y)dy=\color{blue}{\int_{-\sqrt{2}}^{\sqrt{2}}2\pi (3-y)\left(\left(\frac{y^2}{2}+1\right)-y^2\right)dy}$

$\;\;\;$Alternate answer:  (disc method)
$\hspace{.2 in}\displaystyle V=\color{green}{\int_0^{2}\pi\left((3+\sqrt{x})^2-(3-\sqrt{x})^2\right)dx-\int_1^{2}\pi\left(\left(3+\sqrt{2(x-1)}\right)^2-\left(3-\sqrt{2(x-1)}\right)^2\right)dx}$


text:
Q: Get rid of unicode error I have the following code attempting to print the edge lists of graphs. It looks like the edges are cycled but it's my intention to test whether all edges are contained while going through the function for further processing.
def mapper_network(self, _, info):
    info[0] = info[0].encode('utf-8')
    for i in range(len(info[1])):
        info[1][i] = str(info[1][i])
    l_lst = len(info[1])
    packed = [(info[0], l) for l in info[1]] #each pair of nodes (edge)
    weight = [1 /float(l_lst)] #each edge weight
    G = nx.Graph()
    for i in range(len(packed)):
        edge_from = packed[i][0]
        edge_to = packed[i][1]
        #edge_to = unicodedata.normalize("NFKD", edge_to).encode('utf-8', 'ignore')
        edge_to = edge_to.encode("utf-8")
        weight = weight
        G.add_edge(edge_from, edge_to, weight=weight)
    #print G.size()  #yes, this works :)
    G_edgelist = []
    G_edgelist = G_edgelist.append(nx.generate_edgelist(G).next())
    print G_edgelist

With this code, I obtain the error
Traceback (most recent call last):
File "MRQ7_trevor_2.py", line 160, in <module>
MRMostUsedWord2.run()
File  "/tmp/MRQ7_trevor_2.vagrant.20160814.201259.655269/job_local_dir/1/mapper/27/mrjob.tar.gz/mrjob/job.py", line 433, in run
mr_job.execute()
File "/tmp/MRQ7_trevor_2.vagrant.20160814.201259.655269/job_local_dir/1/mapper/27/mrjob.tar.gz/mrjob/job.py", line 442, in execute
self.run_mapper(self.options.step_num)
File "/tmp/MRQ7_trevor_2.vagrant.20160814.201259.655269/job_local_dir/1/mapper/27/mrjob.tar.gz/mrjob/job.py", line 507, in run_mapper
for out_key, out_value in mapper(key, value) or ():
File "MRQ7_trevor_2.py", line 91, in mapper_network
G_edgelist = G_edgelist.append(nx.generate_edgelist(G).next())
File "/home/vagrant/anaconda/lib/python2.7/site-packages/networkx/readwrite/edgelist.py", line 114, in generate_edgelist
yield delimiter.join(map(make_str,e))
File "/home/vagrant/anaconda/lib/python2.7/site-packages/networkx/utils/misc.py", line 82, in make_str
return unicode(str(x), 'unicode-escape')
UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 0: \ at end of string

With the modification below
edge_to = unicodedata.normalize("NFKD", edge_to).encode('utf-8', 'ignore')

I obtained
edge_to = unicodedata.normalize("NFKD", edge_to).encode('utf-8', 'ignore')
TypeError: must be unicode, not str

How to get rid of the error of unicode? It seems very troublesome and I highly appreciate your assistance. Thank you!!

A: I highly recommend reading this article on unicode. It gives a nice explanation of unicode vs. strings in Python 2.
For your problem specifically, when you call unicodedata.normalize("NFKD", edge_to), edge_to must be a unicode string. However, it is not unicode since you set it in this line: info[1][i] = str(info[1][i]). Here's a quick test:
import unicodedata

edge_to = u'edge'  # this is unicode
edge_to = unicodedata.normalize("NFKD", edge_to).encode('utf-8', 'ignore')
print edge_to  # prints 'edge' as expected

edge_to = 'edge'  # this is not unicode
edge_to = unicodedata.normalize("NFKD", edge_to).encode('utf-8', 'ignore')
print edge_to  # TypeError: must be unicode, not str

You can get rid of the problem by casting edge_to to unicode.
As an aside, it seems like the encoding/decoding of the whole code chunk is a little confusing. Think out exactly where you want strings to be unicode vs. bytes. You may not need to be doing so much encoding/decoding/normalization.


text:
Q: Existem alguma função em R similar ao PROCV do excel? No meu caso tenho dois data.frames:
> head(Trecho)
         Xt       Yt Zt
1 -75.56468 1.642710  0
2 -74.56469 1.639634  0
3 -73.56469 1.636557  0
4 -72.56470 1.633480  0
5 -71.56470 1.630403  0
6 -70.56471 1.627326  0

    > head(TrechoSim)
        Xs        Ys Zs
1 -71.7856 -0.509196  0
2 -71.7856 -0.509196  0
3 -71.7856 -0.509196  0
4 -71.7856 -0.509196  0
5 -71.7856 -0.509196  0
6 -71.7856 -0.509196  0

O data frame Trecho tem aproximadamente 5 mil linhas e o TrechoSim tem  20 mil linhas. Semelhante ao PROCV do Excel, preciso buscar o valor mais próximo onde Xt = Xs (no excel uso o VERDADEIRO, e retorna o primeiro valor mais próximo de Xt). Não existe uma tolerância para essa proximidade. Preciso de todos os valores do data frame Trecho com seu respectivo valor mais próximo de TrechoSim.
Tentei difference_inner_join mas ele retorna valores NA em algumas linhas.
Grata,

A: Eu não tenho os conjuntos de dados originais ou o Excel instalado para testar a função PROCV, mas creio que o código abaixo resolveu o problema.
A função procura calcular a diferença, em valor absoluto, entre um número e um vetor e encontra qual posição do vetor é mais próxima deste número.
O código não está otimizado, mas imagino que deva rodar razoavelmente rápido em computadores atuais. Testei o mesmo código aumentando os tamanhos amostrais dos dados simulados para 5000 e 20000 e meu código levou menos de 2 segundos para fazer todas as comparações.
Trecho    <- data.frame(Xt=rnorm(5),  Yt=rnorm(5),  Zt=0)
TrechoSim <- data.frame(Xs=rnorm(20), Ys=rnorm(20), Zt=0)

procura <- function(x, y){
  return(which.min(abs(x-y)))
}

index <- 0

for (j in 1:length(Trecho$Xt)){
  index[j] <- procura(Trecho$Xt[j], TrechoSim$Xs)
}

Trecho
TrechoSim[index, ]