text:
Q: Submitting CI form without page reloading So I have a controller within CI for updating the title of a Shoutcast server.
I'd like be able to run the form, without the page reloading.
The applicable controller / view is below;
Controller
                function update_title()
            {
                $this->form_validation->set_rules('song', 'Song', 'trim|required|xss_clean');
                $this->form_validation->set_error_delimiters(
                    '

                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    ×
                    </button>', '
'
                );

                if ($this->form_validation->run() == FALSE)
                {
                    /* $this->load->view('header');
                    $this->load->view('radio/panel'); // Failed validation
                    $this->load->view('footer'); */
                    $this->broadcast();
                }
                else
                {
                $data   =  $this->data;
                $ip     =  $data[1]; // Server Address
                $port   =  $data[2]; // Server Port
                $pass   =  $data[4]; // Admin Password
        //  -------------------------------------------------
                $song = $this->input->post('song');
                $song = urlencode($song);
                $song = str_replace("+", "%20", $song);
                $fp = @fsockopen($ip,$port,$errno,$errstr,4);
                if (!$fp) {
                    print "Error: cant get server, please check that server is online";
                } else {
                    fputs($fp, "GET /admin.cgi?pass=" . $pass . "&mode=updinfo&song=" . $song . " HTTP/1.0\r\n");
                    fputs($fp, "User-Agent: Mozilla\r\n\r\n");
                    fclose($fp);
                    $song = str_replace("%20", "+", $song);
                    $song = urldecode($song);
                }
                    $this->load->view('header');
                    $this->load->view('radio/title_updated');
                    $this->load->view('footer');
                }
            }

View
<?php
            $input_title = array(
                'name'  => 'song',
                'id'    => 'song',
                'size'  => 30,
                'class' => 'form-control',
                'placeholder' => 'Artist(s) - Show Name'
            );

            $input_submit = array(
                'name'  => 'submit',
                'class' => 'btn btn-primary',
                'type'  => 'submit'
            );

            ?>

                <?php echo validation_errors(); ?>

                <?php
                echo form_open('radio/update_title');
                echo '
';
                echo form_input($input_title);
                echo '';
                echo form_button($input_submit, '');
                //echo form_submit('submit', 'Update Show Title', "class='btn btn-primary'");
                echo '
';
                echo form_close();
                ?>

This all works perfectly, however as I say the page is refreshing. I've tried following a number of guides on this, however regardless of what I try, the page reloads.
Can someone please offer some advice?
Thank you in advance!

A: It sounds like your problem is primarily client-side at this point.  You should never see the page refresh if you're properly calling an AJAX function.  Even if it errors out, it would die silently (or show an error in the javascript console).  So lets put together a call for your function.
In your PHP, you will have to add an ID to your form.  This is important to key off of when we build the jQuery around the AJAX call
echo form_open('radio/update_title', array('id' => 'update-title'));

Now we can start building the javascript.  jQuery has some really nice features for calling ajax and we'll use them to full effect.
$('#update-title').on('submit', function(event){ // make sure you pass the event param

    // get the form values and serialize them
    var values = $(this).serializeArray();

    // lets make our call to the server
    $.ajax({
        url: this.action,
        type: 'POST',
        data: $.param(values), // get it in the right format
        error: function(data, status, error) {
            // handle your errors here
        },
        success: function(data, status) {
            // show your validation or display success message
        },
        complete: function(data, status) {
            // other post-process stuff regardless of success
        }
    });

    // here's the important part to prevent the page load
    event.preventDefault();
});

I would highly recommend either detecting AJAX or using a different method other than update_title for your AJAX request because of the $this->load->view calls in update_title.  Whatever you echo out is what you will need to work with back on the client side, and if you echo out a full HTML document, it's going to be a mess.  I suggest validating server-side and then returning your success, error, or validation error messages with JSON and not loading views. NOTE: this is untested code


text:
Q: question about integration of symmetrical graph to find area
let's say, we have an symmetrical curve such as $x=\sqrt{y}$
If we integrate from 4 to 0, wouldn't it cancel out with the area on the other side of the axis?
When integration is performed from 4 to 0, where exactly is the area we are getting?

A: Taking the integral of the function $f(x) = \sqrt x $ over the interval $0 \le x \le 4$ yields the area$$ \int\limits_0^4 {{x^{\frac{1}{2}}}} dx=\left[ {\frac{2}{3}{x^{\frac{3}{2}}}} \right]_0^4$$
However, for a function $f(x) =  \pm \sqrt x $ the integral over this interval is given by  $$ + \int\limits_0^4 {{x^{\frac{1}{2}}}} dx - \int\limits_0^4 {{x^{\frac{1}{2}}}} dx = 0$$.
The second integral is negative only by virtue that the height of $f$ takes negative values as well as positive. In contrast to the height of the function, the area enclosed by any function can never be negative by definition of area.
It is therefore not sufficient to compute integrals when considering areas. It is also necessary to consider the position of the function with respect to the $y-axis$.
In this example the function is symmetrical about the $x-axis$ so it is convenient to compute the required area as $$ 2 \int\limits_0^4 {{x^{\frac{1}{2}}}} dx =2\left[ {\frac{2}{3}{x^{\frac{3}{2}}}} \right]_0^4$$

A: Area is an unsigned scalar. Area = $ \int _ {0} ^ {4} y  \,dx $  or $ \int _ {4} ^ {0} y  \,dx $  i.e., x- limits taken between  $ x=0 , x=-2 $ or $x=-2 , x =0 $ is quite the same. Like between cuts in a pie of cake its area or weight is same whether  you take a cut first at the left or at the right.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Action Script loop I'm new to using actionscript 3 and I was wondering if it was possible to simplify this code and create a loop of some sort, so I could easily replicate the function whenever I'm importing a new button.
The code is this:
videobutton.addEventListener(MouseEvent.CLICK, fl_OpenVideo);
gallerybutton.addEventListener(MouseEvent.CLICK, fl_OpenGallery);
contactbutton.addEventListener(MouseEvent.CLICK, fl_OpenContact);

function fl_OpenVideo(event:MouseEvent):void{
if (!(currentClip is Vids))
   {
       currentClip.play();
        var newClip:Vids = new Vids;
        addChild(newClip);
        newClip.play();
        newClip.y =140;
        currentClip =  newClip;
   }
}
function fl_OpenGallery(event:MouseEvent):void
{
    if (!(currentClip is Gal))
   {
    currentClip.play();
    var newClip:Gal = new Gal;
    addChild(newClip);
    newClip.play();
    newClip.y =140;
    currentClip =  newClip;
   }
}
function fl_OpenContact(event:MouseEvent):void
{
    if (!(currentClip is Con))
   {
    currentClip.play();
    var newClip:Con = new Con;
    addChild(newClip);
    newClip.play();
    newClip.y =140;
    currentClip =  newClip;
   }
}

A: You can do like that:
videobutton.addEventListener(MouseEvent.CLICK, fl_Open);
gallerybutton.addEventListener(MouseEvent.CLICK, fl_Open);
contactbutton.addEventListener(MouseEvent.CLICK, fl_Open);

const S:Sprite = new Sprite();
S.y = 140;
this.addChild(S);
var __last:*;

function fl_Open(event:MouseEvent):void
{
    while(S.numChildren > 0) S.removeChildAt(0);
    if(event.target == videobutton) __last = new Vids;
    if(event.target == gallerybutton) __last = new Gal;
    if(event.target == contactbutton) __last = new Con;
    __last.play();
    S.addChild(__last);
}


text:
Q: Pyramid Authentication/Authorization implementation Software: Python 2.7.9, Pyramid 1.5.7
Updates
The issue I kept coming across was the inability of group_finder to return the value of the retrieved user and their respective group from the database. This became worse when validating the user's permissions (ACE/ACL) since the two did not match. I created a custom group_finder function that would print out the retrieved results to match the ACL permissions. With that said, I still find that this function needs conditionals to handle an unrecognized username / password. As of right now it breaks the program. What type of If statement should I include to handle None?
Working callback function, but needs if statement to handle unknown userid:
def groupfinder(userid, request):
    print '#'*80
    print userid # this is the username
    group_name = api.retrieve_group_byusername(userid) # retrieves user and returns [Group(group_name='')]
    print 'group_name', group_name[0].group_name # Registered User
    gp = group_name[0].group_name
    print 'gp', gp #gp Registered User
    print ['g:%s' % gp] # [u'g:Registered User']
    return ['g:%s' % gp] #[u'g:Registered User']

