text:
Q: Gtest with lcov in c++ I have successfully generated the .gcda and .gcno files and they are in the same folder.
The flags in the make file looks as below :
CPPFLAGS += -std=c++11 --coverage -isystem $(GTEST_DIR)/include
CXXFLAGS += -std=c++11 --coverage -g -Wall -Wextra -pthread -I$(PULSE_DIR)/inc
CFLAGS += -std=c++11 --coverage -g -Wall -Wextra -pthread -I$(PULSE_DIR)/inc

I am using the googleTest (Gtest) to write the unitTests. The executable files generated for the unitTests are working fine. I just want to generate the code coverage.
I am successfully able to generate .gcno and .gcda files and both of them are in the same obj folder.
Then, I used the following lcov command from obj directory :
lcov -t "result" -o testcoverage.info -c -d .

This was supposed to generate testcoverag.info file but it gives me error as follows :
Capturing coverage data from .
Found gcov version: 5.4.0
Scanning . for .gcda files ...
Found 4 data files in .
Processing GeneratorObj_unittests.gcda
Cannot open source file deps/googletest/googletest/include/gtest/internal/gtest-internal.h
Cannot open source file deps/googletest/googletest/include/gtest/gtest-printers.h
Cannot open source file deps/googletest/googletest/include/gtest/gtest.h
Cannot open source file deps/googletest/googletest/include/gtest/internal/gtest-port.h
Cannot open source file deps/googletest/googletest/include/gtest/gtest-message.h
Processing GeneratorObj.gcda
Processing gtest-all.gcda
Cannot open source file deps/googletest/googletest/src/gtest-typed-test.cc
Cannot open source file deps/googletest/googletest/include/gtest/internal/gtest-port.h
Cannot open source file deps/googletest/googletest/src/gtest.cc
Cannot open source file deps/googletest/googletest/src/gtest-death-test.cc
Cannot open source file deps/googletest/googletest/include/gtest/internal/gtest-internal.h
Cannot open source file deps/googletest/googletest/src/gtest-internal-inl.h
Cannot open source file deps/googletest/googletest/include/gtest/internal/gtest-death-test-internal.h
Cannot open source file deps/googletest/googletest/include/gtest/gtest-printers.h
Cannot open source file deps/googletest/googletest/include/gtest/gtest.h
Cannot open source file deps/googletest/googletest/include/gtest/gtest-message.h
Cannot open source file deps/googletest/googletest/include/gtest/gtest-test-part.h
Cannot open source file deps/googletest/googletest/src/gtest-printers.cc
Cannot open source file deps/googletest/googletest/src/gtest-port.cc
Cannot open source file deps/googletest/googletest/src/gtest-test-part.cc
Cannot open source file deps/googletest/googletest/src/gtest-filepath.cc
Cannot open source file deps/googletest/googletest/include/gtest/internal/gtest-filepath.h
Cannot open source file deps/googletest/googletest/include/gtest/internal/gtest-param-util.h
Processing gtest_main.gcda
Cannot open source file deps/googletest/googletest/src/gtest_main.cc
Cannot open source file deps/googletest/googletest/include/gtest/gtest.h
Finished .info-file creation

GeneratorObj_unittests is the unittest file that I have written. It some how is not able to open all the files associated with gtest folder.
If I could only generate testcoverage.info file then I would be able to generate the html coverage file using the genhtml.
I tried checking the permission of the gtest files and they are all read and write. I dont know what is going on wrong here.


text:
Q: SQL use max date from one table in where statement of another Here's the business problem I'm trying to solve.  We have a sales table that updates weekly based on invoicing.  We also have a daily sales table that I want select so it's just transactions since the last refresh of the weekly sales table.
daily_sales.invoice_date > weekly_sales.invoice_date

I need to get the MAX date from the weekly sales table and then use to filter the daily sales data I'm pulling in a new SQL job.  Source tables are in oracle.  I'm a SQL rookie at best... any help you can provide would be greatly appreciated.  Thanks in advance!
Something like:
Select  a. SDKCOO "Order Company", a. SDDOCO "Order Number", a. SDDCTO "Order Type", a.SDIVD "Invoice Date", a.SDAEXP "Sales"
from    daily_sales a, weekly_sales b where a.SDIVD > b.DSIVD

A:
I need to get the MAX date from the weekly sales table and then use to
  filter the daily sales

select sdkcoo , sddoco, sddcto, sdivd, sdaexp
  from daily_sales
  where sdivd > (select max(dsivd) from weekly_sales)

A: I didn't understood what you want to achive but depending on my understanding do you want something like this:
  Select  a. SDKCOO "Order Company", a. SDDOCO "Order Number", a. SDDCTO "Order Type", a.SDIVD "Invoice Date", a.SDAEXP "Sales", b.MAX(DATE)
    from    daily_sales a CROSS JOIN weekly_sales b where a.SDIVD > b.DSIVD
    group by a. SDKCOO , a. SDDOCO , a. SDDCTO , a.SDIVD , a.SDAEXP

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to redirect with form data in asp.net mvc? Here is my situation, may be a little odd though: I login as admin, and go to some page with a form, then the authentication fail for some reason (for example, leave too long but not close the page, or disconnect the network and connect later), when i post the form again, it goes to login page. The login page can get returnUrl and redirect to the previous page, but all the form data is lost now. The final result is a application error page.
The redirect section of login is:
    if (Membership.ValidateUser(userName, password))
    {
        if (!String.IsNullOrEmpty(returnUrl))
            return this.Redirect(303, returnUrl);
        else
            return this.Redirect(303, FormsAuthentication.DefaultUrl);
    }

So ,how can i redirect with the form data(since many page needs authentication, the form data may vary from action to action)?

A: You cannot redirect with form data. When you are redirecting you are using a GET request. Form data is only contained in the body of a POST request. You could of course loop through all form data keys and values and append them to the target url as query string parameters but don't forget that there's a limitation to the length of a query string which could vary between the browsers.


text:
Q: How to deploy a png image to IOS device? I am taking an image in QPixmap & draw that pixmap via QPainter.
  Every thing works fine on the Desktop but when I run the application on an iPad (IOS), then image is not loading there.
It is showing only Painter drawing not image?
I also have included the image in resource file.
QPainter painter(this);  // My code snippet
painter.setPen("#7FFF00");
QPixmap pixmap(":template2.png");
pixmap.scaled(width(),height());
painter.drawPixmap(0,0,pixmap);

I included the resource file in .pro file like this.
RESOURCES = \
    untitled.qrc
Please tell me where I am wrong?


text:
Q: Why is a feature good for distinguishing a cluster? Let us supposed that we are trying to rank the importance of each feature of the dataset for each given cluster, in a clustering task. What are the characteristics that we should measure in the feature for considering it good for characterizing a given cluster?
I am looking for a more analytical characterization of these features. For example, if a feature f have a high standard deviation in the whole dataset, but a small standard deviation within a cluster c, does this means that this feature is important for distinguishing the cluster c?

A: There are two approaches you could use here:

*

*A feature selection approach would be to remove the said feature and redo the clustering and see if it had strong effect, if no you could say this feature is unnecessary for the clustering task. The down side of this approach is the time it would take to run the clustering process for each subset of features in the dataset.

*A statistical approach would be to split the data into two groups: the samples from the cluster and the rest of the samples. Then you ask how different are the feature values when comparing the two populations. Depends on the distribution of this feature, you could pick for this task a test like KS test, t test, chi-squared test or any other test for comparing distributions of two samples.


text:
Q: Why Spring Mvc application with Hibernate throw an error: Unable to acquire JDBC Connection I followed the tutorial on the following link:Tutorial Spring MVC, and I used Ubunto, MySQL and Eclipse, but at runtime I received an error, below the trace of the error:

Root Cause
org.springframework.transaction.CannotCreateTransactionException:
Could not open Hibernate Session for transaction; nested exception is
org.hibernate.exception.JDBCConnectionException: Unable to acquire
JDBC Connection
org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:541)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
org.o7planning.springmvcforms.controller.MyController$$EnhancerBySpringCGLIB$$32fb6e31.applicantList()
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:568)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859)
javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

And below the config properties file:
# DataSource

ds.database-driver=com.mysql.jdbc.Driver
ds.url=jdbc:mysql://localhost:3306/my_databse?autoReconnect=true&useSSL=false
ds.username=root
ds.password=mypassword

# Hibernate Config

hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
current_session_context_class=thread

And below the function used for configuration of Hibernate:
 @Bean(name = "dataSource")
 public DataSource getDataSource() {
     DriverManagerDataSource dataSource = new DriverManagerDataSource();

     dataSource.setDriverClassName(env.getProperty("ds.database-driver"));
     dataSource.setUrl(env.getProperty("ds.url"));
     dataSource.setUsername(env.getProperty("ds.username"));
     dataSource.setPassword(env.getProperty("ds.password"));

     return dataSource;
 }

And here is the function to create session Factory object:
@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource)throws Exception  {
    Properties properties = new Properties();
         // See: ds-hibernate-cfg.properties
     properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
     properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
     properties.put("current_session_context_class", env.getProperty("current_session_context_class"));

     LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
     factoryBean.setPackagesToScan(new String[] { "org.o7planning.springmvcforms.entity" });

     factoryBean.setDataSource(dataSource);
     factoryBean.setHibernateProperties(properties);
     factoryBean.afterPropertiesSet();
     //
    SessionFactory sf = factoryBean.getObject();
    return sf;
}

What is the source of this error?

A: I found the solution, for those who encounter the same problem.
Indeed the version of Mysql is 8.0.28,for this reason it is necessary to use the version 8.0.11 of Mysql connector and to use the configuration of driver under the bellow format:
ds.database-d=com.mysql.cj.jdbc.Driver

instead of
ds.database-d=com.mysql.jdbc.Driver

Hoping it can help


text:
Q: TypeError: member is not a function when using `${member}` I have a function to send a randomly chosen welcome message on Discord when a user join and also add a role to it and it used to work, but after updating to Discord.js v12, I get the error

*

*Welcome ${member}, that will be 6,99 $. Wanna pay cash or credit card?
^