Original Error:
I am trying to implement the SQLAlchemy User and Group classes via the Pyramid groupfinder function and RootFactory. I created a nifty API using CRUD for retrieving user by group and group by user etc...
After going through Pyramid's tutorial and this awesome 'Group-Level' tutorial, I am still struggling with the nuts and bolts of getting users authenticated and authorized. It's currently not working. I've noticed that the terminal prints ACLDenied permission 'create' via ACE ' ... despite the fact that permission is granted.
I am looking specifically at the Registered User view. Root Factory is established exactly as shown in the Pyramid Tutorial Wiki.
original code:
    #API from db for api.retrieve_group_byuser(username)

        def retrieve_group_byuser(self, username):
                # retrieves a group by username
                query = self.session.query(Group).\
                filter(Group.users.any(User.username == username)).all() #returns a list
                print "retrieved by username:", query
                return query

    #security.py

        from ..models import * #DB

        def groupfinder(userid, request):
            print '#'*80
            print userid # this is the username
            group = api.retrieve_group_byuser(userid) # retrieves group by username
            if userid in group:
                return group(userid, [])

    #models.py (includes the import of the DB and API)

        class RootFactory(object):
            __acl__ = [ (Allow, Everyone, 'view'),
                    (Allow, 'group: Administrator', ALL_PERMISSIONS),
                    (Allow, 'group: Registered User', 'create')
                    ]
            def __init__(self, request):
                self.request = request

    #views **(default.py)**

        @view_config(route_name='login', renderer='templates/login.jinja2')
        @forbidden_view_config(renderer='templates/login.jinja2')
        def login(request):
            login_url = request.route_url('login')
            referrer = request.url
            if referrer == login_url:
                referrer = '/' # never use the login form itself as came_from
            came_from = request.params.get('came_from', referrer)
            message = ''
            login = ''
            password = ''
            if 'form.submitted' in request.params:
                login = request.params['login']
                password = request.params['password']

                user = api.retrieve_user(login)
                if(user is not None):
                    headers = remember(request, login)
                    return HTTPFound(location = came_from,
                                     headers = headers)
                message = 'Failed login'

            return dict(
                message = message,
                url = request.application_url + '/login',
                came_from = came_from,
                login = login,
                password = password,
                )

        @view_config(route_name='assessments', request_method='GET', renderer='templates/assessments.jinja2', permission='create')
        def view_assessments(request):
            login = authenticated_userid(request)
            if login is None:
                raise HTTPForbidden()
            #more code

    #__init__.py (auth setup and routes)

        authn_policy = AuthTktAuthenticationPolicy(
        'sosecret', callback=groupfinder, hashalg='sha512')
        authz_policy = ACLAuthorizationPolicy()
        config = Configurator(settings=settings,
                            root_factory='notssweb.models.RootFactory')
        config.set_authentication_policy(authn_policy)
        config.set_authorization_policy(authz_policy)

        config.add_route('frontpage', '/')
        config.add_route('login', '/login')
        config.add_route('logout', '/logout')
        config.add_route('users', '/users')
        config.add_route('user', '/users/{id:\d+}/{login}')

    #Terminal prints:

        starting subprocess with file monitor
        --db Session--
  ################################################################################
        dorisday # this is the userid being entered
        retrieved by username: [<Group(group_name='Registered User')>] #this is the group_finder api printout
        2015-11-10 15:02:29,240 DEBUG [web][Dummy-3] debug_authorization of url http://0.0.0.0:6432/assessments (view name u'' against context <models.RootFactory object at 0x110005ad0>): ACLDenied permission 'create' via ACE '<default deny>' in ACL [('Allow', 'system.Everyone', 'view'), ('Allow', 'group: Administrator', <pyramid.security.AllPermissionsList object at 0x10e932d10>), ('Allow', 'group: Editor', ('add', 'edit')), ('Allow', 'group: Registered User', 'create')] on context <models.RootFactory object at 0x110005ad0> for principals ['system.Everyone']


text:
Q: Spring in Action 3 example of AOP causing problems I am working my way through Spring in Action 3 and there is an example in there of using AOP with the around aspect.
This is the Aspect class:
package com.xetius.springIdol;

import org.aspectj.lang.ProceedingJoinPoint;

public class Audience {

public void watchPerformance(ProceedingJoinPoint joinpoint) {
    try {
        System.out.println("The audience is taking their seats.");
        System.out.println("The audience is turning off their cell phones.");
        long start = System.currentTimeMillis();

    joinpoint.proceed();

        long end = System.currentTimeMillis();
        System.out.println("CLAP CLAP CLAP CLAP CLAP");
        System.out.println("The performance took " + (end - start) + " milliseconds.");
    } catch (Throwable e) {
        System.out.println("Boo! We want our money back!");
    }
}

and here is the spring xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="audience" class="com.xetius.springIdol.Audience" />

    <aop:config>
        <aop:aspect ref="audience">
            <aop:pointcut id="performance2" expression="execution(* com.xetius.springIdol.Performer.perform(..))"/>
            <aop:around pointcut-ref="performance2" method="watchPerformance()"/>
        </aop:aspect>
    </aop:config>
</beans>

However, when I run this I am getting the following exception thrown:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'audience' defined in class path resource [springIdol.xml]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Cannot create inner bean '(inner bean)' of type [org.springframework.aop.aspectj.AspectJAroundAdvice] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Cannot create inner bean '(inner bean)' of type [org.springframework.aop.config.MethodLocatingFactoryBean] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Unable to locate method [watchPerformance()] on bean [audience]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:452)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.xetius.springIdol.SpringIdolMain.main(SpringIdolMain.java:13)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Cannot create inner bean '(inner bean)' of type [org.springframework.aop.aspectj.AspectJAroundAdvice] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Cannot create inner bean '(inner bean)' of type [org.springframework.aop.config.MethodLocatingFactoryBean] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Unable to locate method [watchPerformance()] on bean [audience]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:281)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:125)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:630)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:86)
    at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:100)
    at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:107)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:278)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:848)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:820)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:446)
    ... 10 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Cannot create inner bean '(inner bean)' of type [org.springframework.aop.config.MethodLocatingFactoryBean] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Unable to locate method [watchPerformance()] on bean [audience]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:281)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:125)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:616)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:270)
    ... 28 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Unable to locate method [watchPerformance()] on bean [audience]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:270)
    ... 36 more
Caused by: java.lang.IllegalArgumentException: Unable to locate method [watchPerformance()] on bean [audience]
    at org.springframework.aop.config.MethodLocatingFactoryBean.setBeanFactory(MethodLocatingFactoryBean.java:75)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1439)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1408)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    ... 38 more

I believe the pertinent line is:
nested exception is java.lang.IllegalArgumentException: Unable to locate method [watchPerformance()] on bean [audience]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:452)

I am trying to do this using Springs implementation of AOP, but I believe I have to include part of AspectJ to do this.
If I remove the parameter ProceedingJoinPoint joinpoint then it can locate this method.  I thought that this was an implicit parameter in the method for the around aspect.  Is this correct?  If not, what am I doing wrong here?
I am using Maven to build this.  Here is my POM:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.xetius</groupId>
<artifactId>springIdol</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>

<name>springIdol</name>
<url>http://maven.apache.org</url>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>3.0.4.RELEASE</spring.version>
    <aspectj.version>1.6.9</aspectj.version>
    <junit.version>4.6</junit.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjtools</artifactId>
        <version>${aspectj.version}</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>
</project>

A: The method name should be specified without the brackets:
method="watchPerformance"


text:
Q: Python: setting apart speech from empty audio records I'm trying to write a Python-3.6 script that would set apart empty .aif audio records (i.e. containing ambient noise only) from those which contain speech. My aim is not to recognize speech content - firstly, it's not English, and secondly, it's not needed for my purposes.
Nonetheless, I failed to invent something better than to use SpeechRecognition with pocketsphinx for resolving this issue. My idea was quite primitive:
        import speech_recognition as sr

        r = sr.Recognizer()
        emptyRecords = []
        for fname in os.listdir(TESTDIR):
            with sr.AudioFile(TESTDIR + fname) as source:
                recorded = r.record(source)
                recognized = r.recognize_sphinx(recorded)
            if len(recognized) <= 10:
                print("{} seems to be an empty record.".format(fname))
                emptyRecords.append(fname)

That is, I tried to transform recorded audios into lists of strings and to separate those lists according to an 'intuitive' threshold of 10 words, since sometimes pocketsphinx recognized background noise as a sparse sequence of several interjections. However, this took an extremely long time because of unnecessary speech recognition process - for each record I only needed to check whether it containted more than 10 words and nothing more. As far as I understand from SpeechRecognition's docs, the Recognizer class doesn't contain any attributes or methods that would limit the number of words to be recognized.
Could someone suggest a better idea for this issue?
Thanks in advance.

A: Try webrtcvad lib. Set aggressiveness mode and test with your recorded data.
https://pypi.org/project/webrtcvad/