TypeError: member is not a function*
when a user joins. Could someone help me, please? This is my code.
// When a member joins, this function executes.
bot.on('guildMemberAdd', (member) => {
    console.log('User ' + member.id + ' has joined the guild.');
    // Welcome messages possible options.
    let welcomeMessages = [`${member}, welcome to our server :wave:!\n\nNow you're **one of us** :new_moon_with_face:! \n\n`,
    `Welcome, ${member}. Hope you enjoy your stay.`, `Look who showed up... ${member}`, `Welcome ${member}, have a pleasant time.`,
    `So... ${member} just arrived.`, `Great... ${member} is here!`, `Everyone stand up! ${member} is here.`, `Hello daddy ${member}...`
    `Welcome ${member}, that will be 6,99 $. Wanna pay cash or credit card?`
    ];

    let welcomeChannel = member.guild.channels.cache.get(serverData.welcomeChannelId);
    let defaultRole = member.guild.roles.cache.get(serverData.defaultRoleId);

    // Both the welcome message and GIFs will be chosen randomly.
    let welcomeGif = welcomeGifs[Math.floor(Math.random() * welcomeGifs.length)];
    let welcomeMessage = welcomeMessages[Math.floor(Math.random() * welcomeMessages.length)];

    // This is the variable that stores the user profile picture for later use.
    let newUserIcon = member.user.displayAvatarURL;

    welcomeChannel.send(`${member}`);

    // This is my embedded message, which allows loads of customization.
    let welcomeMessageEmbed = new Discord.MessageEmbed()
      .setColor(Math.floor(Math.random() * 16777214) + 1) // The color will be random.
      .setDescription(welcomeMessage) // A message will be chosen randomly from the welcome messages tab.
      .setImage(welcomeGif) // Same with the GIF.
      .setThumbnail(newUserIcon) // The icon of the embedded message will be the user profile picture.

    // Send in the embed.
    welcomeChannel.send(welcomeMessageEmbed);

    // This is the default role.
    member.roles.add(defaultRole);
});

A: member is an object and you need a string. Try using member.displayName in the template literals instead.


text:
Q: The counter script should be running when the scroll reaches it ( JS), how can i make it? The task is to make a counter script on the site, I sort of managed to implement the counter script, but now I need it to work by scrolling. Help please, how can I add a scrolling event to this counter script so that it fires 1 time when I scroll to it?
========================================================================

  const counters = document.querySelectorAll('.number');
    counters.forEach((number) => {
    number.innerHTML = "0";

        const updateCounter = () => {
            const target = +number.getAttribute("data-target");
            const c = +number.innerText;

            if (c < target) {
                number.innerText = c + 1;
                setTimeout(updateCounter, 100);
            } else {
                number.innerText = target;
            }
        };
        updateCounter();
    })
* {
 box-sizing: border-box;
 background-color: gray;
 margin: 20px auto;
}

.long-text {
  font-size: 16px;
  max-width: 500px;
  text-align: center;
}

.form-count {
  max-width: 324px;
  padding-left: 15px;
  color: #fff;
  font-weight: 900;
  text-align: center;
}

.form-count__title {
  font-size: 30px;
  line-height: 36px;
}

.number-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 50px 0;
}

.thousand {
  font-weight: 900;
  font-size: 96px;
  text-align: center;
  color: #c40b0b;
}

.number {
  font-weight: 900;
  font-size: 96px;
  line-height: 56px;
  text-align: center;
  color: #c40b0b;
}

.form-count__text {
  font-size: 19px;
  line-height: 26px;
}

 Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo.

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo

  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo

  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo

  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo

  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo

  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo

  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo
  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo

    k

A: The trick for you will be Intersection Observer
You can see that I added an Observer for the number items
and when they appear 100% in the viewport you the counter will start.
It will also stop the moment you scroll out of the viewport event partially.
This is due to the threshold being set to 1.0. You can play with it as you need

const counters = document.querySelectorAll('.number');

const updateCounter = (number, e) => {
  const target = +number.getAttribute("data-target");
  const c = +number.innerText;

  if (c < target && e.intersectionRatio === 1) {
    number.innerText = c + 1;
    setTimeout(() => updateCounter(number, e), 100);
  }
};

function createObserver(number) {
  let observer;

  let options = {
    threshold: 1
  };

  observer = new IntersectionObserver(([e]) => updateCounter(number, e), options);
  observer.observe(number);
}

counters.forEach(number => {
  number.innerHTML = "0";
  createObserver(number)
})
* {
 box-sizing: border-box;
 background-color: gray;
 margin: 20px auto;
}

.long-text {
  font-size: 16px;
  max-width: 500px;
  text-align: center;
}

.form-count {
  max-width: 324px;
  padding-left: 15px;
  color: #fff;
  font-weight: 900;
  text-align: center;
}

.form-count__title {
  font-size: 30px;
  line-height: 36px;
}

.number-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 50px 0;
}

.thousand {
  font-weight: 900;
  font-size: 96px;
  text-align: center;
  color: #c40b0b;
}

.number {
  font-weight: 900;
  font-size: 96px;
  line-height: 56px;
  text-align: center;
  color: #c40b0b;
}

.form-count__text {
  font-size: 19px;
  line-height: 26px;
}

 Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo.

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo

  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo

  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo

  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo

  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo

  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo

  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo
  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illoLorem ipsum, dolor sit amet consectetur adipisicing elit. Sint enim non animi nam aliquid repudiandae vel quod quaerat? Quasi maiores reprehenderit minus deserunt deleniti illo

    k


text:
Q: CodeIgniter Can not open view I am just started with CodeIgniter and one interesting think is when I press button "Read More" i get error "404 Page Not Found The page you requested was not found."
Just looking inside the code but cannot find any mistake
Any comment, help ?
Posts controller
 <?php

class Posts extends CI_Controller{

    public function index($page='home'){

        $data['title']= 'Sve voznje';

        $data['posts'] = $this->Posts_model->get_posts();

        $this->load->view('templates/header');
        $this->load->view('posts/index',$data);
        $this->load->view('templates/footer');
    }

    public function view($mjesto_polaska=NULL){
        $data['posts'] = $this->Posts_model->get_posts($mjesto_polaska);
        if(empty($data['post'])){
            show_404();
        }
        $data['title'] = $data['mjesto_polaska'];

        $this->load->view('templates/header');
        $this->load->view('posts/view',$data);
        $this->load->view('templates/footer');
    }

    public function create(){
        $data['title'] ='Create Posts';

        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('body', 'Body', 'required');

        if($this->form_validation->run()===FALSE){

            $this->load->view('templates/header');
            $this->load->view('posts/create');
            $this->load->view('templates/footer');

        }else {
            $this->Posts_model->create_post();
            redirect('posts');
        }

    }

    public function delete($id){
        $this->Posts_model->delete_post($id);
        redirect('posts');
    }
}

Posts Model
<?php
 class Posts_Model extends CI_Model{

    public function __construct(){
        $this->load->database();
    }

    public function get_posts($mjesto_polaska=FALSE){
        if($mjesto_polaska === FALSE){
            $this->db->order_by('id','DESC');
            $query=$this->db->get('posts');
            return $query->result_array();
        }
        $query=$this->db->get_where('posts', array('mjesto_polaska' => $mjesto_polaska));
        return $query->row_array();
    }

    public function create_post(){
        $mjesto_polaska=url_title($this->input->post('title'));

        $data=array(
                'mjesto_polaska'=>$mjesto_polaska,
                'mjesto_odredista'=>$this->input->post('mjesto_odredista'),
                'datum_polaska'=>$this->input->post('datum_polaska'),
                'datum_povratka'=>$this->input->post('datum_povratka'),
                'cijena'=>$this->input->post('cijena'),
                'broj_mjesta'=>$this->input->post('broj_mjesta'),
                'opis'=>$this->input->post('opis'),

        );
        return $this->db->insert('posts',$data);
    }

    public function delete_posts($id){
        $this->db->where('id',$id);
        $this->db->delete('posts');
        return true;
    }
 }

index.php

<?= $title?>

<?php foreach($posts as $post) :?>

<?php echo  $post['mjesto_polaska']; ?>

Posted on: <?php echo $post['created_at']; ?>

<a class="btn btn-default"    href="<?php echo site_url('/posts'.$post['mjesto_polaska']);?>">Read More

<a class="btn btn-default"    href="<?php echo site_url('/posts'.$post['id']);?>">Delete

<?php endforeach;?>

view.php

<?php echo $posts['title'];?>

Posted on:<?php echo post['created_at'];?>

<?php echo $post['body'];?>

<?php form_open('/posts/delete'.$post['id']);?>
<input type="submit" value="Delete" class="btn btn-danger">
</form>

routes.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$route['posts/create']='posts/create';
$route['posts/(:any)'] = 'posts/view/$1';
$route['posts']='posts/index/$1';
$route['default_controller'] = 'pages/view';
$route['(:any)'] = 'pages/view/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

A: I made some changes in files. You can check and let me know if it is working there. Don't forget to load url and form helpers in config autoload file since you are using some in model too (url_title). Also fill constructor method in controller too.
routes.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
// default routes should be at first place
$route['default_controller'] = 'pages/view';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

$route['posts']='posts/index/$1';
$route['posts/create']='posts/create';
$route['posts/(:any)'] = 'posts/view/$1';

$route['(:any)'] = 'pages/view/$1';

index.php view file

<?= $title?>

<?php foreach($posts as $post) :?>

<?php echo  $post['mjesto_polaska']; ?>

Posted on: <?php echo $post['created_at']; ?>

<a class="btn btn-default"    href="<?php echo
site_url('/posts/'.$post['mjesto_polaska']);?>">Read More

<a class="btn btn-default"    href="<?php echo
site_url('/posts/delete/'.$post['id']);?>">Delete

<?php endforeach;?>

view.php view file

<?php echo $posts['title'];?>

Posted on:<?php echo post['created_at'];?>

<?php echo $post['body'];?>

<?php form_open('/posts/delete/'.$post['id']);?>
    <input type="submit" value="Delete" class="btn btn-danger">
</form>


text:
Q: Why is my application returning the IIS 404 page on my dev environment but not test or production? OK, so I develop my application locally at http://dev.myapplication.com (using hosts file for the DNS), and then I have http://test.myapplication.com and http://www.myapplication.com.
In IIS 7 (same version, dev test and live), I've opened 'Error Pages' and edited the 404 status code to go to path '/en/404.mvc'.  This works locally and I can navigate to http://dev.myapplication.com/non-existent-url.mvc which produces the 404 page.
However, if I navigate to http://dev.myapplication.com/non-existent-url (ie a static address) it shows the IIS 404 page and says it was handled by the static file handler rather than my mvc file handler.
I'm baffled as to why this happens, as it has successfully modified my web.config which in turn allows it to work on test and live, just not locally.  i.e. http://www.myapplication.com/404 will show my customized 404 page

A: You need a wildcard mapping to run all requests through aspnet_isapi - this article explains it nicely: http://www.asp.net/mvc/tutorials/older-versions/deployment/using-asp-net-mvc-with-different-versions-of-iis-cs
Also, check your web.Config has these settings:
<system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>


text:
Q: Xamarin EntryRenderer NSTextField Change Cursor Color As I was trying to modify an entry with no border and modify the background color, I've notice that there is no implementation on NSTextfield that could access the cursor. Is there any work around on how to modify the cursor color?
PS : NSTextView has the capability but NSTextfield is not the same as NSTextView.
If I put white background on the textfield (which is the default or common color), cursor is also white which make it invincible.


text:
Q: Free dynamic bidimensional matrix in C I made a code which allocs 2 int matrices, and frees in the end, after use. When I disalloc the first matrix, it works fine. In the second, the error:

munmap_chunk(): invalid pointer: 0x0829a068 ***Abortado (imagem do núcleo gravada)

I can't find where the error is.
#include <stdio.h>
#include <stdlib.h>

int **AlocaMatriz (int linha, int coluna) {
    int **m, i, j;

    m = (int **) malloc (linha * sizeof(int *));

    for (i = 0; i < linha; i++) {
        m[i] = (int *) malloc (coluna * sizeof(int ));
    }

    /*inicializa matriz*/
    for (i = 0; i < linha; i++) {
        for (j = 0; j < coluna; j++) {
            m[i][j] = 0;
        }
    }

    return(m);
}

int **DesalocaMatriz (int linha, int coluna, int** m) {
    int i;
    for (i = 0; i < linha; i++) {
        free (m[i]);
    }
    free (m);
    return(NULL);
}

int main() {

    int i, j, numLinhas, numColunas, numInstancias, **matriz, **somas, resultado = 0;

    scanf("%d", &numInstancias);

    while (numInstancias > 0) {

        scanf("%d %d", &numLinhas, &numColunas);

        matriz = AlocaMatriz(numLinhas, numColunas);
        somas = AlocaMatriz(numLinhas, numColunas);

        //some operations on both matrices

        DesalocaMatriz(numLinhas, numColunas, matriz);
        DesalocaMatriz(numLinhas, numColunas, somas);
        numInstancias--;
    }

    return 0;
}

A: Once you have a two dimensional array, you have a pointer to a pointer. In order to free the memory allocated to this array, you need to free the secondary arrays before the first array. Do it like this...
int **array;
int size1 = sizeof(array)/sizeof(array[0]);
for(int i=0; i<size1; i++) {
    free(array[i]);
}
free(array);

You should also know that once a program ends, all of the allocated memory is automatically freed.
You can dynamically allocate an array by doing this...
array = malloc(size1 * sizeof(int*));
    for (int i = 0; i < size1; i++) {
            array[i] = malloc(size2 * sizeof(int));
    }

This should give an array that can be accessed like this...
array[0-size1][0-size2];

A: check the return of malloc to see if it succeeded or failed.
#include <stdio.h>
#include <stdlib.h>

int **AlocaMatriz (int linha, int coluna) {
    int **m = NULL, i, j;

    if ( ( m = malloc (linha * sizeof(int *))) != NULL) {//not NULL is success

        for (i = 0; i < linha; i++) {
            if ( ( m[i] = malloc (coluna * sizeof(int ))) == NULL) {//NULL is failure
                while ( i) {//free allocated so far
                    i--;
                    free ( m[i]);
                }
                free ( m);
                return NULL;
            }
        }

        /*inicializa matriz*/
        for (i = 0; i < linha; i++) {
            for (j = 0; j < coluna; j++) {
                m[i][j] = 0;
            }
        }
    }

    return(m);
}

int **DesalocaMatriz (int linha, int coluna, int** m) {
    int i;
    for (i = 0; i < linha; i++) {
        free (m[i]);
    }
    free (m);
    return(NULL);
}

int main() {

    int i, j, numLinhas, numColunas, numInstancias, **matriz, **somas, resultado = 0;

    scanf("%d", &numInstancias);

    while (numInstancias > 0) {

        scanf("%d %d", &numLinhas, &numColunas);

        matriz = AlocaMatriz(numLinhas, numColunas);
        somas = AlocaMatriz(numLinhas, numColunas);

        //some operations on both matrix

        if ( matriz) {//if not NULL
            DesalocaMatriz(numLinhas, numColunas, matriz);
        }
        if ( somas) {//if not NULL
            DesalocaMatriz(numLinhas, numColunas, somas);
        }
        numInstancias--;
    }
    return 0;
}


text:
Q: Importance of order in registering provider and configuring a module in angular.js it seems that from angular's point of view the order of registering of a service provider and the module configuration code is important: in order for the configuration code to find the provider, the provider should be registered before.
This was a total surprise for me, as I thought that angular first processes all provider registrations, to make them available for DI, and then calls config callbacks, like this:
module.config(function(myServiceProvider) {...});
Please see here a very short test that demonstrates the problem. It fails on "unknown provider", you can see it in the JS console: http://plnkr.co/edit/jGJmE2Fq7wOrwubdlTTX
Am I missing anything here? Is it an expected angular behavior?
Thanks.

A: Looks like this behavior has changed in more recent versions of Angular (not sure when exactly). I modified your Plunker to point from 1.0.7 to 1.3.0 and it worked without error as you had originally expected.
Similar example of code that works:
    var myModule = angular.module('myModule', []);
myModule.config((myServiceProvider) => {
});

myModule.service('myService', () => {
});

Running a config for a provider before the provider is registered with the module should work just fine as you were expecting.
Reference
For reference, this reported issue appears to be the one to have fixed it: https://github.com/angular/angular.js/issues/6723

A: The Angular documentation for module state that:

Recommended Setup
  While the example above is simple, it will not scale to large applications. Instead we recommend that you break your
  application to multiple modules like this:

*

*A service module, for service declaration

*A directive module, for directive declaration

*A filter module, for filter declaration

*And an application level module which depends on the above modules, and which has initialization code.

As you are using a single module that you call app, you are creating a dependency between that module's config and declaration of a provider.  What you should have done is to place all your providers into a separate module, such as:
var appr = angular.module('appr', [])
  .provider('myService', function() {
    this.$get = function() {};
  })

Then you declare the dependency of your app using:
var app = angular.module('plunker', ['appr']);

Check out the updated Plunker: http://plnkr.co/edit/Ym3Nlsm1nX4wPaiuVQ3Y?p=preview
Also, instead of using the generic provider, consider using more specific implementation of provider such as controller, factory or service.  Take a look at Module API documentation for more detail.


text:
Q: Are there any clojure tools to see how Clojure uses JVM memory? I would like to be able to analyze my Clojure program to see how the memory is used. Are there any tools to do this?
Update: I have tried the JVM tools mentioned in the answers but none of these tools allow me to visualise any of my clojure data structures, although they do give me some indication

A: jvisualvm allows you to do that

A: Perform a jvm heap dump using jmap. You can then load the dump into Eclipse Memory Analyser which will show you where memory is being used. Alternatively, you can just use jhat to browse the heap dump.


text:
Q: Hacer consulta mysql al cargar pagina y mostrar resultado en un modal Requiero que al cargar una página html se haga una consulta a la base de datos mysql, y constatar si el valor dentro de un campo es 0 (0 negado, 1 autorizado); para luego mostrar un modal indicando que se debe realizar completar el registro para la autorización de acceso. Además, que el modal se muestre cada hora hasta que el valor del campo sea 1 y no se vuelva a mostrar.
He intentado varias cosas infructuosamente, y requiero de su gran ayuda
Aquí parte del script que tengo para mostrar el modal cada hora
<?php
$muestraModal = false;
if(!isset($_COOKIE["verModal"])) {
$expirar = 3600;
setcookie('verModal', 'SI', (time() + $expirar));
$muestraModal = true;
}
?>

Modal title

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

if($exibirModal === true) { ?>

  <?php
}

Gracias por la ayuda

A: He resuelto la dificultad haciendo una consulta a la base de datos, y utilizando la condicional if-else, constato el contenido del campo, y así, dependiendo del resultado
 debe mostrar el modal o no.
Ésta es la consulta que ejecuto al cargar la pagina:
function getCorpsys() {
  $mysqli=conectaSQL();
  $mysqli->set_charset("utf8");
  $query=$mysqli->query("SELECT * from tblcorpsystem");
  while ($array=$query->fetch_array(MYSQLI_ASSOC)) {
    if ($array['corpIsReg']==0) {
      echo "Aqui coloque el script que muestra el modal cada hora";
    }
  }
  return $corpo;
  $desconectaSQL;
}

Y así he resuelto mis dudas.


text:
Q: How can I get when the button is clicked? I use wxwidget with erlang.
init() ->
    Wx=wx:new(),
    F=wxFrame:new(Wx, -1, "Hello, World!"),
    Panel = wxPanel:new(F),
    wxButton:new(Panel, 12, [{label,"Default"}]),
    wxFrame:show(F).

If I click on the button nothing is doing, I want to do something, execute a function for example. How can I do that?
Thanks
Best regards

A: Here's an example in the shell.
First, create a window with a button, which you have already:
1> Wx = wx:new().
{wx_ref,0,wx,[]}
2> Frame = wxFrame:new(wx:null(), -1, "Hello, World!").
{wx_ref,35,wxFrame,[]}
3>
3> Panel = wxPanel:new(Frame).
{wx_ref,36,wxPanel,[]}
4>
4> Button = wxButton:new(Panel, 12, [{label,"Default"}]).
{wx_ref,37,wxButton,[]}