A: You could use a STFT (Short TIME Fourier Transform)
Getting the total energy in the signal and comparing it to the energy that is located in the human vocal range (300 Hz to 3000 Hz). (https://en.wikipedia.org/wiki/Short-time_Fourier_transform)
Here is a simple stft using numpy and a fft size of 1024, you can use it https://github.com/JPabloVasquez/SimpleAudioTools


text:
Q: How to choose suitable naming convention for Dimensional Table Column in a Data Mart? I have done a lot of reading on naming columns for use in a data mart / data warehouse, as well as for general programming usage.
For example, if I had a business branch in a normal application I would have
Table BRANCH
------------
ID
Code
Name
RegionID

Now in the star schema data mart, I want to flatten the region information into this table.
Which would be more appropriate and user friendly as a naming choice?
Table Branch_Dim
------------
BranchID
BranchCode
BranchName
RegionName
RegionShortName

OR
Table Branch_Dim
------------
ID
Code
Name
RegionName
RegionShortName

A: I just completed a 4 day course with the Kimball group and they had this to say on naming conventions:

*

*Always use full descriptive names ie. Brand Name. and don't use abbreviations. Otherwise you may need to spend time training users.

*Don't use Dim or Fact in your table names because you end up spending a lot of time deleting these from the reporting layer.

*Don't use camel case or underscores, use spaces. Yeah I thought this was bizarre, but again they said you'll spend a lot of time adding in space at the reporting layer and most databases now handle spaces in column names without a problem.

If you subscribe to the Kimball methodology, then this is their approach. But like the other commenter said, it's all about comprehension. So if it makes sense for the business users, then you're on the right track.

A: Based purely on the fact that "Name" is a reserved word in some RDBMS (although, not SQL Server 2008), I was always taught to avoid it like the plague.
Apart from that, naming conventions are used to boost comprehension and should therefore always be consistent.
You've got two names in your branch table, one of which is prefixed with which type of name it is ("RegionName") because you were forced to do so upon merging those tables. I think if you're prefixing one then you should prefix them ALL, consistency is more important than naming conventions themselves.
You could prefix every string in a software system with "wibble", it's a bit weird but at least another programmer would very quickly identify that "wibble" means it's a string.


text:
Q: Neo4j modeling relationship query I have a query regarding modeling a relationship in Neo4j:
Here is a graph that I am creating:

*

*Company1 has products - A, B, C

*Company2 has products - A, B, D

*Company2 competes with Company1

If I wanted to specify which products company2 is competing with company1 e.g. just product A. Would I have to put a list of products on the COMPETES relationship? or is there another way?

A: I think the definition of 'competing' should be more explicit. From the diagram you post, my common sense is that they compete on A and B, because they are both offering these products.
Putting an array of product(ids) on the COMPETES rel could work, but is not very 'graphy'
I would add (:Competition) nodes, and link them to each of the competing companies, as well as to specific products. The advantage would be that you can use this node, or the rel to store data on the type of competition (price, quality).

Another approach (perhaps even better) would be to create :(:Offering) nodes between the company and the products, and create [:COMPETES] rels between the competing offerings.


text:
Q: One-Sheeted- Hyperboloid I am given the following surface:
$z^2-xy=1$ . How can I show it is of the form $\frac{x^2}{a^2} + \frac{y^2}{b^2} - \frac{z^2}{c^2}=1$ ?
I can't find an appropriate coordinate change...
Will you help ?
Thanks a lot

A: Hint: Try letting $u=x+y$ and $v=x-y,$ and see if you can rewrite $z^2-xy=1$ in the form $$-\frac{u^2}{a^2}+\frac{v^2}{b^2}+\frac{z^2}{c^2}=1.$$


text:
Q: on submit form remove part of the word of input value I have a form that submits fields. I'm using Google autocomplete to suggest location and populate fields. Problem is that it adds extra words to the locations like -si, -do, etc.
I need to remove these extra words on submit.
I have this JQuery code but it does not work:
 $(document).ready(function () {
     $("form").submit(function () {
         $('input[name=locality').val.replace('-si', '');
         //return value.replace('-si', '');
     });
 });

Any help is appreciated.

A: $(document).ready(function () {
     $("form").submit(function () {
         var inp = $('input[name=locality]');
         inp.val(inp.val().replace('-si', ''));
     });
 });

Fiddle


text:
Q: Dynamically allocate or waste memory? I have a 2d integer array used for a tile map.
The size of the map is unknown and read in from a file at runtime. currently the biggest file is 2500 items(50x50 grid).
I have a working method of dynamic memory allocation from an earlier question but people keep saying that it a bad idea so I have been thinking whether or not to just use a big array and not fill it all up when using a smaller map.
Do people know of any pros or cons to either solution ? any advice or personal opinions welcome.
c++ btw
edit: all the maps are made by me so I can pick a max size.

A: Probably the easiest way is for example a std::vector<std::vector<int> > to allow it to be dynamically sized AND let the library do all the allocations for you. This will prevent accidentally leaking memory.

A: My preference would be to dynamically allocate. That way should you encounter a surprisingly large map you (hopefully) won't overflow if you've written it correctly, whereas with the fixed size your only option is to return an error and fail.
Presumably loading tile maps is  a pretty infrequent operation. I'd be willing to bet too that you can't even measure a meaningful difference in speed between the two. Unless there is a measurable performance reduction, or you're actually hitting something else which is causing you problems the static sized one seems like a premature optimisation and is asking for trouble later on.

A: It depends entirely on requirements that you haven't stated :-)

*

*If you want your app to be as blazingly fast as possible, with no ability to handle larger tile maps, then by all means just use a big array. For small PIC-based embedded systems this could be an ideal approach.

*But, if you want your code to be robust, extensible, maintainable and generally suitable for a wider audience, use STL containers.

*Or, if you just want to learn stuff, and have no concern about maintainability or performance, try and write your own dynamically allocating containers from scratch.

A: I believe the issue people refer to with dynamic allocation results from allocating randomly sized blocks of memory and not being able to effectively manage the random sized holes left when deallocated. If you're allocating fixed sized tiles then this may not be an issue.
I see quite a few people suggest allocating a large block of memory and managing it themselves. That might be an alternative solution.

A: Is allocating the memory dynamically a bottleneck in your program? Is it the cause of a performance issue? If not, then simply keep dynamic allocation, you can handle any map size. If yes, then maybe use some data structure that does not deallocate the memory it has allocated but rather use its old buffer and if needed, reallocate more memory.


text:
Q: Manual signing .appex breaks the safari browser extension I am trying to build a CI pipeline for a safari browser extension. And in order to achieve this I am manually signing the .app.
The file that creates problems is the .appex. From "extensionName.app/Contents/PlugIns/extenstionName Extension.appex". Not signing this file causes the notarization to flag the package as invalid. The order that I achieved the signing and caused the notarization to work is this.
(not actual signing request lines, I simplified them for easier readability)
# Signing first all the .dylib files
-timestamp --options runtime  "extenstionName.app/Contents/Frameworks/*.dylib"
# Then signing the binary from the appex
--prefix=com.domain. --timestamp --options runtime  "extenstionName.app/Contents/PlugIns/extenstionName Extension.appex/Contents/MacOS/extenstionName Extension"
# Then signing the .app package
--prefix=com.domain. --timestamp --options runtime  "extenstionName.app/"
# And at the end signing the .appex
--prefix=com.domain. --timestamp --options runtime  "extensionName.app/Contents/PlugIns/extensionName Extension.appex"

If I do the signing this way the notarization works, and the .app is code signed and can be verified. The issue is that the extension does not load at all in safari, not even with Allow Unsigned Extensions enabled. And I can't find any way to debug this. Clicking Quit and Open Safari Extensions Preferences... does nothing, nothing appears inside the Safari Extension Preferences menu.
I tried multiple combinations of signing order.

*

*Signing the .appex before the .app causes the code signature to not be valid at all.

*Do not sign the .appex at all causes the .app to be verified and signed but in safari you need to have unsigned extension enabled. And also the notarization fails throwing errors about the .appex that is not signed

*Not signing the binary from the .appex causes the notarization to fail throwing error that that binary is not signed.

Also I tried to run the signed and notarized .app on a clean macOS computer, and it does not load into safari, the same that happens on the development computer.

A: I had a similar issue, but it was related to QuickLook Preview Extension. This extension is just a small part(very) of the bigger .app. So we are performing manual signing.
What worked for me was replicating the Build steps in xcode.

*

*sign .appex file

*Touch .appex file

*Touch .app file

Touch command works for me, as it updates the file's access and modification timestamps for existing files. This kind of registered my .appex in System Properties -> Extensions, and made extension work flawlessly.


text:
Q: Why vector file I/O has this error in c++? I want to run file I/O. You want to enter int values one by one for vector and output them.
The input goes in properly, but a strange number is output when outputting. Can you help me?
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;

void saveOrder(vector<int> ex)
{
    ofstream fout("ex.txt");
    if (!fout.is_open()) {
        cerr << "fail" << endl;
        return;
    }
    for (vector<int>::iterator it = ex.begin(); it != ex.end(); it++) {
        fout << *it << " ";
    }
}

vector<int> loadOrder()
{
    vector<int> ex2;

    ifstream fin("ex.txt");

    if (!fin.is_open()) {
        cerr << "fail";
        return ex2;
    }

    while (!fin.eof()) {
        cout << fin.get() << endl;
        ex2.push_back(fin.get());
    }

    return ex2;
}

int main() {
    vector<int> ex;

    ex.push_back(1);
    ex.push_back(2);
    ex.push_back(3);
    saveOrder(ex);

    vector<int> ex3;
    ex3 = loadOrder();

    for (vector<int>::iterator it = ex3.begin(); it != ex3.end(); it++) {
        cout << *it << endl;
    }
}

enter image description here

A: Your loadOrder function implementation is not correct. fin.get() function reads one character at a time and returns it if its available otherwise it returns EOF.
So your while loop reads two character per loop:
cout << fin.get() << endl; display the first character on the console and
ex2.push_back(fin.get()); push the next character on to the vector as an integer.
Also it's not a good idea to use fin.eof() in while loop to check for end of file because fin.eof() will returns true only after reading the end of the file. So your while loop will try to access past the end of file before it terminates.
You can change loadOrder function as follows:
vector<int> loadOrder()
{
    vector<int> ex2;

    ifstream fin("ex.txt");

    if (!fin.is_open()) {
        cerr << "fail";
        return ex2;
    }

    int x;
    while (fin >> x) {
        ex2.push_back(x);
    }

    fin.close();
    return ex2;
}

Also if you have access to latest C++ compiler, you can use range-based for loop and automatic type deduction feature to make your code much more simpler.
For example, to print the vector you can use
for(const auto& elem : ex) {
     fout << elem << " ";
}


text:
Q: How to create a time-based BufferingHandler in python? I would like to create a time-based BufferingHandler. Currently, a BufferingHandler is based on a capacity, meaning it will flush the records only when this capacity is reached as can be seen in the source code:
class BufferingHandler(logging.Handler):
    def __init__(self, capacity):
        logging.Handler.__init__(self)
        self.capacity = capacity
        self.buffer = []

    def shouldFlush(self, record):
        return (len(self.buffer) >= self.capacity)

    def emit(self, record):
        self.buffer.append(record)
        if self.shouldFlush(record):
            self.flush()

    def flush(self):
        self.acquire()
        try:
            self.buffer = []
        finally:
            self.release()
    ...

What I tried is:
class TimeBasedBufferingHandler(BufferingHandler):

    def __init__(self, capacity=10, delta=60):
        BufferingHandler.__init__(self)
        self.capacity = capacity
        self.delta = delta  # in seconds (as time.time())

    def shouldFlush(self, record):
        is_full = len(self.buffer) >= self.capacity
        is_old = (record.created - self.buffer[0].created) >= self.delta
        return is_full or is_old

The problem in my TimeBasedBufferingHandler is that, if no record is received after the last record and shouldFlush did not return True, some logs will be trapped for a very long time in the buffer, which is not what I want. I still want to release the logs after some time (like delta) even if no record has been received to trigger the emit function.
How can I do that?

A: You can call flush yourself manually, from wherever you want, when you want to flush the handler's buffer. You could do this on a timer, for instance, something like:
timeout = 60
handler = TimeBasedBufferingHandler(capacity=XXX, delta=timeout)
timer = threading.Timer(timeout, handler.flush)


text:
Q: How to connect my PC to my Android with ADB wireless connections? I am new to android.
Is there any way to connect the wireless adb to my PC?
I've gone through many free apps which are not allowing me to connect when my PC doesn't have internet connection

A: Yes it is possible using this free app
https://play.google.com/store/apps/details?id=com.wave18.adbwireless
I am not sure have you ever used it or not

A: I think there are a lot of applications for wireless ADB connection for rooted devices. In case of non rooted devices, it is possible to establish ADB session over wifi, however, you'll have to connect your device to the PC over USB first:

*

*Connect your device to PC via USB

*Set the TCP/IP port to 5555:
$ adb tcpip 5555

*Disconnect your device (via USB) and then reconnect it over WiFi (do ping test to verify)

*Execute the following:
$ adb kill-server
$ adb connect 192.168.2.5

*

*daemon not running. starting it now on port 5037 *

*daemon started successfully *
connected to 192.168.2.5:5555

Now, you'll be able to run ADB commands over WiFi.


text:
Q: How to drop '+' or '-' characters in MASM Assembly In MASM Assembly, if the user writes "-22", I want to check the first character for a "-" sign and then drop it.
If the user writes "+12", I want to check the first character for a "+" sign and then drop it.
The code below is not working.
Could someone please let me know what is wrong with the code.
insertNums:

    lodsb

    cmp     ch, 43  ;I am not sure if this is the proper way of checking for a "+"
    je      convertPos
    cmp     ch, 45  ;Same with this. Does this check for ASCII 45 which is "-"?
    je      convertNeg
continue:
    cmp     eax, 0
    je      endInsert
    sub     eax, 48
    mov     ebx, eax
    mov     eax, value
    mov     edx, 10 ;multiplies by 10
    imul    edx
    jc      tooLargeNumber ; check for carry after multiply
    add     eax, ebx ;add the digit to the converted value
    jc      tooLargeNumber ; check for carry after adding
    mov     value, eax ; store temporary value from eax
    mov     eax, 0 ; reset eax
    loop    insertNums
    jmp     endInsert

convertPos:
; this is for positive numbers
; the goal is to just drop the'+' sign and feed it back to the loop

convertNeg:
; this one is supposed to drop the '-' sign
; and once I know it is a negative number, I would have a separate procedure for ;converting the number to a negative


text:
Q: How to save visible column state in bootstrap table toolbar? I am using bootstrap table toolbar in my table list. Now while uncheck any column from toolbar it's hide that column from table heading,but now how i will save this visible column states to see after refreshing the page?

A: There is a 'Table Cookie' extension. It saves:

*

*Sort order

*Page number

*Page number from the list

*Visible columns

*Search text

Source: https://github.com/wenzhixin/bootstrap-table/tree/master/src/extensions/cookie
Example: http://bootstrap-table.wenzhixin.net.cn/extensions/
Include the JS file

and add this attributes to your table:
data-state-save="true",
data-state-save-id-table="whateverIdYouLike"

Cookies must be enabled to use this extension.

A: Not sure if the data attributes have been updated since @Martin's post, however the two fields:
data-state-save="true",
data-state-save-id-table="whateverIdYouLike"

are not being used. Per current example: http://bootstrap-table.wenzhixin.net.cn/extensions/
View with debug tool:

Just utilize data-cookie-id-table instead and ensure it's value is unique if using multiple bootstrap tables on site.

A: Full source example here.
<link href="bootstrap-table.min.css" rel="stylesheet">

      ID
      Item Name
      Item Price

Otherwise
<link href="bootstrap-table.min.css" rel="stylesheet">

      ID
      Item Name
      Item Price


text:
Q: Purpose of "consider_all_requests_local" in config/environments/development.rb? What is the purpose of this Rails config setting...
config.action_controller.consider_all_requests_local = true

It's set to true by default in config/environments/development.rb.
Thanks,
Ethan

A: At development level we set:

consider_all_requests_local set = true

because developer needs to take a look at full error showing layout/view as you can see in the image below.

But at production level, we don't need to show our internal coding bug so we set  false:

config.consider_all_requests_local = false

A: Non-local requests result in user-friendly error pages.  Local requests, assumed to come from developers, see a more useful error message that includes line numbers and a backtrace.  consider_all_requests_local allows your app to display these developer-friendly messages even when the machine making the request is remote.


text:
Q: Is there a word for "things I am grateful for"? I am writing a letter of thanks to my parents, and I'm looking for a word that describes "things I am thankful/grateful for". I was hoping "gratuities" might carry the right meaning, but everything I read suggests this most commonly refers to a tip left at a restaurant (not even a close second definition that points to the object that one is grateful for). Word enthusiasts, do you have any recommendations?
Because this is a letter, I would probably choose to say "things I am grateful for" before using an uncommon word, but I'm hoping there's a fairly standard word I'm just failing to remember.

Sample sentence: "I wrote you this letter to share some memories and
overdue gratuities."

Thanks!

A: Well, to start with, note that it is not the things you are grateful that are overdue, but your gratitude. So your sentence would make more sense if you said

I wrote you this letter to share some memories and overdue gratitude.

As for things you are grateful for you could use benefactions:

Benefaction is the process or action of benefitting someone, particularly when you're motivated by kindness. When your neighbor is gravely ill and everyone on your street takes turns cooking meals for their family, that's a type of benefaction. (Voc.com)

If benefactions is too uncommon for you, then I would go for the general kindness:

I wrote you this letter to share some memories and overdue gratitude for your kindness (towards me).

A: Firstly, a gratuity is a tip: a small gift of money given to a waiter etc.
Next, we don't 'share' gratitude, we show or express it.
Finally, giving overdue thanks is more important than sharing memories. By placing it last in your sentence, it seems almost like an afterthought, as much as to say

Let me tell you about me, and thanks by the way.

So I would rephrase the sentence as

I wrote this letter to express my long overdue gratitude [for all your help], and I would also like to share some memories.

And continue with more detail, again beginning with the thanks, for example

I would never have been able to ... without your advice and assistance.

and so on. This puts the importance of their help, above your own news.

A: Perhaps thanks would suit you, ie

I wrote you this letter to share some memories and overdue thanks.

though I suspect it may not meet the register of formality you seem to want to use in writing to your parents.

A: The idiomatic standard here is

count one's blessings (Merriam-Webster)
to make a special effort to appreciate the good things in one's life
I try to remember to count my blessings every day.
You escaped the fire? Well, count your blessings!

Obviously originally, those "blessings" would have been bestowed by God. But atheists use this expression today without thinking about the religious dimension - just as they say Bless you! when someone sneezes, or OMG! when they're surprised.

A:

*

*I wrote you this letter to share some memories and overdue gratuities.

"Gratuities" is certainly not the proper term, but then supposing the proper term has been found, the idea of "sharing" what it represents makes no sense; a small modification is therefore necessary.

*

*I wrote you this letter to share some memories and thank you for your kindnesses.


text:
Q: Make Firebug NOT autocomplete I just started using Firebug, and the autocompletion feature is proving to be more a nuisance than an asset. The issue is that on some web pages there are elements whose names start with numbers, so that if I go to Firebug's console and type something like a=1, it will autocomplete to something I don't want.  Since Enter selects the autocompletion, there doesn't seem to be a good way to not choose to autocomplete.
The best solution to this that I've come up with so far is to put some whitespace after my desired command. I'm looking for a better solution. In particular:

*

*Is there another key besides Enter which will submit a command to the console, without accepting an autocompletion suggestion?

*Is there a way to reconfigure the autocompleter so that Enter does not select a suggestion (since Tab does the same thing, I see no need to have Enter also select suggestions...).

A: Sounds like a bug in Firebug - I opened https://code.google.com/p/fbug/issues/detail?id=7729 for it and pushed a fix.
As for your question, no, there is no way to make it not auto-complete other than (as you note) adding additional whitespace, or pressing Escape before Enter (this also serves as a revert key when you accidentally do auto-complete, FWIW). The reasoning is that any situation where it would be annoying is a bug, so adding a pref or way to avoid it would be admitting failure, in a sense.


text:
Q: Best way to parameterize a method I'm writing a custom dll that references another dll to implement SNMP PDUs.
Now in my dll I need to implement the Binding, that is the possibility to select from which network card to instantiate the udp packet towards the snmp agent. This function is not present in the dll that I downloaded, therefore I have to insert it by hand. The github module is somewhat extensive, there are several encapsulated methods, and the package instance is created within a series of encapsulations , here is the code that does it:
udpSocket.SendTo(bytes, receiver);
udpSocket.ReceiveTimeout = timeout;

Before the two instructions above, I have to add these 3 lines for binding:
IPAddress Binding = IPAddress.Parse("192.168.1.195");
IPEndPoint localIPEndPoint = new IPEndPoint(Binding, 0);
udpSocket.Bind(localIPEndPoint);

Now what I need to do is pass the address (192.168.1.195) as a parameter. My question is: is there a transversal way to declare some kind of global variable in the dll project, considering that the class implementing the method is static?


text:
Q: CakePHP Search plugin search in many fields I'm using CakePHP search plugin http://cakedc.com/downloads/view/cakephp_search_plugin and want to make an arg to search multiple fields I have the array filterArgs as follows
var $filterArgs = array(
      array('name' => 'search', 'type' => 'like', 'field' => 'Interview.title_en'),
    );

I want the search arg to search not only the field Interview.title_en but to search also another field I tried something like
var $filterArgs = array(
      array('name' => 'search', 'type' => 'like', 'field' => array('Interview.title_en',  'Interview.Desc'));

but It doesn't work!!
Any suggestions?

A: In order to achieve this, you have to create a simple method in your model which builds the 'OR' conditions for searching the fields.
public $filterArgs = array(
    array('name' => 'q', 'type' => 'query', 'method' => 'filterQuery'),
);

public function filterQuery($data = array()) {
    if(empty($data['q'])) { // q is the name of my search field
        return array();
    }

    $query = '%'.$data['q'].'%';
    return array(
        'OR' => array(
            'Model.title LIKE' => $query,
            'Model.description LIKE' => $query,
            'Model.resources LIKE' => $query,
        )
    );
}


text:
Q: How do I regex split with variable values? I have the following string:

21>Please be specific. What do you mean by that?21>Hello are you there623>Simon?

I want to split it into:
21>Please be specific. What do you mean by that?
21>Hello are you there
623>Simon?

Basically the splitter is the numeric value (21 and 623 in this case) followed by the >.
My implementation is that I find the > char, then walk back until I find a non-numeric value.
So basically using sub-string and the like.  But it's ugly and I am certain there is a better Regex implementation, but I don't know enough about it.
So can Regex be used here?

A: You can achieve that with look ahead and look behind, so that your match is the zero length area between what you want to split.
string s = "21>Please be specific. What do you mean by that?21>Hello are you there623>Simon?";
Regex reg = new Regex(@"(?<=\D)(?=\d+>)");
var r = reg.Split(s);
foreach(var i in r)
    Console.WriteLine(i);

Will output

21>Please be specific. What do you mean by that?
21>Hello are you there
623>Simon?

A: Try with following regex. It matches the zero width between something and number>
Regex: (?<=\D)(?=\d+>) replaced with \n for demo.
Explanation:

*

*(?<=\D) looks behind to see if it's not a number.

*(?=\d+>) looks ahead to see if it's a number>.
And matched the zer0-width between them.
Regex101 Demo

A: Try: [0-9]+>
Explanation:

*

*[0-9]+ At least 1 digit

*> followed by >

It might make sense to replace the matches with \n$0, which will move them to individual lines.


text:
Q: How to solve the problem that the video is covered by the navigation bar after full screen like this as follow,When I want to play in full screen, the video is overlaid behind

A: You have to use this code to hide the navigation bar:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mActivity.getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                    View.SYSTEM_UI_FLAG_FULLSCREEN |
                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                    //View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}

With fullscreen options you can hide status bar too and with Immersive sticky you can get the navigation and status bar again sliding your finger.
To remove this options use the following code:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            View decorView = mActivity.getWindow().getDecorView();
            int uiOptions = decorView.getSystemUiVisibility();

            uiOptions  &= ~View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
            uiOptions  &= ~View.SYSTEM_UI_FLAG_FULLSCREEN;
            uiOptions  &= ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            uiOptions  &= ~View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;

            decorView.setSystemUiVisibility(uiOptions);
}

A: you can use  react-native-full-screen which provide full screen control
You can put that on componentDidmount or useeffect method with     FullScreen.onFullScreen();


text:
Q: How to start Firefox with with specific profile Selenium Python geckodriver Here is my code:
profile = webdriver.FirefoxProfile('C:\\Users\\Administrator\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\kvycjolb.Prdel')
driver = webdriver.Firefox(profile)

Im not getting any error and firefox starts, but it just does not load with this profile: I have tried changing / to // etc.. but no luck.
This also does not work:
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
binary = FirefoxBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe")
profile = FirefoxProfile("C:\\Users\\Administrator\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\kvycjolb.Prdel")
driver = webdriver.Firefox(firefox_profile=profile, firefox_binary=binary, executable_path="C:\\aprog\\geckodriver.exe")
driver.get('https://google.com')

Im getting error:
C:\aprog>testff
Traceback (most recent call last):
  File "C:\aprog\testff.py", line 7, in <module>
    driver = webdriver.Firefox(firefox_profile=profile, firefox_binary=binary, e
xecutable_path="C:\\aprog\\geckodriver.exe")
  File "C:\Python27\lib\site-packages\selenium\webdriver\firefox\webdriver.py",
line 152, in __init__
    keep_alive=True)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", l