Now you can register a callback. In this case I am just printing out the data passed to the callback:
5> wxButton:connect(Button, command_button_clicked, [{callback,
5>         fun(Evt, Obj) ->
5>             io:format("click~n  event = ~p~n  obj = ~p~n", [Evt, Obj])
5>             end
5>         }]).
ok

Display the window:
6> wxFrame:show(Frame).
true
7>

Now, when you click the button, you should see:
click
  event = {wx,12,
              {wx_ref,37,wxButton,[]},
              [],
              {wxCommand,command_button_clicked,[],0,0}}
  obj = {wx_ref,39,wxCommandEvent,[]}
7>

Edit (notes concerning OTP):
When you implement a more fully OTP style application with wx you may want to do something slightly different, because you don't want that fun hanging around. Instead you can have a message sent to you when the button is clicked. If you omit the 'callback' option to connect then the event will be delivered to the process that calls connect instead. So you could have done:
5> wxButton:connect(Button, command_button_clicked, []).
ok

If you do that, and click the button, your (shell in this case) process will receive a message:
7> receive Msg -> Msg after 0 -> timeout end.
{wx,12,
    {wx_ref,37,wxButton,[]},
    [],
    {wxCommand,command_button_clicked,[],0,0}}
8>

A: The attached link explains how to handle events in general with wxWidgets but it also discusses wxbutton and its click event.  There is some sample code there as well.  Hope this helps.
wxWidget Event Handling


text:
Q: jquery file returning errors in netbeans I've downloaded the lastest jquery file from the jquery website and I've installed the file into my php project. I'm currently using Netbeans IDE 8.0 and jquery-2.1.1.min.js
When I open the jquery file to view its contents it returns numerous errors.
Main Errors:

expected semicolon; after ")"
  expected "===" and instead saw "=="
  expected a conditional expression and instead saw an assignment
  expected semicolon; after "b"
  expected semicolon; after "c"

Netbeans or JQuery issue? Any help would be appreciated. Thanks!

A: These are just linting errors. The script will work fine, but Netbeans is just recommending you make those changes to make it more readable, which you don't need as it is a minified file. Basically don't worry about it.


text:
Q: How can I make a function that counts the total orders I have made and adds the price up? I prompt the user if they want to order fish, once they are done ordering fish, they are asked to order chips, and then drinks. Once drinks is done, I need a total of all prices and then I need to list them.
Problem is, I don't know how to "tally" up all the totals. How would I go about writing a function to tally up subtotals?
The way my program gets the subTotal is:
subTotal(typeOfFood, foodChoice, foodSize, foodOrders);

In my subtotal function it just has subtotal+= $x.xx based on what type of food they chose.
I tried making a function like this:
float accumTotal(int total) {
    float finalTotal;
    finalTotal += total;
    return finalTotal;
}
but that didn't work.
OUTPUT of my proglram:
Do you order FISH (Y/N)? y
Fish choice (K- Haddock, T- Halibut): t
What size (L-Large, M-Medium, S-Small): l
How many orders do you want? (>=0): 2
You ordered: [fish]: [Halibut], Size: [Large], ordered: [2], subtotal: [8.00]

Do you order FISH (Y/N)? y
Fish choice (K- Haddock, T- Halibut): t
What size (L-Large, M-Medium, S-Small): s
How many orders do you want? (>=0): 2
You ordered: [fish]: [Halibut], Size: [Small], ordered: [2], subtotal: [4.80]

Do you order FISH (Y/N)? n

Do you order CHIPS (Y/N)? y
Chips choice (C- Cut, R- Rings): r
What size (L-Large, M-Medium, S-Small): m
How many orders do you want? (>=0): 5
You ordered: [chips]: [Ring], Size: [Medium], ordered: [5], subtotal: [12.00]

Do you order CHIPS (Y/N)? n

Do you order DRINKS (Y/N)? n
============================
ACCUMULATIVE TOTAL = $x.xx

SOURCE: though not really necessary
#include <stdio.h>
#include <string.h>
int processing(char *typeOfFood, char foodChoice, char foodSize, int foodOrders);
float subTotal(char *typeOfFood, char foodChoice, char foodSize, int foodOrders);
float accumTotal(int total);

float subTotal(char *typeOfFood, char foodChoice, char foodSize, int foodOrders) {

    float subTotal = 0;

    if ((strcmp(typeOfFood, "fish")) == 0) {
        if (foodChoice == 'k' || foodChoice == 'K') {
            if (foodSize == 's' || foodSize == 'S') {
                subTotal += 3.00;
            }
            else if (foodSize == 'm' || foodSize == 'M') {
                subTotal += 4.00;
            }
            else if (foodSize == 'l' || foodSize == 'L'){
                subTotal += 5.00;
            }
        }
        else if (foodChoice == 't' || foodChoice == 'T') {
            if (foodSize == 's' || foodSize == 'S') {
                subTotal += 2.40;
            }
            else if (foodSize == 'm' || foodSize == 'M') {
                subTotal += 3.20;
            }
            else if (foodSize == 'l' || foodSize == 'L'){
                subTotal += 4.00;
            }
        }
    }
    if ((strcmp(typeOfFood, "chips")) == 0) {
        if (foodChoice == 'c' || foodChoice == 'C') {
            if (foodSize == 's' || foodSize == 'S') {
                subTotal += 1.20;
            }
            else if (foodSize == 'm' || foodSize == 'M') {
                subTotal += 1.60;
            }
            else if (foodSize == 'l' || foodSize == 'L'){
                subTotal += 2.00;
            }
        }
        else if (foodChoice == 'r' || foodChoice == 'R') {
            if (foodSize == 's' || foodSize == 'S') {
                subTotal += 1.80;
            }
            else if (foodSize == 'm' || foodSize == 'M') {
                subTotal += 2.40;
            }
            else if (foodSize == 'l' || foodSize == 'L'){
                subTotal += 3.00;
            }
        }
    }
    if ((strcmp(typeOfFood, "drink")) == 0) {
        if (foodChoice == 's' || foodChoice == 'S') {
            if (foodSize == 's' || foodSize == 'S') {
                subTotal += 1.20;
            }
            else if (foodSize == 'm' || foodSize == 'M') {
                subTotal += 1.60;
            }
            else if (foodSize == 'l' || foodSize == 'L'){
                subTotal += 2.00;
            }
        }
        else if (foodChoice == 'c' || foodChoice == 'C') {
            if (foodSize == 's' || foodSize == 'S') {
                subTotal += 1.05;
            }
            else if (foodSize == 'm' || foodSize == 'M') {
                subTotal += 1.40;
            }
            else if (foodSize == 'l' || foodSize == 'L'){
                subTotal += 1.75;
            }
        }
        else if (foodChoice == 't' || foodChoice == 'T') {
            if (foodSize == 's' || foodSize == 'S') {
                subTotal += 0.90;
            }
            else if (foodSize == 'm' || foodSize == 'M') {
                subTotal += 1.20;
            }
            else if (foodSize == 'l' || foodSize == 'L'){
                subTotal += 1.50;
            }
        }
    } // ifs

    subTotal = subTotal * foodOrders;
    return subTotal;

}

float accumTotal(int total) {

    // float finalTotal;

    // finalTotal += total;
    // printf("[%lf]", finalTotal);
    // return finalTotal;
}

int processing(char *typeOfFood, char foodChoice, char foodSize, int foodOrders){

    char *foodSizeSelect, *foodChoiceSelect;
    float total = subTotal(typeOfFood, foodChoice, foodSize, foodOrders);

    if ((strcmp(typeOfFood, "fish")) == 0){
        switch (foodChoice) {
            case 'k':
                foodChoiceSelect = "Haddock";
            break;
            case 'K':
                foodChoiceSelect = "Haddock";
            break;
            case 't':
                foodChoiceSelect = "Halibut";
            break;
            case 'T':
                foodChoiceSelect = "Halibut";
            break;
        }
    }
    else if ((strcmp(typeOfFood, "chips")) == 0){
        switch (foodChoice) {
            case 'c':
                foodChoiceSelect = "Cut";
            break;
            case 'C':
                foodChoiceSelect = "Cut";
            break;
            case 'r':
                foodChoiceSelect = "Ring";
            break;
            case 'R':
                foodChoiceSelect = "Ring";
            break;
        }
    }
    else if ((strcmp(typeOfFood, "drinks")) == 0){
        switch (foodChoice) {
            case 's':
                foodChoiceSelect = "Softdrink";
            break;
            case 'S':
                foodChoiceSelect = "Softdrink";
            break;
            case 'c':
                foodChoiceSelect = "Coffee";
            break;
            case 'C':
                foodChoiceSelect = "Coffee";
            break;
            case 't':
                foodChoiceSelect = "Tea";
            break;
            case 'T':
                foodChoiceSelect = "Tea";
            break;
        }
    }
    switch (foodSize) {
        case 's':
            foodSizeSelect = "Small";
        break;
        case 'S':
            foodSizeSelect = "Small";
        break;
        case 'm':
            foodSizeSelect = "Medium";
        break;
        case 'M':
            foodSizeSelect = "Medium";
        break;
        case 'l':
            foodSizeSelect = "Large";
        break;
        case 'L':
            foodSizeSelect = "Large";
        break;
    }

    printf("You ordered: [%s]: [%s], Size: [%s], ordered: [%d], subtotal: [%.2lf]\n\n", typeOfFood, foodChoiceSelect, foodSizeSelect, foodOrders, total);

}