ine 98, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", l
ine 188, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", l
ine 256, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py"
, line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Unable to find a matchin
g set of capabilities

A: I think the official answer is found in documentation.
Presently that is:
# Custom profile folder to keep the minidump files
profile = tempfile.mkdtemp(".selenium")
print("*** Using profile: {}".format(profile))

# Use the above folder as custom profile
opts = Options()
opts.add_argument("-profile")
opts.add_argument(profile)
opts.binary = "/Applications/Firefox.app/Contents/MacOS/firefox"

driver = webdriver.Firefox(options=opts,
    # hard-code the Marionette port so geckodriver can connect
    service_args=["--marionette-port", "2828"])

A: To start Mozilla Firefox with a specific Firefox Profile through Selenium 3.4.3, geckodriver v0.18.0, Mozila Firefox 53.0 and Python 3.6, you need to create a separate Firefox Profile with the Firefox Profile Manager as per the documentation here.
I have created a Firefox Profile by the name debanjan. This profile got stored in this subdirectory:
"C:\Users\AtechM_03\AppData\Roaming\Mozilla\Firefox\Profiles"
The name of the profile (folder) is w8iy627a.debanjan. So while initiating the WebDriver instance we have to pass the absolute path of the Firefox Profile named as w8iy627a.debanjan as follows:
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