int main() {

    char fishYesNo, chipsYesNo, drinksYesNo;
    char fishChoice, fishSize; int fishOrders;
    char chipsChoice, chipsSize; int chipsOrders;
    char drinksChoice, drinksSize; int drinksOrders;

    char *typeOfFood;

    do {
        typeOfFood = "fish";
        printf("Do you order FISH (Y/N)? ");
        scanf(" %c", &fishYesNo);
        if (fishYesNo != 'n' || fishYesNo != 'n') {
            printf("Fish choice (K- Haddock, T- Halibut): ");
                scanf(" %c", &fishChoice);
            printf("What size (L-Large, M-Medium, S-Small): ");
                scanf(" %c", &fishSize);
            printf("How many orders do you want? (>=0): ");
                scanf("%d", &fishOrders);
            processing(typeOfFood, fishChoice, fishSize, fishOrders);
        }
        else if (fishYesNo == 'n' || fishYesNo == 'N') {
            typeOfFood = "chips";
        }

    } while ((strcmp(typeOfFood, "fish")) == 0);

    do {
    typeOfFood = "chips";
        printf("Do you order CHIPS (Y/N)? ");
        scanf(" %c", &chipsYesNo);
        if (chipsYesNo != 'n') {
            printf("Chips choice (C- Cut, R- Rings): ");
                scanf(" %c", &chipsChoice);
            printf("What size (L-Large, M-Medium, S-Small): ");
                scanf(" %c", &chipsSize);
            printf("How many orders do you want? (>=0): ");
                scanf("%d", &chipsOrders);
            processing(typeOfFood, chipsChoice, chipsSize, chipsOrders);
        }
        else if (chipsYesNo == 'n' || chipsYesNo == 'N') {
            typeOfFood = "drinks";
        }

    } while ((strcmp(typeOfFood, "chips")) == 0);

    do {
    typeOfFood = "drinks";
        printf("Do you order DRINKS (Y/N)? ");
        scanf(" %c", &drinksYesNo);
        if (drinksYesNo != 'n') {
            printf("Drinks choice (S- Softdrink, C- Coffee, T- Tea): ");
                scanf(" %c", &drinksChoice);
            printf("What size (L-Large, M-Medium, S-Small): ");
                scanf(" %c", &drinksSize);
            printf("How many orders do you want? (>=0): ");
                scanf("%d", &drinksOrders);
            processing(typeOfFood, drinksChoice, drinksSize, drinksOrders);
        }
        else if (drinksYesNo == 'n' || drinksYesNo == 'N') {

        }

    } while ((strcmp(typeOfFood, "drinks")) == 0);

}

A: What you need is a tracking variable to keep count of the running total:
void processing(char *typeOfFood, char foodChoice, char foodSize, int foodOrders, float *subTotal)
{
    ...
    printf("You ordered: [%s]: [%s], Size: [%s], ordered: [%d], subtotal: [%.2lf]\n\n", typeOfFood, foodChoiceSelect, foodSizeSelect, foodOrders, total);
    *subTotal += total; // add to the total.
}

int main () {
   ...
   char *typeOfFood;
   float subTotal = 0.0f;
   ...

   ...
   // for each call to 'processing'
   processing(typeOfFood, fishChoice, fishSize, fishOrders, &subTotal);
   ...

   ...
   // when the drinks are done:
   else if (drinksYesNo == 'n' || drinksYesNo == 'N') {
        printf("your bill totals to $%.2f", subTotal);
        break;   // note the added 'break' so that the program exits.
   }
   ...
}


text:
Q: Construct a bounded set of reals with exactly three limit points I tried doing that, but I didn't get anything at all.
Could you provide me with some hints?
What I'm sure of Is that, such a set doesn't contain any interval and it's infinite so I think it's a set like cantor's one or something like that.

A: Hint: Consider the set $\{ 1/n : n\in\mathbb{N}\}$.  Can you use this set to solve the problem?


text:
Q: Using math in browser using XML data I'm trying to make pull XML or Csv data into a HTML file then I want to use math to add up the values and show the result on the page ( I'm basically trying to display invoices on a web browser)
My skill set is HTML/CSS and I understand a little JavaScript
I've managed to pull XML data into HTML using http request and style that information using xslt
Really what I'm asking is what is the best solution to my needs is it using the above method then using xquiry to add up values or would I need to learn a bit of Ajax, Json and calculate the values with JavaScript?

A: You really should learn AJAX in order to fetch and manipulate data instead of fetching presentation parts. That's the way everyone follows as it allows more responsive interactions with the user and a cleaner architecture in case of complex interactions.
But that doesn't mean you must abandon XML : originally AJAX was built on XML (the X in AJAX) and not JSON.
Personally I prefer JSON, and I think it will be easier to manage in the long term, but if the server side is hard to change, you can fetch the XML (look for example at jquery's ajax function), build javascript objects using it, and then change your screen using those data. If later you decide to use JSON instead of XML, you'll just have to change the "parsing" part of the client code.

A: "I'm trying to make pull XML or Csv data into a HTML file then I want to use math to add up the values and show the result on the page"
You can do this with either XSLT or javascript. However, with XSLT things can become pretty complicated, depending on what version you're using. XSLT 1.0 has pretty limited set of functions for aggregating results. For all XSLT, you can't reassign variables you'll have to solve many of these things with recursion. In my opinion, not really a comfortable method.
Regardless of the choice between XSLT and Javascript, I would also question the architecture that would put this kind of logic in the presentation layer in the browser. I think it would be better if the server side would perform all the calculations that are required, and limit the browser's tasks to styling the output.


text:
Q: how to set the text position in pdfbox i have use pdfbox for creating pdf but not getting sure how to set the text in x and y it will not come in proper format
PDDocument document=new PDDocument();
    PDPage blank=new PDPage();
    PDFont font=PDType1Font.HELVETICA_BOLD;
    document.addPage(blank);

    PDPageContentStream content=new PDPageContentStream(document, blank);
    content.beginText();
    int i=0;
    int  x=20;
    int y=700;
while(i<5){
content. newLineAtOffset(x, y);
            content.setFont(font, 12);
            content.showText(id);
            content.showText(role);
            i++;
            y=-20;
}
content.endText();
content.close();
document.save("BlankPage.pdf");
document.close();[it will increase x and i dont want to increase possition of x][1]

  [1]: http://i.stack.imgur.com/Q1A6I.jpg

A: Unfortunately the OP has not explained what exactly he means by not coming in proper format.
Looking at his code, though, it seems like he thinks
content.newLineAtOffset(x, y);

will position the new line at the given x, y as absolute coordinates. This is not the case. Instead x, y are relative to the previous line coordinates which are set to 0, 0 in the PDF instruction generated by content.beginText().
This actually already is hinted at by the Offset in newLineAtOffset and made clear in the JavaDocs:
/**
 * The Td operator.
 * Move to the start of the next line, offset from the start of the current line by (tx, ty).
 *
 * @param tx The x translation.
 * @param ty The y translation.
 * @throws IOException If there is an error writing to the stream.
 * @throws IllegalStateException If the method was not allowed to be called at this time.
 */
public void newLineAtOffset(float tx, float ty) throws IOException

Thus, most likely he wants do something like
int x=20;
int y=700;
content.beginText();
content.setFont(font, 12);
content.newLineAtOffset(x, y);
for (int i=0; i<5; i++)
{
    content.showText(id);
    content.showText(role);
    content.newLineAtOffset(0, -20);
}
content.endText();


text:
Q: How to open a pull request against an upstream repo using BitBucket Api? Let's say I have a workspace and repo called acme/widget, and I have a fork of that called brianc/widget. Using the BitBucket api, how can I create a pull request from my repo to the upstream?
In the docs there doesn't seem to be a way to do this kind of cross-repo pull request creation, since it seems that branch is the only variable allowed. Any ideas?


text:
Q: Creating a VS .Net 2003 property macro/variable I'd like to create a macro/variable for my project properties, similar to $(ConfigurationName), $(OutDir), etc - without making environment variables.  I've found that this can be done in later versions of Visual Studio, but I do not have the option of updating my IDE.  Can this be done in the .Net 2003 version (if so, how?) - or is the only way to do this through environment variables?

A: Turns out this cannot be done in VS .Net 2003 except by using environment variables.


text:
Q: Open Existing DB in MySQL WorkBench I got a DB files that created in My SQL , and I want open them in My SQL WorkBench 6.1.
The files I got contains : FRM ,MYD , MYI for each table, and another file calls db.opt.
how can I import that to the workbench?

thanks.

A: so first you restore the database in mysql server like explained in the linked anwser. Then you connect the workbench tool to you mysql server to open your database, note sometimes the word schema is used for "database".
to do so you need to create a database connection in workbench, i am just away from my machine. restoring the database in mysql server needs to be done before you can import / sync / reverse engineer the schema into workbench model.


text:
Q: Docker Hub login failed with status 404 Not Found I am trying to login to Docker hub and pull an image. I tried for example
docker login store.docker.com
Username: myusername
Password: *****
Error response from daemon: login attempt to https://store.docker.com/v2/ failed with status: 404 Not Found

And I tried
docker login hub.docker.com
Username: myusername
Password: ***
Error response from daemon: login attempt to https://hub.docker.com/v2/ failed with status: 404 Not Found

So both store.docker.com and hub.docker.com produce an error 404 not found. I can log in to https://hub.docker.com using a browser using myusername. So my account looks fine.
What is the secret to pulling images from Docker hub? Is there an instruction, tutorial or training that describes the details of pulling and uploading images?
I am on Ubuntu 18.04. I can pull and push images to my own registry but somehow I lost the ability to pull from Docker hub when it no longer allowed anonymous pull requests.
[myuser:~] 130 $ docker --version
Docker version 18.09.1, build 4c52b90

As a workaround, is there a way to download images files? So I can upload to my own registry?

A: You should just write
docker login

A: If you specify the url, you should use https://index.docker.io. hub.docker.com and store.docker.com no longer work.


text:
Q: How to escape single quotes in JSP In my application I have a jsp page where the variables from server is assigned to the angular in client side. Please see the code below.
jsp
    <div ng-controller="HeaderController"
         ng-init="init( {   firstName: '${customerInfo.firstName}',
                            lastName: '${customerInfo.lastName}' }) >

Issue
If the name contains a single quotes,
     for example, if the firstName is d'souza, the code will be like this firstName: 'd'souza' which breaks. So how can this be escaped in JSP. Something like
{   firstName: 'escape(${customerInfo.firstName})',
                            lastName: '${customerInfo.lastName}' }

A: Simply use escapeJavaScript method of org.apache.commons.lang.StringEscapeUtils class. You have to include the common-lang library in your project, obviously.


text:
Q: Recaptcha for .NET Does Not Work in AJAX Request I want to use 'Recaptcha for .NET' in my ASP.NET MVC 4 application. I did instructions here. I use AJAX request to login the user through the following script:
$(".@loginGuid button[type=button]").click(function () {
      var wrapper = $(this).parents(".@loginGuid");
      wrapper.find(".has-error").removeClass("has-error");
      var dto = {
        Valid: true,
        UserName: wrapper.find(".user-name").val(),
        Password: wrapper.find(".password").val(),
        Remember: wrapper.find(".remember").is(":checked"),
      };

      if (!validateUserName(dto.UserName)) {
        dto.Valid = false;
        wrapper.find(".user-name").addClass("has-error");
      }
      if (dto.Password.length < 6) {
        dto.Valid = false;
        wrapper.find(".password").addClass("has-error");
      }

      if (dto.Valid) {

        $.ajax({
          url: "/Account/AjaxLogin",
          type: "post",
          data: JSON.stringify(dto),
          context: dto,
          dataType: "json",
          contentType: "application/json;charset=UTF-8",
          cache: false,
          statusCode: {
            404: function () {
              alert("page not found");
            },
            200: function () {
            }
          }
        }).done(function (result) {
          if (result) {
            if (result.Succeed) {
              window.location.reload();
            } else {
              $.map(result.Messages, function (item, index) {
                alert(item);
              });
            }
          }
        }).fail(function () {
        }).always(function () {

        });
      }
      return false;
    });

Here is my action method:
[HttpPost]
    [AllowAnonymous]
    public ActionResult AjaxLogin(string username, string password, bool remember)
    {
        ScriptResult scriptResult = new ScriptResult() { Succeed = true };

        RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
        RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
        if (recaptchaResult != RecaptchaVerificationResult.Success)
        {
            scriptResult.Messages.Add("Incorrect captcha answer.");
            scriptResult.Succeed = false;
        }
        else
        {
            var user = UserManager.Find(username, password);
            if (user != null)
            {
                user.UserName = user.UserName.ToLower();
                SignIn(user, remember);
            }
            else
            {
                scriptResult.Messages.Add(LocalizeHelper.GetLocalizeString("Invalid username or password."));
                scriptResult.Succeed = false;
            }
        }

        return Json(scriptResult);
    }

When I fill out the login form(username, password and captcha fields) and click the login button, then I get the following error:

An exception of type 'System.InvalidOperationException' occurred in
  Recaptcha.Web.dll but was not handled in user code
Additional information: Recaptcha challenge field cannot be empty.

A: The documentation you linked assumed a standard form post so the Recaptcha form values are likely pulled from Request.Form["x"] where x is a particular form field from the Recaptcha control. You are doing an AJAX request so you will need to pass these values explicitly yourself.
If you examine the html for the rendered Recaptcha control you will see two input fields.
<input id="recaptcha_challenge_field" ... />
<input id="recaptcha_response_field" ... />

These values will need to be passed in your AJAX request so your javascript becomes:
$.ajax({
    url: "/Account/AjaxLogin",
    type: "post",
    data: {
        recaptcha_challenge_field: $("#recaptcha_challenge_field").val(),
        recaptcha_response_field: $("#recaptcah_response_field").val(),
        ...
    }
})

Your controller action signature does not change
public ActionResult AjaxLogin(string username, string password, bool remember)

And you can verify the values are passed if you inspect inside your controller action
var challenge = Request.Form["recaptcha_challenge_field"];
var answer = Request.Form["recaptcha_response_field"];

From the actual source code we see that the RecaptchaVerificationHelper's values are taken from the Request:
HttpRequest request = HttpContext.Current.Request;
...
this._Challenge = request.Form["recaptcha_challenge_field"];
this.Response = request.Form["recaptcha_response_field"];

You do not need to do anything more than POST the values to your action then call recaptchaHelper.VerifyRecaptchaResponse(). Since you are not doing standard form submission the javascript above will send the values via the AJAX post.


text:
Q: Elliptic curve key wrapping/encapsulation using Java From my research I learned that this is the correct way to wrap an AES session key using RSA:
import java.security.*;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class Main {
    public static void main(String args[]) throws Exception {
        KeyGenerator aesKeyGen = KeyGenerator.getInstance("AES");
        aesKeyGen.init(256);
        SecretKey secretKey = aesKeyGen.generateKey();

        Base64.Encoder encoder = Base64.getEncoder().withoutPadding();
        Cipher cipher = Cipher.getInstance("RSA");
        KeyPairGenerator rsaKeyGen = KeyPairGenerator.getInstance("RSA");
        rsaKeyGen.initialize(4096);
        KeyPair keyPair = rsaKeyGen.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        cipher.init(Cipher.WRAP_MODE, publicKey);
        byte[] wrappedKey = cipher.wrap(secretKey);
        cipher.init(Cipher.UNWRAP_MODE, privateKey);
        SecretKey unwrappedKey = (SecretKey)cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

        System.out.println(encoder.encodeToString(wrappedKey));
        System.out.println(encoder.encodeToString(secretKey.getEncoded()));
        System.out.println(encoder.encodeToString(unwrappedKey.getEncoded()));
    }
}

My questions are:

*

*Should I keep using Cipher.getInstance("RSA"), switch to Cipher.getInstance("RSA/ECB/PKCS1Padding") or something else?

*How can I do the same thing I am doing above but using EC?

*Is key wrapping the same as key encapsulation?

*Do I need to clear the memory used by secretKey in some way like we do with arrays (e.g. Arrays.fill(array, (byte)0)) or just if call getEncoded()?

To answer my second question I found that I should use:
KeyPairGenerator ecKeyGen = KeyPairGenerator.getInstance("EC");
However I am not sure what to use here instead of <name>:
Cipher cipher = Cipher.getInstance("<name>");
I also discovered that I can choose what curve to use by doing this:
...
ECGenParameterSpec ecsp = new ECGenParameterSpec("sect571k1");
ecKeyGen.initialize(571);
...

but again, I don't know what parameter should I use here instead of <name>:
new ECGenParameterSpec("<name>");
I believe that some good candidates are the following:
secp521r1, nistp521, sect571r1, nistb571, nistb571, sect571k1, nistk571 nistk571, sect163r2
are there other options? Can you help me select the best one? Is it enough to instantiate an ECGenParameterSpec object to set the initialization parameters of the EC KeyPairGenerator?

A:
Should I keep using Cipher.getInstance("RSA"), switch to Cipher.getInstance("RSA/ECB/PKCS1Padding") or something else?

You should switch to the fully specified string at the minimum; different providers could possible have different defaults, and specifying the full scheme is simply easier to read/maintain; not everybody will know the defaults.
PKCS#1 v1.5 padding is however susceptible to certain padding oracle attacks to switching to OAEP padding would provide certain security benefits.

How can I do the same thing I am doing above but using EC?

Not easily. The RSA problem allows for both signature generation and encryption, while the (EC)DH problem allows for signature generation and Diffie-Hellman. It is however possible to use ECDH to implement ECIES, which "derives" a symmetric key which is then used to encrypt the message.
ECIES is not included in the normal Java runtimes, but Bouncy Castle has implementations and it is of course possible to build the functionality on top of ECDH, which is included into the KeyAgreement class.

Is key wrapping the same as key encapsulation?

They are related. Key encapsulation is more for session keys and often derives the session key rather than encrypting it. I.e. you cannot use key encapsulation to (directly) encrypt an existing key if this is the case. Key wrapping does encrypt existing keys and may use specialized (deterministic) encryption schemes - although this is not directly the case with the schemes provides by the Java runtime.
The wrapping in Java is mainly useful because you don't need to store the intermediate key values of the key being wrapped in a byte array; this would be impossible if the keys are managed in hardware (such as a smart card) anyway.

Do I need to clear the memory used by secretKey in some way like we do with arrays (e.g. Arrays.fill(array, (byte)0)) or just if call getEncoded()?

You can't as the fields are not directly accessible. Java 8 and later implement Destroyable.destroy() so you have a method to destroy the keys. If the keys are in hardware then this method may throw an exception though.

I believe that some good candidates are the following:
secp521r1, nistp521, sect571r1, nistb571, nistb571, sect571k1, nistk571 nistk571, sect163r2
are there other options?

Sure, for lower number of bits: secp384r1 and secp256r1 for instance.

Can you help me select the best one?

Define best. Performance vs security, but even secp256r1 is already pretty strong. I would choose a SEC prime (p) curve though, not a Koblenz or twisted curve (k or t curve).

Is it enough to instantiate an ECGenParameterSpec object to set the initialization parameters of the EC KeyPairGenerator?

Yes.


text:
Q: I need to clarify my understanding of the extreme value theorem. I have had some difficulty in trying to understand the extreme value theorem but I think I might understand it correctly now but would like to clarify that I am thinking about this correctly. If we take for example the function 1/x, this is a continuous function over the reals without $0$. Clearly, the closer x approaches $0$, the larger 1/x becomes so 1/x is not bounded as x approaches $0$. However, $0$ is not part of the domain of 1/x so we can not apply the extreme value theorem since we require a closed interval for the theorem to hold is this correct?

A: The extreme value theorem is a special case of the fact that a continuous function on a compact set attains a maximum and minimum.
A compact set in $\mathbb{R}$ is a set $S$ that is closed and bounded. The closed part you already know. In the case that $S$ is an interval, it means that the interval must contain the endpoints. More generally, it means that if $S$ contains points arbitrarily close to some point $x$, it must also contain $x$. In the case of $T = \mathbb{R} \setminus \lbrace 0 \rbrace$ that you considered, $T$ contains points arbitrarily close to $0$ (like $.01$, $.001$, and so on) but does not contain $0$, so it is not closed.
I should also point out that this $T$ is not an interval. An interval is a set such  $S'$ that if $x \in S'$, $y \in S'$, and $x \leq a \leq y$, then $a \in S'$. But the fact about continuous functions attaining a maximum and minimum is true for all compact sets, not just compact intervals.
The bounded part means that all the points in the interval have absolute value less than or equal to some fixed finite number. That is, $S \subseteq [-M,M]$ for some finite positive number $M$. This excludes the $(-\infty, \infty)$ case that Michael Hoppe brought up.