binary = FirefoxBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe")
profile = FirefoxProfile("C:\\Users\\AtechM_03\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\w8iy627a.debanjan")
driver = webdriver.Firefox(firefox_profile=profile, firefox_binary=binary, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe")
driver.get('https://google.com')

Let me know if this answers your question.

A: def setFirefoxDriver():
    profilePath = r"PathHere"
    driverPath  = r"pathHere\driver.exe"

    options = Options()
    options.add_argument("-profile")
    options.add_argument(profilePath)

    dService = Service(driverPath)
    d = webdriver.Firefox(service=dService, options=options)

    return d

d = setFirefoxProfile()

d.get('https://www.amazon.com/)

*

*to know profile paths search in your firefox about:support or about:profiles

*You can test it loading your own profile and see if cookies are loading, ie: when I go to amazon.com amazon recognizes me.

*Notice that you can't be using the same profile in 2 different instances, so if you wanna load your profile to test in selenium you shouldn't be using that firefox profile, but another one.

A: Always use double backslashes in the path (for Windows paths at least):
profile = webdriver.FirefoxProfile('C:\\Users\\Administrator\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\kvycjolb.Prree')

In your code, you use both backslashes and forward slashes.


text:
Q: Why a field theory containing only fermions does not show spontaneous symmetry breaking? For a real scalar field $\phi$, a theory as simple as the $\phi^4$ theory, can exhibit the phenomenon of Spontaneous Symmetry Breaking (SSB). For a complex scalar field $\phi$, a theory as simple as the one described by a potential of the form $V(\phi^*\phi)$ is capable of showing SSB. Why is it that a simple quantum field theory containing only a fermion field $\Psi$ incapable of showing this feature of SSB?
Added after @Dwagg's answer I was a bit sloppy in saying that theories with only fermions do not admit SSB. In QCD, there is chiral symmetry breaking which is related to a nonzero VEV of the operator $\bar{q}q$ for a quark field $q$. But the route is not straightforward.
In classical field theories, the standard way to check whether SSB has occurred is the following. One has a Lagrangian with a potential term $V(\phi)$. When minimized, the minimum of $V(\phi)$ occurs at a nonzero value of $\phi$. In QFT, one says that $\phi$ has got a VEV.
I have not seen such a straightforward route to understand QCD chiral symmetry breaking i.e., no such potential in the QCD Lagrangian. So the question is

Is there a similar way of showing that a nonzero VEV of $\bar{q}q$ is possible by minimizing some "effective potential" $V(\bar{q}q)$ of QCD.?

For the Gross-Neveu model in Dwagg's answer there is already a quartic term in the Lagrangian, and minimizing the potential w.r.t $\bar{\psi}_a\psi_a$ can give rise to SSB. Such a term is not there in QCD Lagrangian.

A: First, as already discussed, there are several (very similar) purely fermionic model field theories that exhibit spontaneous symmetry breaking, the models of Gross-Neveu, Thirring, and Nambu-Jona-Lasionio. These theories contain a fundamental four-fermion interaction ${\cal L}\sim G(\bar\psi\psi)^2$.
Second, there are interesting and important condensed matter systems that exhibit spontaneous symmetry breaking with a fermion-bilinear order parameter, BCS superconductivity in metals, neutron matter, liquid helium 3, and atomic gases. Fundamentally, these are not purely fermionic theories, but they can often be reduced to effective four-fermion theories. This is already a hint that a fundamental four-fermion interaction is not essential; such an interaction can always appear from integrating out other degrees of freedom.
In QCD we can define an effective potential for $\langle\bar\psi\psi\rangle$ in the usual way. Couple an external field to the order parameter (QCD already has such a term, the mass term) and compute the partition function. Then Legendre transform to get the effective action as a function of the order parameter. The static part is the effective potential.
Chiral symmetry breaking takes place at strong coupling, so we cannot compute the effective potential reliably (except in certain limiting cases), but we can identify the diagrams that contribute to it. The simplest is a fermion loop with a gluon going across. If the gluon was heavy (which it is not), we would be able to contract the gluon propagator to a point, and this diagram would be the same four-fermion closed-off-by-two-loops diagram that appears in the Gross-Neveu model (which is why, historically, Gross and Neveu studied it).

A: The typical method for SSB for fermions is the formation of bosonic bound states, such as Cooper pairs, which can then have an effective potential which looks like Landau-Ginzburg. There is no problem with, eg. $\langle \bar \psi(x) \psi(x) \rangle \neq 0$ while $\langle \psi(x) \rangle = 0$. There are also interesting systems in condensed matter physics such as superfluid He-3 which have order parameters with angular momentum such as $\langle \bar \psi \gamma^\mu \psi \rangle$.

A: Check out the Gross-Neveu model, which involves only fermions. The chiral symmetry is spontaneously broken by a composite field of fermions.


text:
Q: Benefit of creating Android activity vs Fragment I am creating an app that has a slide menu..When you choose different options of the slide menu, you can do the following:

*

*Option 1: Upload a photo

*Option 2: Check all the uploaded photos

*Option 3: Check out all the nearby events

I am not sure if it is better to create a fragment that is created when an option is selected, or if an activity should be created if an option is selected..Please note, each option shows certain elements such as an autocomplete location box that are common to each other.
CUrrently I have created a Fragment with subfragments that are displayed as the user clicks on each option. In hindsight, I am not sure if having activities having fragments was a better option. Can someone tell me what's a better way in my case, and why?


text:
Q: Using AJAX in Salesforce I want to create a picklist of all objects of my salesforce org. by the help of AJAX, without using apex controller.I want to achive this functionality by VF page only.

A: This can be done using the describeGlobal() method from the AJAX toolkit:
<apex:page title="Object List">

    <apex:pageBlock title="Object List">
        <apex:pageBlockSection columns="1">
            <apex:pageBlockSectionItem>
                Object List
                <apex:outputPanel>

                </apex:outputPanel>
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
    </apex:pageBlock>

</apex:page>

Note here, you would need connection.js file which is a Standard Salesforce JavaScript file.

A: You can use apex remoting for that, so you will be calling an apex class from your ajax method, but It's impossible to do that without calling apex, all you need to do is create a class that calls schema.getDescribe to get a map with all the objects in your org, then just send it back to your ajax as a JSON and convert it to a picklist


text:
Q: How is Maven supported in PhpStorm? Intellij supports Maven as a native Java tool pretty well.
Now Maven seems to grow more and more attractive for other languages, too.
So my question is how well does PhpStorm support integration of Maven in PHP projects.
Especially regarding:

*

*profile generation

*profile validation

*different views on profiles

*build-execution from IDE

*profile organization

*...

I cannot find much on that via Google ... so is that already the end of the story?

A: There is no Maven support in PhpStorm and it's not planned in the nearest releases.
You can submit a feature request to the issue tracker.


text:
Q: How can i get data row by row in HtmlAgilityPack? This is my 1 example data. There are 15 of these data.
How can i get 4 (data-class), 8,2(data-score),Parkk(name)I want data row by row. I think i must use foreach, someone can help me ?

        <a class="hotel_name_link url"
        href="/hotel/nl/parkhoteladam.tr.html?aid=309654;label=booking-be-tr-JKGYPlETyQ8zXLSF_YGpswS70199808652%3Apl%3Ata%3Ap1%3Ap2%3Aac%3Aap1t1%3Aneg%3Afi%3Atikwd-21085524309%3Alp1012783%3Ali%3Adec%3Adm;sid=8b79e4c094eb1d07801d638dbebd5d45;dcid=4;checkin=2015-11-28;checkout=2015-11-29;ucfs=1;room1=A,A;srfid=ddba57556d198f7f351dfd7936afdee5e7b5d96fX1;highlight_room="
         target="_blank"
        data-component="track" data-track="mouseenter" data-stage="1" data-hash="HMDCcKPRNHcXJEbSaTfRe"
        >
        Parkk

A: This works as expected:
var div = doc.DocumentNode.SelectSingleNode("//div[contains(@class, 'sr_item sr_item_new') and contains(@class, 'sr_item_default') and contains(@class, 'sr_property_block') and contains(@class, 'sr_flex_layout')and contains(@class, 'card-bigger-price')and contains(@class, 'sr_item--with-value-deal')]");
string hotelID = div.GetAttributeValue("data-hotelid", "");
string dataClass = div.GetAttributeValue("data-class", "");
string dataScore = div.GetAttributeValue("data-score", "");
string dataRecommended = div.GetAttributeValue("data-recommended", "");
string name = div.InnerText.Trim();

A: Building on the existing answer.
The xpath used to get the divs starts with "//div" which means that it will find all the dics that meet the criteria. The foreach loop then extracts the data from each div. You still have to populate that data into a list of a class.
    public static void Main(string[] args)
    {
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();

        doc.Load(link);

        HtmlAgilityPack.HtmlNodeCollection divs = doc.DocumentNode.SelectNodes("//div[contains(@class, 'sr_item sr_item_new') and contains(@class, 'sr_item_default') and contains(@class, 'sr_property_block') and contains(@class, 'sr_flex_layout')and contains(@class, 'card-bigger-price')and contains(@class, 'sr_item--with-value-deal')]");
        foreach (HtmlAgilityPack.HtmlNode n in divs)
        {
            string hotelID = n.GetAttributeValue("data-hotelid", "");
            string dataClass = n.GetAttributeValue("data-class", "");
            string dataScore = n.GetAttributeValue("data-score", "");
            string dataRecommended = n.GetAttributeValue("data-recommended", "");
            string name = n.SelectSingleNode("a").InnerText;
        }
    }


text:
Q: ng new failing with Angular CLI 7.2.1 I recently upgraded Angular CLI to 7.2.1. After upgrade I realized that while creating a new project using
ng new hello-ng-world
The command fails with following error.
npm WARN deprecated circular-json@0.5.9: CircularJSON is in maintenance only, flatted is its successor.
npm ERR! Unexpected end of JSON input while parsing near '...ource-map":"0.1.x"},"'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\XXX\AppData\Roaming\npm-cache\_logs\2019-01-15T04_01_29_782Z-debug.log
Package install failed, see above.

I checked the log file and found following lines
2298 silly fetchPackageMetaData error for mini-css-extract-plugin@0.4.4 Unexpected end of JSON input while parsing near '...","webpack-cli":"^2.0'
....
2316 silly fetchPackageMetaData error for portfinder@1.0.17 Unexpected end of JSON input while parsing near '...82V3Kq5OEdhCZQ8nOUUQ/'

2352 verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...ource-map":"0.1.x"},"'
2352 verbose stack     at JSON.parse (<anonymous>)
2352 verbose stack     at parseJson (C:\Program Files\nodejs\node_modules\npm\node_modules\pacote\node_modules\make-fetch-happen\node_modules\node-fetch-npm\node_modules\json-parse-better-errors\index.js:7:17)

Not able to proceed with the project creation. Please suggest what can be done.
Edit 1:
Ng version details (ng --version)
Angular CLI: 7.2.1
Node: 8.11.1
OS: win32 x64
Angular:
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.12.1
@angular-devkit/core         7.2.1
@angular-devkit/schematics   7.2.1
@schematics/angular          7.2.1
@schematics/update           0.12.1
rxjs                         6.3.3
typescript                   3.2.2

A: I had to force cache clean to make it work. I used the following command.
npm cache clean --force


text:
Q: Do I have to CompareTo implementation? I am trying to search in a list but I sort as array so that I convert my linked list to array list but when I compile it without this part below. Command prompt gives "Person is not abstract and does not override abstract method compareTo(Person) in Comparable".
How can I fix this?
public int compareTo(Person other){
    if (!this.name.equalsIgnoreCase(other.name))
        return this.name.compareTo(other.name);

        return this.name + " "+other.name;
}

Search list and sort methods:
public void searchList(String search)
{
    if(phoneList.size() == 0){
        System.out.println("There is no record phone book.");
    }

    Node<Person> tempNode = phoneList.head;
    SLinkedList<Person> tempList = new SLinkedList();
    for(int i=1; i<=phoneList.size; i++)
    {
        if (tempNode.getElement().getName().contains(search) || tempNode.getElement().getSurname().contains(search) || tempNode.getElement().getAddress().contains(search) || tempNode.getElement().getCell().contains(search) || tempNode.getElement().getHome().contains(search) || tempNode.getElement().getWork().contains(search))
        {
            tempList.addLast(tempNode.getElement());

            personArray = new Person[tempList.size()];
            Iterator<Person> it = tempList.iterator();

            while(it.hasNext()){
            int x = 0;
            personArray[x] = it.next();
            x++;
            }

            bubbleSort(personArray );
            for(int x = 0; x < tempList.size(); x++)
            System.out.println((x+1) + ""+ personArray[x]);

        }

        tempNode = tempNode.getNext();
    }
}

public <AnyType extends Comparable<? super AnyType>> void bubbleSort(AnyType[] a) {
    int outer, inner;
    for (outer = a.length - 1; outer > 0; outer--) { // counting down
        for (inner = 0; inner < outer; inner++) { // bubbling up
            if (a[inner].compareTo(a[inner + 1]) > 0) { // if out of order...
                //then swap
                swapReferences(a,inner,inner+1);
            }
        }
    }
}

    public <AnyType> void swapReferences( AnyType [ ] a, int index1, int index2 )
{
    AnyType tmp = a[ index1 ];
    a[ index1 ] = a[ index2 ];
    a[ index2 ] = tmp;
}

Person Class:
public class Person implements Comparable<Person>
{
    private String name;
    private String surname;
    public  String address;
    public  String cell;
    public  String home;
    public  String work;

    public Person(String name, String surname, String address, String cell, String home, String work)
    {
        this.name    = name;
        this.surname = surname;
        this.address = address;
        this.cell    = cell;
        this.home    = home;
        this.work    = work;
    }

    // Accessor methods:
    public String getName(){
        return name;
    }
    public String getSurname(){
        return surname;
    }
    public String getAddress(){
        return address;
    }
    public String getCell(){
        return cell;
    }
    public String getHome(){
        return home;
    }
    public String getWork(){
        return work;
    }

    // Modifier methods:
    public  void setName(String name){
        this.name = name;
    }
    public void setSurname(String surname){
        this.surname = surname;
    }
    public void setAddress (String address){
        this.address = address;
    }
    public void setCell (String cell){
        this.cell = cell;
    }
    public void setHome (String home){
        this.home = home;
    }
    public void setWork (String work){
        this.work = work;
    }

    public String toString(){
        return name + " " + surname + " " + address + " " + cell + " " + home + " " + work;
    }

    public int compareTo(Person other){
        if (!this.name.equalsIgnoreCase(other.name))
            return this.name.compareTo(other.name);

        return this.name + " "+other.name;
    }

}

A: Your existing compareTo method has a problem, but removing it violates the implements Comparable contract, since you must provide a compareTo method.
public int compareTo(Person other) {
    if (!this.name.equalsIgnoreCase(other.name))
        return this.name.compareTo(other.name);

    // next line returns a String, but the method needs to return an int
    return this.name + " " + other.name;
}

You can instead rely more directly on the standard String compareTo:
public int compareTo(Person other) {
    if ( this.name.equalsIgnoreCase( other.name ) ) { return 0 };

    return this.name.compareTo( other.name );
}

If you didn't have the ignore case constraint you've coded for, this would simply be
public int compareTo(Person other) {
    return this.name.compareTo( other.name );
}

As an aside, there is no reason to make address, cell, home, and work public — and that's generally bad practice.

A: In order to implement an interface you need to implement all the methods in that interface. You either remove implements Comparable part or add public int compareTo method to your class.
The rule of compareTo method is that :
- if this Person is greater than other , return 1
- if this Person is smaller than other , return -1
- if they are equal, return 0


text:
Q: Cast sqlite prepare to a custom model I want to cast result into a ModelA array but did not figure out a way.
let query = "SELECT t1.columnA, t2.columnB from table1 as t1, table2 as t2 ..."
let results = try! db.prepare(query) as Array<ModelA>() // I do not know how to cast

ModelA:
Struct ModelA: Codable{
let columnA: String
let columnB: String
}

A: You can't cast directly, try using map on the result
let models = results.map { ModelA(columnA: $0[0], columnB: $0[1] }


text:
Q: Confidence matrix for multilayer perceptron Use case: I have data which has 5 category of labels(output). I want to get the prediction confidence for the output.
Is there a way to get confidence matrix while doing prediction?
Thanks


text:
Q: Not able to print hex bytes in C I know this question has already been asked many times. I am facing a problem where I am getting few hex bytes via serial communication in ubuntu. I have written a C code which reads all the data and display it. It is working fine as I have tested it with many strings. I also have another system running windows and a software named Docklight. This software is giving me hex bytes and I need to receive it in my application.
Hex bytes are like below:
FF AA 2E 0F CC 0D
I have connected both the systems via null modem cable. Now to print hex bytes, we need to include %02X in printf  statement. Doing this, it gave me a warning of format '%X' expects argument of type 'unsigned int', but argument 2 has type 'unsigned char *'. I searched about this and replaced  it with %p. Here is the code:
unsigned char buf[255];

res = read(fd,buf,255);
buf[res]='\0';

printf("data: %p\n",buf);

The output of the printf statement is data: 0x603380. I opened the buf variable to see the exact values which are below:
Name : buf
Details:"ÿª.\017Ì\n", '\0' <repeats 248 times>
Default:0x603380 <buf>
Decimal:6304640
Hex:0x603380
Binary:11000000011001110000000
Octal:030031600

Now I really don't know why it shows random characters like ÿª.\017Ì\n The output of the printf is may be because it has combined all the bytes into one and displayed its hex equivalent.
I actually need to save each byte like FF and AA in an array. But just for the time being, I thought of first displaying it. What could be the issue. Why it is not displaying hex bytes. Can anyone give me suggestions on this. I also need to know that when we transmit hex bytes via serial, how does the receiving end should receive it. It should be saved as int or strings. Thanks.!

A: This is a basic C problem, you are giving printf() a pointer and expecting it to show your hex dump, as if it was a string. That's not the way it works.
You should do something like this:
unsigned char buf[255];

res = read(fd,buf,255);
// AN HEX BUFFER IS NOT A STRING DO NOT TERMINATE IT
// buf[res]='\0';

printf("data: ");
for (int i = 0; i < res; ++i)
  printf("%02x ", (int)buf[i]);

printf("\n");

The option %p of printf it's used to dump the pointer ADDRESS, not the contents a pointer point to.

A: printf("data: %p\n",buf);

This is printing address of variable buf, as you have used %p
To display buf in hex, you need to print it in loop character by character
printf("data: %.2X\n",buf[i]);// i from 0 to res

"I actually need to save each byte like FF and AA in an array."
Its already in your array ie buf, you need to print it correctly, if you want to display in hex


text:
Q: Image corrupted after POST on ftp I'm tryin to upload images from my Saved Photos (iPhone 4) using http-post request.
I got uploader.php which works fine moving $_FILES to right place.
But in the end, when image uploaded I see this:

I've spent hours trying to fix the problem and looking for related questions here but nothing works for me.
-(void)sendImage:(UIImage*)image{
    NSString *url = @"http://www.mypage.vv.si/uploader.php";
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                            cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                        timeoutInterval:60.0f];
    [theRequest setHTTPMethod:@"POST"];

    NSString *boundary = @"UVYDTNFMLFUVTTCECELPLCPELCPE";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [theRequest addValue:contentType forHTTPHeaderField:@"Content-Type"];

    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    if (imageData)
    {
        NSMutableData *body = [NSMutableData data];

        [body appendData:[[NSString stringWithFormat:@"Content-Length %d\r\n\r\n", [imageData length] ] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

        NSString *timeStr = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
        timeStr = [timeStr stringByReplacingOccurrencesOfString:@"." withString:@""];
        NSString *uniqueFileName = [NSString stringWithFormat:@"img%@.jpg", timeStr];
        NSString *contDispos = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", uniqueFileName];

        [body appendData:[contDispos dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:imageData];

        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [theRequest setHTTPBody:body];

        NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
        [theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
        NSURLConnection *connection = [NSURLConnection connectionWithRequest:theRequest delegate:self];
        if (connection) {
            self.infoData = [NSMutableData data];
        } else {
            NSLog(@"Connection failed");
        }
    }
    else
        NSLog(@"No Data!");
}


text:
Q: call procedure with out parameters in hibernate3 I work with hibernate3 and didn't use JPA
I have a procedure in oracle which return 2 out parameter
For test I execute this procedure in oracle with this query.
declare

req_type  number;
req_seq  number;

begin

insert_req(1111,req_type,req_seq);
dbms_output.put_line('req_type='||req_type);
dbms_output.put_line('req_seq='||req_seq);
end;

Now I want to call this procedure using hibernate
I try with native query without success using this code :
public void insertReq(String numEmp) {

                    int req_type  ;
                    int req_seq;

                    String sql = " insert_req(1111,:in1,:in2) ";
                    SQLQuery query = session.createSQLQuery(sql);
                    query.setParameter("in1", req_type);
                    query.setParameter("in2", req_seq);
                    List results = query.list();

                    System.out.println(req_type);
                    System.out.println(req_seq);

                    }

when I have a function I can run it using hibernate using this code as an example :
public void insertOrder(String numEmp) {

            String query = "call  insert_order(" + numEmp + ",50)";

            SQLQuery sqlQuery = this.getSession().createSQLQuery(query);
            sqlQuery.executeUpdate();

        }

but the problem is how to call procedure with 2 out parameter using hibernate.

A: you have to use CallableStatement and registerOutParameter.
you can get a connection from your hibernate session and create the callablestatement.
hibernate does not provide a mecanism to deal with this (at least as i know).
i hope that helps.

A: Try this and let me know.
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();

Session session = em.unwrap(Session.class);
session.doWork(new Work() {

    @Override
    public void execute(Connection con) throws SQLException {
        // do something useful
        try (CallableStatement stmt = con.prepareCall("{call my_sp()}")) {
            stmt.execute();
        }
    }
});

em.close();

Best regards.


text:
Q: Notification class not loading I have just started experimenting on android. I am reading book Beginning Android 4 application development by Wrox pulication. There is a code for showing notifications. The problem is the code I have written(not copied) is very little modified. So, I am able to show notification on status/notification bar but on clicking the notification the notificaion class is not being invoked. Here is the code for android_mainfest first.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="legacy_systems.notificationproject"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="9" />
<uses-permission android:name="android.permission.VIBRATE"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="legacy_systems.notificationproject.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="Notification"
        android:label="Details of the Notification" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</application>

</manifest>

Now, the code for MainActivity
package legacy_systems.notificationproject;
import android.os.Bundle;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {
int notificationID = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public void onClick(View V)
{
    getNotification();
}

protected void getNotification()
{
    Intent i = new Intent(this, Notification.class);
    i.putExtra("notificationID", notificationID);
    PendingIntent pn = PendingIntent.getActivity(this, 0, i, 0);
    NotificationManager nm= (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    Notification n = new Notification(R.drawable.ic_launcher,
                                      "Reminder! Meeting starts in 5 Minute",
                                      System.currentTimeMillis());
    CharSequence from = "System Alarm";
    CharSequence message = "Meeting with customer in next 2 minute";
    n.setLatestEventInfo(this, from, message, pn);
    n.vibrate = new long[]{ 100,250,50,500};
    nm.notify(notificationID, n);
}

}

And, the code for Notification.java is
    package legacy_systems.notificationproject;
import android.app.Activity;
import android.os.Bundle;
import android.app.NotificationManager;
import android.util.Log;

public class Notification extends Activity{
String tag;

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    Log.d(tag,"In here");

    setContentView(R.layout.notification);

    NotificationManager nm = (NotificationManager)getSystemService(VIBRATOR_SERVICE);
    nm.cancel(getIntent().getExtras().getInt("notificationID"));
}
}

And activity_main.xml is,
<xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<Button
    android:id="@+id/btn"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:text="@string/getnot"
    android:onClick="onClick"
 />

</RelativeLayout>

A: You would be well-advised to not name your own classes the same name as system-defined classes. You are attempting to open android.app.Notification as an activity, which will not work and should be resulting in warnings in LogCat.
Please rename your Notification activity to something else, such as Easdluaerdf, so as to make it unique, adjusting your manifest and PendingIntent to match, and you should have better luck.


text:
Q: Multi-submit buttons on one form with ajax I have a form which has 5 submit buttons like
<form action="pages/test.php" method="post" name="form1 "onsubmit="ajaxrequest('pages/test.php', 'resp'); return false;">
    <input type="hidden" name="Id" id ="Id" value=<?php echo "{$Id}"; ?> />
    <input type="submit" name="Value" value="0.01" />
    <input type="submit" name="Value" value="0.02" />
    <input type="submit" name="Value" value="0.03" />
    <input type="submit" name="Value" value="0.04" />
    <input type="submit" name="Value" value="0.05" />
</form>

Here will be displayed the server response.

The ajax processing for this is:
function get_XmlHttp() {
    var xmlHttp = null;

    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    return xmlHttp;
}

// sends data to a php file, via POST, and displays the received answer
function ajaxrequest(php_file, tagID) {
    var request =  get_XmlHttp();
    var Id = document.getElementById('Id').value;
    var Value = document.getElementById('Value').value;

    // create pairs index=value with data that must be sent to server
    var  the_data = 'Id='+Id+'&Value='+Value;

    request.open("POST", php_file, true);

    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.send(the_data);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            document.getElementById(tagID).innerHTML = request.responseText;
        }
    }
}

The test.php is:
$Id = strip_tags($_POST['Id']); $Value = strip_tags($_POST['Value']); echo "{$Id}, {$Value}";
The problem is that when clicking on any value in the form only the first value is ever displayed. How do I get it to recognise all the different submit values?

A: When posting, only the last value of the same name will be changed.
See this post on using multiple name elements
What you are looking for is something like this where you have multiple button names.
If you need to loop through them, give them predictable names then loop through the names like:
Submit1
Submit2
Submit3

EDIT:
You are getting the element by getElementByID('Value')
This will get the first element with the ID value.
This may be a good way to go here


text:
Q: how to edit my connection string to work with System.Data.SqlClient? i am a newbie programmer, and i have a problem with sqldatasource. In my project, i have a database called "KFS". I have a gridview and sqldatasource as gridview's datasource. I have a connection string like that:
"KFSConnectionString"
connectionString="Data Source=.\sqlexpress;Initial Catalog=KFS;Integrated Security=True"
providerName="System.Data.SqlClient"

This is working in VS2008 but when i load this on my website, it doesn't work. How should i change my connection string?

A: When running in Visual Studio you are able to connect to a database on your local system.  When you publish the web site to a web server, there is no local database for it to connect to.  You'll need to put your database on a SQL server (or use local MDF file in App_Data) and adjust your connection string accordingly.
The connection to a local file in the application would look something like this:
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;
    Database=dbname;Trusted_Connection=Yes;

See this reference for some various connection string options.
Here's a reference on how to access data in ASP.NET and VS2005.  I think this should still apply, at least with respect to the connection strings.

A: The '.\sqlexpress' in the Data Source property of your connection string is telling the application to connect to a SQL Server on the same machine.  If your web server is on a different computer you need to replace the '.' with the name of your computer.  The \sqlexpress portion is the name of the SQL Server instance which you shouldn't need to change.
You also want to make sure that your SQL Server allows remote connections.  By default I don't think it does. You can use the SQL Server Surface Area Configuration tool to change the remote connnection permissions.  The SAC tool should have been installed when you installed SQL Server under the Microsoft SQL Server 200x --> Configuration Tools folder in your Start Menu.  Have a look at the Surface Area Configuration for Services and Connnections and in there find the Remote Connections item.

A: I'd guess that either (or both) "Data Source" and/or the "integrated security" is incorrect. Your connection string is saying that the database is on the same server as the web server (signified by ".") and that the database is MSSQL Express, using a named instance (signified by .\"express") "integrated security=true" means that the account running your web server's aspx pages should be used to try to access the database. In my experience neither of these things are likely on a 3rd party hosting site. The database is mostly likely on a different server, and has specific credentials (username/password). I suggest calling your hosting provider's support or examining any activation emails you would have gotten from them.
Then again, you could be talking about your "website" meaning IIS on your development box (as opposed to vs2008's builtin server), and I may have wasted several minutes typing this. :D
-Oisin

A: It should work in local, but when you upload on server, you should post server IP address.


text:
Q: parsing through an extjs result I am using the extjs file upload using ColdFusion as my server language. My ColdFusion uploadaction page is returning the following result to extjs.
{"success":true,"data":{"file":"img\/diamondring22.jpg","Contact Id":"contact1"}}

I am very new to javascript and I need to retrieve the value of the file.
I can display action.response.responseText and see the results. I need to see the results in action.results.data but is shows as a null.
I tried using var mypluck = Ext.pluck('result', 'file'); but this returned nothing.
Any ideas would be greatly appreciated.

A: You can parse the responseText and create a JavaScript object. Then you'll easily be able to access it's values.
var responseObj = Ext.JSON.decode(action.response.responseText);

if (responseObj.success){
    var file = responseObj.data.file;
} else {
  //something
}