text:
Q: DataModel cannot be cast to java.lang.String Here is the MainActivity.java including only a couple of the if/else blocks:
// Simple array with a list of languages
    String[] languages = {"Arabic", "Armenian", "Cantonese", "Cherokee",
            "Czech", "Dutch", "English", "French", "Gaelic", "German",
            "Greek", "Haitian Creole", "Hawaiian", "Italian", "Japanese", "Korean",
            "Mandarin", "Navajo", "Philippines Tagalog", "Polish", "Portuguese", "Romanian",
            "Russian", "Spanish", "Swedish", "Vietnamese"};

    // Simple array with a list of the spelling for Merry Christmas in language
    final String[] merrychristmas = {"Eid Melad Majeed", "Shnorhavor Surb Tsnund",
            "Sing-daan Faai-lohk", "ulihelisdi hunadetiyisgvi", "veselé vánoce",
            "vrolijk kerstfeest", "Merry Christmas!", "joyeux Noël", "Nollaig Shona Duit",
            "frohe Weihnacten", "Kalá Christoúgenna", "Jwaye Nwèl", "Mele Kalikimaka",
            "Buon Natale", "Merīkurisumasu", "jilgohun-christmas-bonoseyo",
            "Shèndàn kuàilè", "Nizhónígo Késhmish Da'doohleel",
            "Mąligayang Pasko", "Wesołych Świąt", "Feliz Natal", "Crăcuin fericit",
            "schastlivogo Rozhdestva", "Feliz Navidad", "god jul", "Chúc Mừng Giáng Sinh"};

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

    rowItems = new ArrayList<DataModel>();
    for (int i = 0; i < languages.length; i++) {
        DataModel item = new DataModel(languages[i]);
        rowItems.add(item);
    }

    listView = (ListView) findViewById(R.id.listView1);
    CustomAdapter adapter = new CustomAdapter(this, R.layout.item_row, rowItems);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(this);

}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
LinearLayout layout = new LinearLayout(MainActivity.this);
    layout.setBackgroundResource(R.drawable.circle);
    TextView tv = new TextView(MainActivity.this);
    // set the TextView properties
    tv.setTextColor(Color.WHITE);
    tv.setTextSize(20);
    tv.setPaddingRelative(22, 108, 0, 0);
    tv.setGravity(Gravity.FILL);
    tv.setText(merrychristmas[position]);
    layout.addView(tv);
    Toast toast = new Toast(MainActivity.this);

    if (position == 0) {
        Toast.makeText(getApplicationContext(),
                merrychristmas[position], Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
        toast.show();
        _player = MediaPlayer.create(MainActivity.this, R.raw.arabic);
        _player.start();
    }
    if (position == 1) {
        Toast.makeText(getApplicationContext(),
                merrychristmas[position], Toast.LENGTH_LONG);
        // set the layout as the toast view
        toast.setView(layout);
        toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
        toast.show();
        _player = MediaPlayer.create(MainActivity.this, R.raw.armenian);
        _player.start();
    }
    if (position == 2) {
        Toast.makeText(getApplicationContext(),
                merrychristmas[position], Toast.LENGTH_LONG);

And the CustomAdapter.java:
public class CustomAdapter extends ArrayAdapter<DataModel> {

    Context context;

    /****** custom adapter constructor ******/
    public CustomAdapter(Context context, int resourceId, List<DataModel> data) {
        super(context, resourceId, data);
        this.context = context;
    }

    /****** create a holder class to contain inflated xml file elements ******/

    private class ViewHolder {
        public TextView txtlanguage;
    }

    /**
    **** create each ListView row *****
    */
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;
        DataModel rowItem = getItem(position);

        LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {
            /****** Inflate item_row file for each row ******/
            convertView = mInflater.inflate(R.layout.item_row, null);
            /****** ViewHolder object to contain item_row.xml file elements ******/
            holder = new ViewHolder();
            holder.txtlanguage = (TextView) convertView.findViewById(R.id.text1);
            /****** set holder with LayoutInflater ******/
            convertView.setTag(holder);
        } else
            holder = (ViewHolder) convertView.getTag();

        /****** set model values in Holder elements ******/
        holder.txtlanguage.setText(rowItem.getLanguage());
        /****** set itemClickListener for LayoutInflater for each row ******/
        return convertView;
    }
}

For DataModel.java:
public class DataModel {

private String language;

public DataModel(String language) {
    this.language = language;
}

/****** get methods ******/
public String getLanguage() {
    return this.language;
}
/****** set methods ******/
public void setLanguage(String language) {
    this.language = language;
}

} // end class DataModel

Here's the crash dump:
10-12 08:53:01.135    1134-1134/com.blogspot.joyouslybeingjoy.merrychristmas
W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb3a86ba8)
10-12 08:53:01.155    1134-1134/com.blogspot.joyouslybeingjoy.merrychristmas
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.blogspot.joyouslybeingjoy.merrychristmas, PID: 1134
java.lang.ClassCastException: com.blogspot.joyouslybeingjoy.merrychristmas.
DataModel cannot be cast to java.lang.String
        at com.blogspot.joyouslybeingjoy.merrychristmas.MainActivity.
        onItemClick(MainActivity.java:102)
        at android.widget.AdapterView.performItemClick(AdapterView.java:299)
        at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:2904)
        at android.widget.AbsListView$3.run(AbsListView.java:3638)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)

Thanks in advance!  I sure am learning a lot and having fun doing it!  Appreciate the support!

A: It is CustomAdapter extends ArrayAdapter.
Use CustomAdapter extends ArrayAdapter<DataModel>
That's the problem I guess else please post your line 102.

A: CustomAdapter extends ArrayAdapter

means
CustomAdapter extends ArrayAdapter <Object>

Do like this, it will work
CustomAdapter extends ArrayAdapter <DataModel>

A: The error was on line 102.  I moved that and a few other commented out lines in the same area out (to the bottom of the file actually) and I ensure that the CustomAdapter extends ArrayAdapter  was in place, did a clean and it's working!  I'm moving all my commented out lines to NotePad++ for now on!  Thanks so much.  Really like learning from this board.


text:
Q: How can I perform a single selection on dynamically generated tree items? I need to perform the following task:
On selection of a single tree item in a treeViewer, relevant data is supposed to display in the tableViewer.
I have retrieved data from MySQL, using the rs.getString() method, and added the obtained string array into the tree item using the setText() method.
I need to select one of the string values displayed in the treeViewer that has been dynamically generated.
On using a selection event for the tree, all generated elements get selected. How can I obtain a single selection?
Is there any method similar to getSelectedItem() for a treeViewer?
This is the code i used to generate the tree items:
Tree tree_1 = treeViewer.getTree();
tree_1.setBounds(316, 205, 244, 446);
try {
    Class.forName("com.mysql.cj.jdbc.Driver");
    Connection con2 = DriverManager.getConnection("jdbc:mysql://localhost:3306/project","xxxx","xxxx");
    Statement stmt2 = con2.createStatement();
    String query2="select DISTINCT xxx FROM xxxxx";
    ResultSet rs2=stmt2.executeQuery(query2);
    while(rs2.next()) {
        String executive=rs2.getString("xxxx");
        TreeItem item4=new TreeItem(tree_1,SWT.NONE);
        item4.setText(executive);
        item4.setFont(SWTResourceManager.getFont("Times New Roman", 12, SWT.NORMAL));
    }
}


text:
Q: NBehave story output in resharper I wrote a bunch of stories using NBehave.
Now I have seen examples where the output is display in human readily format (see this example)Wayback machine link
Is there any way to get this output in resharper?

A: This was posted by Jörg Jenni on his blog. He shows how to get nBehave output to display:

When working with the latest build of NBehave 0.4 you may notice that
  there is no output written to the ReSharper Testrunner Output anymore.
Here is how I did workaround the problem. I derived the specs from the
  following class and every thing was fine again:
public class SpecBaseWithConsoleOutput: SpecBase
{
  private EventHandler<EventArgs<MessageEventData>> addedHandler;
  private EventHandler<EventArgs<Scenario>> scenarioCreatedHandler;
  private EventHandler<EventArgs<Story>> storyCreatedHandler;
  public override void MainSetup()
  {
    base.MainSetup();
    addedHandler = (o, a) => Console.WriteLine(a.EventData.Message);
    scenarioCreatedHandler = (o, a) => Console.WriteLine(a.EventData.Title);
    storyCreatedHandler = (o, a) => Console.WriteLine(a.EventData.Title);
    Story.MessageAdded += addedHandler;
    Story.ScenarioCreated += scenarioCreatedHandler;
    Story.StoryCreated += storyCreatedHandler;
  }
  public override void MainTeardown()
  {
    Story.MessageAdded -= addedHandler;
    Story.ScenarioCreated -= scenarioCreatedHandler;
    Story.StoryCreated -= storyCreatedHandler;
    base.MainTeardown();
  }
}


text:
Q: install ghcjs from stack I have GHC installed through stack ( so that stack ghc -- --version shows GHC-7.10.3 )
$ stack install ghcjs

Run from outside a project, using implicit global project config
Using resolver: lts-5.2 from implicit global project's config file: /home/john/.stack/global-project/stack.yaml
The following target packages were not found: ghcjs

Some resources suggest ghcjs is somewhat experimental (though in the further stages).

Looking at http://docs.haskellstack.org/en/stable/ghcjs/ I thought maybe I could find stack.yaml and change it.

To use GHCJS with stack >= 0.1.8, place a GHCJS version in the compiler field of stack.yaml ... then stack setup

$ cat ~/.stack/global-project/stack.yaml
# This is the implicit global project's config file, which is only used when
# 'stack' is run outside of a real project.  Settings here do _not_ act as
# defaults for all projects.  To change stack's default settings, edit
# '/home/john/.stack/config.yaml' instead.
#
# For more information about stack's configuration, see
# http://docs.haskellstack.org/en/stable/yaml_configuration.html
#
flags: {}
extra-package-dbs: []
packages: []
extra-deps: []
resolver: lts-5.2

We are told to look at config.yaml which looks equally blank.  Is this even right, am I going up a dead end?
$ cat ~/.stack/config.yaml
# This file contains default non-project-specific settings for 'stack', used
# in all projects.  For more information about stack's configuration, see
# http://docs.haskellstack.org/en/stable/yaml_configuration.html
#
{}

I just want to install ghcjs with stack.

A: Have a look at this page: http://docs.haskellstack.org/en/stable/ghcjs/
I would try:

*

*Start a new stack project, e.g. stack new js-test

*Modify the stack.yaml file by adding this stanza (taken from the above mentioned link):
compiler: ghcjs-0.2.0.20160414_ghc-7.10.3
compiler-check: match-exact
setup-info:
  ghcjs:
    source:
      ghcjs-0.2.0.20160414_ghc-7.10.3:
        url: https://s3.amazonaws.com/ghcjs/ghcjs-0.2.0.20160414_ghc-7.10.3.tar.gz
        sha1: 6d6f307503be9e94e0c96ef1308c7cf224d06be3

*Change the resolver: to lts-5.12 - this matches the above stanza.

*Run stack setup to get the compiler installed.
Step 4 will take a while.


text:
Q: Postgresql - Query running a lot faster with enable_nestloop=false. Why is the planner not doing the right thing? I have a query that runs a lot slower (~5 minutes) when I run it with the default enable_nestloop=true and enable_nestloop=false (~10 secs).
Explain analyse result for both cases:
Machine A nestloop=true - http://explain.depesz.com/s/nkj0 (~5 minutes)
Machine A nestloop=false - http://explain.depesz.com/s/wBM (~10 secs)
On a different slightly slower machine, copying the database over and leaving the default enable_nestloop=true it takes ~20 secs.
Machine B nestloop=true -  (~ 20secs)
For all the cases above I ensured that I did an ANALYZE before running the queries. There were no other queries running in parallel.
Both machines are running Postgres 8.4. Machine A is running Ubuntu 10.04 32 bit while Machine B is running Ubuntu 8.04 32 bit.
The actual query is available here . It is a reporting query with many joins as the database is mainly used for transaction processing.

*

*Without  resorting to putting in something like materialized views what can I do to make the planner do what I achieved by setting enable_nestloop=false ?

*From the research I have done it seems to be that the reason the planner is choosing the seemingly unoptimal query is because of the huge difference between the estimated and actual rows. How can I get this figure closer ?

*If I should rewrite the query, what should I change ?

*Why is it that the planner seems to be doing the right thing for Machine B. What should I be comparing in both the machines ?

A: If the query planner chooses suboptimal query plans, then chances are it has incomplete or misleading information to work with.
See this PostgreSQL Wiki page on server tuning. Especially pay attention to the chapters on random_page_cost and default_statistics_target.
Also read the corresponding chapters in the manual on Statistics Used by the Planner and Planner Cost Constants.
More specifically, it might help to increase the statistics target for the following columns:
ALTER TABLE postgres.products ALTER COLUMN id SET STATISTICS 1000;
ALTER TABLE postgres.sales_orders ALTER COLUMN retailer_id SET STATISTICS 1000;
ALTER TABLE postgres.sales_orders ALTER COLUMN company_id SET STATISTICS 1000;

ALTER TABLE goods_return_notes ALTER COLUMN retailer_id SET STATISTICS 1000;
ALTER TABLE goods_return_notes ALTER COLUMN company_id SET STATISTICS 1000;

ALTER TABLE retailer_category_leaf_nodes ALTER COLUMN tree_left SET STATISTICS 1000;
ALTER TABLE channels ALTER COLUMN principal_id SET STATISTICS 1000;

These are involved in the filters resulting in the

huge difference between the estimated and actual rows.

There are more. Check every column where the planer deviates a lot from the estimate. Default is just 100. Makes only sense for tables with >> 1000 rows. Experiment with the setting. Run ANALYZE on the tables afterwards for the changes to take effect.
It might also help to create a partial index on postgres(sales_orders.retailer_id) WHERE retailer_id IS NOT NULL (depending on how common NULL values are).

Another thing that may help you is to upgrade to the latest version 9.1. There have been a number of substantial improvements in this area.

A: Turns out rewriting the query was the best fix. The query was written in a way that it relied heavily on left joins and had many joins. I flattened it out and reduced the left joins by using my knowledge of the join nature of the data in the tables the query was joining. I guess the rule of thumb is if the planner is coming out with real crappy estimates, there might be a better way of writing the query.

A: This might be useful reading:
PostgreSQL tutorial about explicit JOINs.
Query planner tries to analyze the JOIN order to find the best order for JOINing.
I saw Your query had at least 15 JOINs. The number of possible JOIN orders goes up as factorial (n!). So it is not reasonable for query planner to try to find the best JOIN order if there are 15 JOINs - it would have to look at 15! = 1307674368000 different plans.
So it uses Genetic Query Optimizer instead. See Query Planning: Genetic Query Optimizer parameters. The parameter "geqo_threshold" determines how many JOINs must be present for query planner to use Genetic Query Optimizer.
This way the PostgreSQL planner looks at only small part of possible variants and tries to find the best one (randomly). So each time You run the ANALYZE, it might come up with better plan.
I think that generally, if You have so many tables to JOIN, You are better off doing as You did: rewriting the query to optimal JOIN order.

A: There are usually only one reason for different plan for same data and same queries on two servers with same PostgreSQL. This is different configuration - mainly value of work_mem. Hash join is usually faster, but needs a lot of available memory.


text:
Q: Windows 10 blocking applications without asking for permission I have a problem with Windows 10 blocking applications from making changes. I remember previously it showed popups asking for permissions, now I'm just getting the notifications that the application was blocked.
What's even worse is that quite often in the notification the application name gets truncated and it's impossible to tell the exact application so I could add another exclusion.
(Different language but you get the point)

It is causing updates to fail and programs malfunction (Adobe Lightroom, for example)
I want it to simply ask for permission not that I have to guess the exact program file and add it as an exception every time.


text:
Q: Searchable Dropdown list in Asp.net SqlConnection myDBCon = new SqlConnection(sc);
SqlCommand command = new SqlCommand("select  Caption_name from Commercial_caption", myDBCon);
myDBCon.Open();
SqlDataAdapter mySqlAdapter = new SqlDataAdapter();
mySqlAdapter.SelectCommand = command;
DataSet ds = new DataSet();
mySqlAdapter.Fill(ds);
DropDownList1.DataSource = command.ExecuteReader();
DropDownList1.DataTextField = "Caption_name";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("--SELECT--","0"));
myDBCon.Close();

A: You can use Select2 The jQuery replacement for select boxes. First include these files and you can download them from Here
<script type="text/javascript" src="js/jquery-3.1.1.js"></script>
<script type="text/javascript" src="js/select2.js"></script>
<link href="css/select2.css" rel="stylesheet" />

ASP
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="custom" AutoPostBack="true">
</asp:DropDownList>

Java Script
 <script type="text/javascript">
     $(document).ready(function () {
         $("#DropDownList1").select2({
            placeholder: "Select an option",
            allowClear: true
         });
     });
 </script>

Custom CSS for increasing the width of DropDownList
<style type="text/css">
   .custom
   {
       width: 50%;
   }
</style>

Your code behind logic remains the same. I have tested it and its working fine.
Code Behind
SqlConnection myDBCon = new SqlConnection(sc);
SqlCommand command = new SqlCommand("select  Caption_name from Commercial_caption", myDBCon);
myDBCon.Open();
SqlDataAdapter mySqlAdapter = new SqlDataAdapter();
mySqlAdapter.SelectCommand = command;
DataSet ds = new DataSet();
mySqlAdapter.Fill(ds);
DropDownList1.DataSource = command.ExecuteReader();
DropDownList1.DataTextField = "Caption_name";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("",""));
myDBCon.Close();

Note:  You need to add an empty item at 0th index and select2 have option for placeholder.


text:
Q: put the canvas in center of screen Below is my code to display a canvas on a background image:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>test</title>
    <link rel="icon" type="image/GIF" href="res/favicon.ico"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="full-screen" content="yes"/>
    <meta name="screen-orientation" content="portrait"/>
    <meta name="x5-fullscreen" content="true"/>
    <meta name="360-fullscreen" content="true"/>

    <style>
        body, canvas, div {

            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -khtml-user-select: none;
            -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
        }
    </style>

    <style type="text/css">

    body {

    background-image: url('bg.jpg');

    }

    </style>
</head>
<!--body style="padding:0; margin: 0; background: #000;"-->
<!--background-color: #cccccc;-->
<canvas id="gameCanvas" width="960" height="640"></canvas>
         <script src="frameworks/cocos2d-html5/CCBoot.js"></script>
         <script src="src/lib/build/build.js" type="text/javascript" ></script>
         <script type="text/javascript">require('boot');</script>
<script src="main.js"></script>
</body>
</html>

But before it display the canvas in the center of web page, It will display as below:

Rather than in the center of the web page.
Your comment welcome.

A: you can do this in modern browser(2dTransformCompatibility 3dTransformCompatibility) with css:
canvas {
    position:absolute;
    top:50%;
    left:50%;
    transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
}

A: body, canvas, div {
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    -khtml-user-select: none;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);

}
canvas {
     margin: auto auto auto auto
}

Should do it.

A: For centering your webpage, you can calculate the difference between size of body and size of canvas.
For eg
diffHeight = (bodyHeight-canavasheight)  // difference in height
diffWidth = (bodyWidth-canvasWidth)  // difference in width
then you can put your margin-left equals to half of diffWidth and margin-top equals to half of diffHeight.
setting margin equals to auto is an good option but it sometimes doesn't center vertically.

A: This should work.
canvas {
    display: -webkit-box;
        display: -moz-box;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -webkit-box-align: center;
        -moz-box-align: center;
        -ms-flex-align: center;
        -webkit-align-items: center;
          align-items: center;
        -webkit-box-pack: center;
        -moz-box-pack: center;
        -ms-flex-pack: center;
        -webkit-justify-content: center;
          justify-content: center;
    }