Id int64 34.6M 60.5M | Title stringlengths 15 150 | Body stringlengths 33 36.7k | Tags stringlengths 3 112 | CreationDate stringdate 2016-01-01 00:21:59 2020-02-29 17:55:56 | Y stringclasses 3 values |
|---|---|---|---|---|---|
35,108,044 | Is there any way to make code organized if I have a super long list? | <p>Is there any way to avoid single lines containing thousands of characters if I happen to have a super long list?</p>
| <python><python-3.x> | 2016-01-30 22:34:34 | LQ_CLOSE |
35,108,046 | Python Reindex Producing Nan | <p>Here is the code that I am working with:</p>
<p><code>import pandas as pd</code></p>
<pre><code>test3 = pd.Series([1,2,3], index = ['a','b','c'])
test3 = test3.reindex(index = ['f','g','z'])
</code></pre>
<p>So originally every thing is fine and test3 has an index of 'a' 'b' 'c' and values 1,2,3. But then when I got to reindex test3 I get that my values 1 2 3 are lost. Why is that? The desired output would be:</p>
<pre><code>f 1
g 2
z 3
</code></pre>
| <python><pandas><series> | 2016-01-30 22:34:42 | HQ |
35,108,243 | Vim command: how to select a word under cursor in normal mode | <p>I'm looking for a Vim command to select a word under cursor in normal mode, like double-clicking by mouse. Does it exist like this?</p>
| <vim><macvim><xvim> | 2016-01-30 22:57:44 | HQ |
35,108,453 | What is the difference between (++c) & (c++)? | <p>What is the difference between (++c) and (c++)?</p>
<p>Lets say
c = 4</p>
<p>I know that for (++c) you would increment increment 4 by 1 so 5, but for (c++)?</p>
| <java><operators><increment> | 2016-01-30 23:24:02 | LQ_CLOSE |
35,108,637 | java.lang.NoSuchMethodError: org.springframework.util.ReflectionUtils.clearCache() | <p>I faced with a problem, was google it for a half of this day. Nothing could help me. It was working. But after that something has happened and i didn't capture that.</p>
<p>Here are TomCat Catalina Log</p>
<pre><code>31-Jan-2016 00:35:27.278 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000412: Hibernate Core {5.0.7.Final}
31-Jan-2016 00:35:27.282 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000205: Loaded properties from resource hibernate.properties: {hibernate.dialect=org.hibernate.dialect.MySQLDialect, hibernate.show_sql=true, hibernate.bytecode.use_reflection_optimizer=false, hibernate.hbm2ddl.auto=update}
31-Jan-2016 00:35:27.283 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000021: Bytecode provider name : javassist
31-Jan-2016 00:35:27.376 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
31-Jan-2016 00:35:28.170 INFO [RMI TCP Connection(2)-127.0.0.1] <unknown>.<unknown> HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
31-Jan-2016 00:35:29.632 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000228: Running hbm2ddl schema update
31-Jan-2016 00:35:30.331 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
31-Jan-2016 00:35:30.349 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [] startup failed due to previous errors
**31-Jan-2016 00:35:30.377 WARNING [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [ROOT] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.**
31-Jan-2016 00:35:32.709 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/apache-tomcat-8.0.24/webapps/manager
31-Jan-2016 00:35:32.907 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/apache-tomcat-8.0.24/webapps/manager has finished in 197 ms
</code></pre>
<hr>
<p>Localhost Log</p>
<pre><code> java.lang.NoSuchMethodError: org.springframework.util.ReflectionUtils.clearCache()V
at org.springframework.context.support.AbstractApplicationContext.resetCommonCaches(AbstractApplicationContext.java:879)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:563)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1648)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:463)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:413)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1466)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1307)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1399)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:828)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$254(TCPTransport.java:683)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$$Lambda$1/2146013565.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
<hr>
<p>My DatabaseConfig</p>
<pre><code>@Configuration
@EnableJpaRepositories("cards.server.repository")
@EnableTransactionManagement
@ComponentScan(value = "cards.server")
@PropertySource({
"classpath:database.properties",
"classpath:hibernate.properties"}
)
public class DatabaseConfig extends IOException {
@Autowired
private Environment env;
@Bean(name = "entityManager")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(env.getRequiredProperty("db.entity.package"));
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(getHibernateProperties());
return em;
}
@Bean(name = "dataSource")
public DataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setUrl(env.getRequiredProperty("db.url"));
ds.setDriverClassName(env.getRequiredProperty("db.driver"));
ds.setUsername(env.getRequiredProperty("db.username"));
ds.setPassword(env.getRequiredProperty("db.password"));
ds.setInitialSize(Integer.valueOf(env.getRequiredProperty("db.initialSize")));
ds.setMinIdle(Integer.valueOf(env.getRequiredProperty("db.minIdle")));
ds.setMaxIdle(Integer.valueOf(env.getRequiredProperty("db.maxIdle")));
ds.setTimeBetweenEvictionRunsMillis(Long.valueOf(env.getRequiredProperty("db.timeBetweenEvictionRunsMillis")));
ds.setMinEvictableIdleTimeMillis(Long.valueOf(env.getRequiredProperty("db.minEvictableIdleTimeMillis")));
ds.setTestOnBorrow(Boolean.valueOf(env.getRequiredProperty("db.testOnBorrow")));
ds.setValidationQuery(env.getRequiredProperty("db.validationQuery"));
return ds;
}
@Bean(name = "transactionManager")
public PlatformTransactionManager platformTransactionManager() {
JpaTransactionManager manager = new JpaTransactionManager();
manager.setEntityManagerFactory(entityManagerFactory().getObject());
return manager;
}
public Properties getHibernateProperties() {
Properties properties = new Properties();
properties.getProperty(env.getProperty("hibernate.dialect"));
properties.getProperty(env.getProperty("hibernate.show_sql"));
properties.getProperty(env.getProperty("hibernate.hbm2ddl.auto"));
return properties;
}
}
</code></pre>
<hr>
<p>pom.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cards.server</groupId>
<artifactId>cards.server</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!-- cmd + alt + v -->
<properties>
<spring-core.version>4.2.2.RELEASE</spring-core.version>
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<spring-data-jpa.version>1.9.2.RELEASE</spring-data-jpa.version>
<hibernate-entitymanager.version>5.0.7.Final</hibernate-entitymanager.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<commons-dbcp2.version>2.1.1</commons-dbcp2.version>
<jta.version>1.1</jta.version>
<postgresql.version>9.1-901-1.jdbc4</postgresql.version>
<junit.version>4.12</junit.version>
<spring-webmvc.version>4.2.4.RELEASE</spring-webmvc.version>
<spring-test.version>4.1.6.RELEASE</spring-test.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-core.version}</version>
</dependency>
<!-- Web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-core.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-webmvc.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
</dependency>
<!--<dependency>-->
<!--<groupId>jstl</groupId>-->
<!--<artifactId>jstl</artifactId>-->
<!--<version>1.2</version>-->
<!--</dependency>-->
<!-- Database -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entitymanager.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2.version}</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>${jta.version}</version>
</dependency>
<!--<dependency>-->
<!--<groupId>postgresql</groupId>-->
<!--<artifactId>postgresql</artifactId>-->
<!--<version>${postgresql.version}</version>-->
<!--</dependency>-->
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-test.version}</version>
</dependency>
</dependencies>
</project>
</code></pre>
<p>Hoping for your help,
Thank you.</p>
| <java><spring><maven><tomcat> | 2016-01-30 23:49:11 | HQ |
35,109,051 | How do you console log inside a knockout template | <p>I thought this was correct:</p>
<pre><code> <div data-bind="foreach: amount_options, visible: $parent.displayAskAmoutRadioButtons()">
<!-- ko console.log(amount_option) --><!-- /ko -->
<label class="donor-js-amount-choice">
<!-- <input type="radio" class="donor-js-webware" name="gift_amt" data-bind="attr: {value: key}, checked: $parent.amountSelected"><span class="donor-js-currency-symbol" data-bind="html: $root.session.currencySymbol"></span>&nbsp;<span class="donor-js-input-currency" data-bind="text: desc"></span>&nbsp;<span class="donor-js-input-currency"></span><br> -->
</label>
</div>
</code></pre>
<p>apparently not as nothing gets out put to the console. The commented out line of tag is throwing an error about the <code>value: key</code> and I need to know whats inside of one of these <code>amount_options</code>.</p>
<p><strong>Ideas?</strong></p>
| <knockout.js> | 2016-01-31 00:48:17 | HQ |
35,109,451 | How to access “Saved Queries” programmatically? | <p>In BigQuery Web UI, there is a “Saved Queries” Section.<br>
Is there way to access (read/write) those programmatically?<br>
Any API? </p>
| <google-bigquery> | 2016-01-31 01:51:33 | HQ |
35,109,964 | I am doing a (StrIns) funcion that mix 2 words but the program is not working at all | this is my code
________________________________________________________________________
#include <stdio.h>
#include <stdlib.h>
char strins(char[],char[],int,int,int);
int main(void)
{
char zk1[1000];
char zk2[1000];
int pos=0;
int n1=0;
int n2=0;
printf("plz enter the first string : ");
gets(zk1);
n1=sizeof(zk1)/sizeof(int);
printf("plz enter the second string : ");
gets(zk2);
n2=sizeof(zk2)/sizeof(int);
printf("plz enter the position");
scanf("%d",&pos);
strins(zk1,zk2,pos,n1,n2);
return 0;
}
char strins(char zk1[],char zk2[],int pos,int n1,int n2)
{
char zk3[]={(char)malloc(sizeof(zk1)+sizeof(zk2))};
int ctr=0;
for(int i=0;i<pos;i++)
{
zk3[i]=zk1[i];
ctr++;
}
for(int i=0;i<n2;i++)
{
zk3[pos]=zk2[i];
ctr++;
}
for(int i=pos;i<n1;i++)
{
zk3[ctr]=zk1[i];
}
free(zk3);
return *zk3;
}
__________________________________________________________________________
there are no compiler errors
__________________________________________________________________________
but when I run the program and write the tow words and the position the program stops
____________________________________________________________________________
and write this error :: process returned 255
___________________________________________________________________________
thanks for helping me
| <c><string><for-loop> | 2016-01-31 03:20:41 | LQ_EDIT |
35,110,363 | React Native init specific version | <p>I upgraded my latest project to React Native 0.19 and instantly the video no longer works. How can I create a new project with a specific version? I want to init a new project at version 0.18.1. I did some google searches but couldn't find anything about this.</p>
<pre><code>$ react-native init newproject --verbose
</code></pre>
<p>I'm guessing I need to add the word @18.1 in there somewhere but can't get that to work.</p>
| <ios><react-native> | 2016-01-31 04:32:06 | HQ |
35,110,610 | What's the right way to clear a bytes.Buffer in golang? | <p>I'm trying to clear a <code>bytes.Buffer</code>, but there's no such function in the document</p>
<p>Maybe I should just renew the buffer? What's the right way to do it?</p>
<pre><code>buffer = bytes.NewBufferString("")
buffer.Grow (30000)
</code></pre>
| <go><buffer> | 2016-01-31 05:18:51 | HQ |
35,110,694 | Cant do a rounded picture box, help me | im having a problem to round a picturebox edge on visual studio enterprise 2015
private void pictureBox3_Click(object sender, EventArgs e)
{
System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
gp.AddEllipse(0, 0, pictureBox1.Width - 3, pictureBox1.Height - 3);
Region rg = new Region(gp);
pictureBox1.Region = rg;
}
this is the code, but nothing happens, could you help me? | <c#><picturebox> | 2016-01-31 05:34:30 | LQ_EDIT |
35,110,777 | Is there a way to create clusters in arcgis | <p>I have arcgis Web application.In that I need to create clusters.I have tried with examples which I got in Google search.
Can anyone tell me how to do it</p>
| <arcgis-js-api> | 2016-01-31 05:47:06 | LQ_CLOSE |
35,110,895 | What is the best and most used way of wiring in spring dependency injection | <p>This question is not pure coding but pre coding.
Actually I am new to spring in winter season. I have a question is that What is the best and most used way of wiring in spring dependency injection? I come to know that xml based wiring is old now. I have confusion between annotation and java-based autowiring. I didn't get enough evidence to choose the right one. Which is most used way now a days? or I have to learn all(which might be confusing at some point).</p>
| <java><spring><spring-mvc> | 2016-01-31 06:04:23 | LQ_CLOSE |
35,111,223 | How to make app alway running in background , so user alway get notif even the app is close? | hello what must i do to make my app(android) that integrate wit smooch SDK always running in background.
example
if you have BBM ,Facebook ,or Gmail , when you close the app with back button or exit . the app will send you a notification even you dont open the app.
| <android><smooch> | 2016-01-31 06:54:26 | LQ_EDIT |
35,111,244 | codeigniter URL routes not working properly | Usually codeigniter URL format is domain/controllerName/functionName/id but i want it like domain/product-name/product-detail-page. I have made changes in routes.php also but it gives me 404 page. Any help. Urgent. ASAP. | <php><codeigniter> | 2016-01-31 06:58:35 | LQ_EDIT |
35,111,283 | OS as algorithm? | <p>Can an Operating System be considered as an algorithm? Focus on the finiteness property, please. I have contradicting views on it right now with one prof. telling me something and the other something else.</p>
| <algorithm><operating-system> | 2016-01-31 07:07:01 | LQ_CLOSE |
35,112,165 | MongoDB: Bulk insert (Bulk.insert) vs insert multiple (insert([...])) | <p>Is there any difference between a <a href="https://docs.mongodb.org/manual/core/bulk-write-operations/" rel="noreferrer">bulk insert</a> vs <a href="https://docs.mongodb.org/manual/reference/method/db.collection.insert/" rel="noreferrer">inserting multiple documents</a>? </p>
<pre><code>var bulk = db.items.initializeUnorderedBulkOp();
bulk.insert( { item: "abc123", defaultQty: 100, status: "A", points: 100 } );
bulk.insert( { item: "ijk123", defaultQty: 200, status: "A", points: 200 } );
bulk.insert( { item: "mop123", defaultQty: 0, status: "P", points: 0 } );
bulk.execute();
</code></pre>
<p>VS</p>
<pre><code>db.collection.insert(
<document or array of documents>
)
</code></pre>
<p>Is there one thats faster? </p>
| <mongodb> | 2016-01-31 09:17:01 | HQ |
35,112,185 | travis-ci — Waiting for status to be reported | <p>I pushed a new commit to my git repo, but travis-ci build isn't triggered.</p>
<p><a href="https://i.stack.imgur.com/DYs8x.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DYs8x.png" alt="enter image description here"></a></p>
<p>It show:</p>
<blockquote>
<p>continuous-integration/travis-ci — Waiting for status to be reported</p>
</blockquote>
<p>but no job is running on travis-ci. It is so strange! </p>
<p>Anyone has idea for this! Thanks in advance!</p>
| <github><travis-ci> | 2016-01-31 09:19:39 | HQ |
35,112,581 | a simple while loop does not read all matches. Reads only the first match and ignores the others | The problem is the code skips the first echo statement no matter what.
$query = mysql_query("SELECT index_no, lesson FROM c8_lessons_list WHERE index_no ='456'");
($row = mysql_fetch_array($query));
if ($row['index_no'] !== '456' && $row['lesson'] !== "Fertilisation process" )
{
echo '<a href="file:///D|/CC-Gate/localhost">Fertilisation process</a>';
}
else
{
echo 'Fertilisation process Completed';
}
| <php><mysql> | 2016-01-31 10:04:43 | LQ_EDIT |
35,112,588 | Python: How to run a select amount of code n amount of times where user input is n | newbie to python:
I'm having some trouble trying to repeat a certain part of code n times where n is user input. It would start off something like
roominput = int(input("How many rooms do you require painting?"))
The user would then input with an integer(n) and a select part of the program would repeat n amount of times, asking for the room name, room's dimensions and colour of paint for the wall. This is for a school project, so any help would be much appreciated. Thank you!
| <python><python-2.7><python-3.x><input><output> | 2016-01-31 10:06:10 | LQ_EDIT |
35,112,633 | convert String to Util date in "dd-MMM-yyyy" fromat | <p>I am working in Eclipse .
I have string date = "12-DEC-2016" </p>
<p>now i want to convert it into util date in same format. Please help me with this query.</p>
| <java><swing><datepicker> | 2016-01-31 10:10:06 | LQ_CLOSE |
35,112,921 | How to detect change in model for input field from directive in angular2 | <p>I have this code for a textarea, it is working great with the ngModel and updating live, however i would like my-custom-directive to know when the model bound to this textarea is changing.</p>
<p>How can i detect a model change for this textarea in the my-custom-directive?</p>
<pre><code> <textarea my-custom-directive class="green" [(ngModel)]="customertext"></textarea>
</code></pre>
| <angular> | 2016-01-31 10:45:31 | HQ |
35,112,991 | Is it possible to change the return value of a method in this case? | <p>I want to change the return value of method getvalue() to string "firefighter" which i tried from main method but did not work out.
looking forward to some soln. </p>
<pre><code>public class Summ2 {
private String getValue() {
return "TUHH";
}
public static void main(String[] args) {
Summ2 GO = new Summ2();
assert GO.getValue() == "firefighter";
System.out.println(GO.getValue());
}
}
</code></pre>
| <java><methods><return-value> | 2016-01-31 10:53:31 | LQ_CLOSE |
35,113,892 | QComboBox - Select no entry | <p>I have a QComboBox on my ui and set the model like this:</p>
<pre><code>QStringListModel* model = new QStringListModel;
QStringList stringlist;
stringlist << "Test1" << "Test2" << "Test3";
model->setStringList(stringlist);
ui->comboBox->setModel(model);
</code></pre>
<p>Now I want to change the current index to be none (so that I get a blank combo box).</p>
<p>I already tried setting the current index to -1 with <code>ui->comboBox->setCurrentIndex(-1);</code>, but that results to an index aout of range exeption in qlist:</p>
<pre><code>ASSERT failure in QList<T>::operator[]: "index out of range", file F:/Qt/5.4/mingw491_32/include/QtCore/qlist.h, line 486
</code></pre>
| <qt><qcombobox> | 2016-01-31 12:35:52 | HQ |
35,115,375 | Can someone please help me with this program? | Write a program that reads four integers and prints "two pairs" if the input consists of two matching pairs (in some order) and "not two pairs"
So far I have written:
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n;
int number1;
int number2;
int number3;
int number4;
System.out.println("Enter up to four numbers: ");
n = s.nextInt(); | <java> | 2016-01-31 15:10:39 | LQ_EDIT |
35,115,414 | Copy or clone a collection in Julia | <p>I have created a one-dimensional array(vector) in Julia, namely, <code>a=[1, 2, 3, 4, 5]</code>. Then I want to create a new vector <code>b</code>, where <code>b</code> has exactly same elements in <code>a</code>, i.e <code>b=[1, 2, 3, 4, 5]</code>. </p>
<p>It seems that directly use <code>b = a</code> just create a pointer for the original collection, which means if I modify <code>b</code> and <code>a</code> is mutable, the modification will also be reflected in <code>a</code>. For example, if I use <code>!pop(b)</code>, then <code>b=[1, 2, 3, 4]</code> and <code>a=[1, 2, 3, 4]</code>. </p>
<p>I am wondering if there is a official function to merely copy or clone the collection, which the change in <code>b</code> will not happen in <code>a</code>. I find a solution is use <code>b = collect(a)</code>. I would appreciate that someone provide some other approaches.</p>
| <collections><julia> | 2016-01-31 15:14:14 | HQ |
35,116,699 | Piping not working with echo command | <p>When I run the following <code>Bash</code> script, I would expect it to print <code>Hello</code>. Instead, it prints a blank line and exits.</p>
<pre><code>echo 'Hello' | echo
</code></pre>
<p>Why doesn't <code>piping</code> output from <code>echo</code> to <code>echo</code> work?</p>
| <bash><echo> | 2016-01-31 17:11:56 | HQ |
35,116,789 | Error: Could not find or load main class | <p>I am new to java and I am currently trying to run a program for a class assignment and it compiles however, every time I run it I get this error "Error: Could not find or load main class sailboat.java" To make things worse I need to submit this in a different way from standard assignments logging onto the main server of my campus and transfer it from my directory to another yet every time I do it, it tells me it can't open the source file.</p>
<p>Would these two situations because by the same thing? Is this something caused by a mistake in my code, or is it something wrong with my Classpath?</p>
<p>here's the code I made, I used notepad++ </p>
<pre><code>import java.text.*;
import java.io.*;
import java.math.*;
public class sailboat {
public static void main (String argv []) throws IOException {
BufferedReader stdin =
new BufferedReader (new InputStreamReader (System.in));
String inputValue;
//Tartan 34C Title
System.out.println("Sailboat: Tartan 34C");
//Tartan 34C inputs
double LOA = Double.parseDouble("34.50");
double LWL = Double.parseDouble("24.00");
double beam = Double.parseDouble("10.20");
double displace = Double.parseDouble("11200.00");
double displace_Ton = Double.parseDouble("5.60");
double sail_Area = Double.parseDouble("483.00");
//Hull Speed Formula
double hull_Speed = Math.sqrt(LWL) * 1.34;
System.out.println("Hull Speed:" + hull_Speed);
//Displacement to Waterline Length Formula
double displace_Lng = displace_Ton / 0.01 * Math.pow(LWL, 3.0);
System.out.println("Displacement to water lenght:" + displace_Lng);
//Sail Area to Displacement Formula
double sail_Area_Displace = sail_Area / Math.pow((displace / 64), 0.67);
System.out.println("Sail Area to displacement:" + sail_Area_Displace);
//Capsize Screening Index Formula
double Cap_I = beam / Math.pow((displace / 64), 0.33);
System.out.println("Capsize Screening Index:" + Cap_I);
//Comfort Index Formula
double Comf_I = displace / (0.7 * LWL + 0.3 * LOA) * 0.65 * Math.pow(beam, 1.33);
System.out.println("Comfort Index:" + Comf_I + "\n");
</code></pre>
<p>any input would be helpful.</p>
| <java><class><find><load><main> | 2016-01-31 17:19:55 | LQ_CLOSE |
35,117,220 | Please help me to get this PHP code work correctly | <?php include 'header.php';
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$con = mysql_connect("localhost","root","");
$db_selected = mysql_select_db("layout",$con);
$name = $_POST['name'];
$password = $_POST['password'];
if($_POST["submit"] == "LOGIN" )
{
$sql = "SELECT username,password from secure";
$result = mysql_query($sql,$con);
}
while($row = mysql_fetch_array($result,MYSQL_BOTH))
{
if($row['username'] == $name and $row['password'] == $password)
{
echo "welcome " .$name;
}
else
{
echo "Wrong Credentials";
}
}
?>
I'm a beginner. I wrote this PHP code for a sign in form. But it's showing "Wrong Credentials" followed by "Welcome George", even if the username and password matches. And if the username and password doesnt match it shows as "Wrong Credentials" followed by another "Wrong Credentials". Please help. Thanks in advance. | <php><mysql><arrays><if-statement><while-loop> | 2016-01-31 17:55:21 | LQ_EDIT |
35,117,289 | Markdown doesn't work in attachments | <p>I'm creating a Slack integration with the Slack API. I followed <a href="https://api.slack.com/docs/formatting">the documentation</a> but the markdown formatting doesn't work on my attachments...</p>
<p>Here is my response object:</p>
<pre><code>{
response_type: "in_channel",
text: "List:",
attachments: [
{
text: "*pseudo*:\nbla bla bla",
mrkdwn: true
}
]
}
</code></pre>
<p>The "*" are displayed and not evaluated. Did I make a mistake? </p>
| <slack-api> | 2016-01-31 18:01:32 | HQ |
35,117,302 | How to get all possible combination of 2xn matrix | <p>I was unable to solve this problem, tried much but logic not working.
Problem is,
I have to calculate all possible combinations of 2 x N matrix.
conditions:</p>
<ul>
<li>sum of all elements must be N.</li>
<li>elements in a row or a column must be in non increasing way.</li>
<li>all elements must be positive and real numbers.
print all possible combinations.
let for 6, it is 29
thanks.</li>
</ul>
| <c> | 2016-01-31 18:02:59 | LQ_CLOSE |
35,117,499 | missing right paranthesis Oracle while creating table | oracle error
SQL> desc user_details;
Name Null? Type
----------------------------------------- -------- --------------
USER_ID NUMBER(38)
NAME VARCHAR2(20)
DOB DATE
CONTACT NUMBER(38)
EMAIL NOT NULL VARCHAR2(50)
TYPE VARCHAR2(4)
create table user_reg
(
reg_id int primary key,
pass varchar(50),
email varchar(20) foreign key preferences user_details(user_id)
);
this is what error i got while creating table user_reg | <oracle> | 2016-01-31 18:18:39 | LQ_EDIT |
35,118,432 | Is it possible to easily copy applications settings from one web app to another on azure | <p>I was wondering if there is an easy way to completely copy all the key values from one web app's application settings to another, as seen in the below picture I have a lot of these key values and having to do this manually every time is very cumbersome.</p>
<p><a href="https://i.stack.imgur.com/4vfJm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4vfJm.png" alt="enter image description here"></a></p>
| <azure-web-sites> | 2016-01-31 19:34:38 | HQ |
35,118,677 | C# Count Threading Not Working | <p>Good afternoon everybody.
I am new to Parallel.ForEach and even newer to threading and I wanted to ask your opinion on what is wrong with this code.</p>
<pre><code> using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace MultiThreading_Example
{
class theMeter {
int count1 = 0;
public void CounterMeter()
{
while (this.count1 < 10000)
{
this.count1++;
Console.WriteLine(this.count1);
}
}
}
class Program
{
static void Main(string[] args)
{
theMeter met = new theMeter();
ThreadStart countForMe = new ThreadStart(met.CounterMeter);
for (int i = 0; i < 1000; i++)
{
Thread t1 = new Thread(countForMe);
t1.Start();
t1.Join();
t1.Abort();
}
Console.ReadLine();
}
}
}
</code></pre>
<p>Any idea what is wrong with this? I mean, I have tried doing it without t1.Join() and also have tried doing it on one thread. All are at the same speed. How can I get he program to process faster?</p>
<p>Thanks in advance!</p>
| <c#><multithreading> | 2016-01-31 19:54:47 | LQ_CLOSE |
35,119,032 | how to use Socks4/5 Proxy Handlers in Netty Client (4.1) | <p>I need to configure socks proxy in Netty client (to request different sites via socks4 or 5 proxies).
Tried a lot of proxies from free socks lists (like www.socks-proxy.net, <a href="http://sockslist.net/" rel="noreferrer">http://sockslist.net/</a> etc) but with no luck:</p>
<pre><code>@Test
public void testProxy() throws Exception {
final String ua = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
final String host = "www.main.de";
final int port = 80;
Bootstrap b = new Bootstrap();
b.group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpClientCodec());
p.addLast(new HttpContentDecompressor());
p.addLast(new HttpObjectAggregator(10_485_760));
p.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "/");
request.headers().set(HOST, host + ":" + port);
request.headers().set(USER_AGENT, ua);
request.headers().set(CONNECTION, CLOSE);
ctx.writeAndFlush(request);
System.out.println("!sent");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("!answer");
if (msg instanceof FullHttpResponse) {
FullHttpResponse httpResp = (FullHttpResponse) msg;
ByteBuf content = httpResp.content();
String strContent = content.toString(UTF_8);
System.out.println("body: " + strContent);
finish.countDown();
return;
}
super.channelRead(ctx, msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace(System.err);
ctx.close();
finish.countDown();
}
});
p.addLast(new Socks4ProxyHandler(new InetSocketAddress("149.202.68.167", 37678)));
}
});
b.connect(host, port).awaitUninterruptibly();
System.out.println("!connected");
finish.await(1, MINUTES);
}
</code></pre>
<p>The connection hangs, resets or getting some strange exceptions.
What's wrong?
Proxy support added to Netty since 4.1 (now there is a 4.1CR, tried it and 4.1b7-8 before)</p>
| <java><httpclient><netty><http-proxy><socks> | 2016-01-31 20:23:29 | HQ |
35,119,819 | Why duplicate code is needed with const reference arguments? | <p>In this <a href="http://www.stlport.org/resources/StepanovUSA.html">interview</a> Stepanov shows how to implement generic <code>max</code> function in C++. </p>
<blockquote>
<p>Try to implement a simple thing in the object oriented way, say, max.
I do not know how it can be done. Using generic programming I can
write:</p>
<pre><code>template <class StrictWeakOrdered>
inline StrictWeakOrdered& max(StrictWeakOrdered& x,
StrictWeakOrdered& y) {
return x < y ? y : x;
}
and
template <class StrictWeakOrdered>
inline const StrictWeakOrdered& max(const StrictWeakOrdered& x,
const StrictWeakOrdered& y) {
return x < y ? y : x;
}
</code></pre>
<p>(you do need both & and const &).</p>
</blockquote>
<p>Why is there need to write the code twice? Is this needed to aid compiler for optimization or a convention to reduce bugs? Is <code>max</code> a special case where body of a <code>const</code> version is identical? </p>
<p>How many valid <code>const</code> and non-<code>const</code> permutations a function of N arguments should have to define a complete API?</p>
| <c++> | 2016-01-31 21:39:37 | HQ |
35,119,858 | python regex polish characters fail | I need to replace a string with polish characters.
I tried something like that:
k = 'aąkkk cdkkk aą xskkk'
odp = re.sub('(?<!aą|cd)kkk', '***', k)
print (odp)
but it doesn't work. I get an error:
File "/usr/lib/python2.7/re.py", line 244, in _compile
raise error, v # invalid expression
It's a problem with polish characters, because when I replace 'ą' character with 'a' char it work:
k = 'aąkkk cdkkk aą xskkk'
odp = re.sub('(?<!aa|cd)kkk', '***', k)
print (odp)
The answer is: aą*** cdkkk aą xs***
I found info that I should to use UNICODE, but it still doesn't work:
a = re.compile(ur'(?<!\u0061\u0105|\u0063\u0064)kkk', re.UNICODE)
a
k = u'aąkkk cdkkk aą xskkk'
odp = a.sub('***', k)
print (odp)
but the answear is : aÄ
*** cdkkk aÄ
xs***
Can you help me how resolve my problem?
I'm so sorry for my mistakes with the English mistakes. | <python><regex> | 2016-01-31 21:43:17 | LQ_EDIT |
35,120,082 | How to get started with Akka Streams? | <p>The Akka Streams library already comes with quite a <a href="http://doc.akka.io/docs/akka/2.4.2-RC1/scala/stream/index.html">wealth of documentation</a>. However, the main problem for me is that it provides too much material - I feel quite overwhelmed by the number of concepts that I have to learn. Lots of examples shown there feel very heavyweight and can't easily be translated to real world use cases and are therefore quite esoteric. I think it gives way too much details without explaining how to build all the building blocks together and how exactly it helps to solve specific problems.</p>
<p>There are sources, sinks, flows, graph stages, partial graphs, materialization, a graph DSL and a lot more and I just don't know where to start. The <a href="http://doc.akka.io/docs/akka/2.4.2-RC1/scala/stream/stream-quickstart.html#stream-quickstart-scala">quick start guide</a> is meant to be a starting place but I don't understand it. It just throws in the concepts mentioned above without explaining them. Furthermore the code examples can't be executed - there are missing parts which makes it more or less impossible for me to follow the text.</p>
<p>Can anyone explain the concepts sources, sinks, flows, graph stages, partial graphs, materialization and maybe some other things that I missed in simple words and with easy examples that don't explain every single detail (and which are probably not needed anyway at the beginning)?</p>
| <scala><akka-stream> | 2016-01-31 22:02:40 | HQ |
35,120,091 | How to print data from database? | <p>I am supposed to create webpage with a list of literature, where admin will maintain the list and users will be able to choose the books and print a list. I already have the web app done, but I have no idea, how to print it. Definetly some button, which will print just the data in a list. Any ideas ?</p>
| <php><mysql><database><printing> | 2016-01-31 22:03:25 | LQ_CLOSE |
35,120,219 | A database schema vs a database tablespace? | <p>Doing my databases reading when I read...</p>
<p>Schema: Is a container for objects</p>
<p>Tablespace: A logical storage unit for objects</p>
<p>Can anyone explain the difference between these?</p>
| <database><database-design> | 2016-01-31 22:17:48 | HQ |
35,120,413 | jQuery add html content in hidden div | <p>When I use jQuery selectors for add dynamically generated html in hidden div, they don't work. How to add something in hidden div with jquery?
I need to make div hidden while adding content after ajax query, because I should generate many html blocks and add them on page, I want to add all blocks in hidden div and then show all content (make div visible).</p>
| <javascript><jquery><html> | 2016-01-31 22:37:41 | LQ_CLOSE |
35,121,491 | How to build dynamic where in EF 6 query | <p>How to dynamically filter the results received from the EF.
I'm using EF 6. In previous versions of the EF it is very hard.
Maybe something has changed?
I know I can use filters, one after another, but it is not the most efficient way.
Is there a way to do it efficiently and elegantly with the EF 6.
On the internet I found a lot of information but they relate to previous versions of EF. </p>
| <c#><entity-framework><entity-framework-6> | 2016-02-01 00:52:08 | LQ_CLOSE |
35,121,560 | How to identify an optimal subsample from a data set with missing values in MATLAB | <p>I would like to identify the largest possible contiguous subsample of a large data set. My data set consists of roughly 15,000 financial time series of up to 360 periods in length. I have imported the data into MATLAB as a 360 by 15,000 numerical matrix.</p>
<p><a href="https://i.stack.imgur.com/qOnzk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qOnzk.png" alt="enter image description here"></a></p>
<p>This matrix contains a lot of NaNs due to some of the financial data not being available for the entire period. In the illustration, NaN entries are shown in dark blue, and non-NaN entries appear in light blue. It is these light blue non-NaN entries which I would like to ideally combine into an optimal subsample.</p>
<p>I would like to find the largest possible contiguous block of data that is contained in my matrix, while ensuring that my matrix contains a sufficient number of periods.</p>
<p>In a first step I would like to sort my matrix from left to right in descending order by the number of non-NaN entries in each column, that is, I would like to sort by the vector obtained by entering <code>sum(~isnan(data),1)</code>.</p>
<p>In a second step I would like to find the sub-array of my data matrix that is at least 72 entries along the first dimension and is otherwise as large as possible, measured by the total number of entries.</p>
<p>What is the best way to implement this?</p>
| <matlab> | 2016-02-01 01:01:28 | HQ |
35,122,257 | Promoting my GitHub repo | <p>I've just recently open-sourced my app, but I'm not entirely sure how to promote the GitHub repository. The whole idea of open-sourcing it was to get the power of the developer community on my side, but I'm not sure how to get people noticing the repo. Does anyone have any suggestions?</p>
| <github><open-source><uwp> | 2016-02-01 02:39:08 | LQ_CLOSE |
35,122,376 | How can I remove a file from Git within IntelliJ VCS? | <p>VCS has an <code>Add</code> option (Git Add) but seems to lack Git Remove.</p>
<p>What's the idiomatic way to Git Remove with VCS?</p>
| <git><intellij-idea><version-control> | 2016-02-01 02:55:11 | HQ |
35,122,750 | How to write this from javascript to JQuery | <p>Simple question I need these few lines of javascript in jquery.
Just trying to close a modal when I select outside of it.</p>
<p>Thank you.</p>
<pre><code> // When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == myModal) {
myModal.style.display = "none";
}
}
</code></pre>
| <javascript><jquery><window><simplemodal> | 2016-02-01 03:51:20 | LQ_CLOSE |
35,122,773 | single command to stop and remove docker container | <p>Is there any command which can combine the <code>docker stop</code> and <code>docker rm</code> command together ? Each time I want to delete a running container, I need to execute 2 commands sequentially, I wonder if there is a combined command can simplify this process.</p>
<pre><code>docker stop CONTAINER_ID
docker rm CONTATINER_ID
</code></pre>
| <docker> | 2016-02-01 03:53:59 | HQ |
35,123,540 | No suitable driver found for jdbc:oracle:thin:@localhost:1522:xe | <p>I am trying to create a connection to my database(oracle), when I put test my code using the main method, it works seamlessly.
However, when trying to access it through Tomcat 8, it fails with error:
No suitable driver found for "jdbc:oracle:thin:@localhost:1522:xe"
I have added ojdbc6 jar file to lib and also configured the built path.
The url,use, password is correct still it give the above error.
when i paste the same code in main it runs but in tomcat it doesn't.</p>
| <java><oracle><tomcat><servlets><jdbc> | 2016-02-01 05:29:10 | LQ_CLOSE |
35,123,671 | Android list view Base adapter getView fire multiple times? | <p><strong>This is my XML</strong>
</p>
<pre><code><RelativeLayout
android:id="@+id/preview_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/socialbottom"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Preview"
android:textColor="@color/white"
android:textStyle="bold" />
<ImageButton
android:id="@+id/close_preview_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="@drawable/close_btn" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/empty_view"
android:layout_below="@+id/preview_header">
<ListView
android:id="@+id/preview_dialog_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:divider="@android:color/transparent"
android:dividerHeight="8dp"
android:scrollbars="none"></ListView>
</RelativeLayout>
<View
android:id="@+id/empty_view"
style="@style/Space"
android:layout_width="match_parent"
android:layout_above="@+id/preview_add_more_btn"></View>
<Button
android:id="@+id/preview_add_more_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/empty_view1"
android:background="@color/content_text"
android:drawableLeft="@drawable/plus_icon"
android:drawablePadding="50dp"
android:gravity="center_horizontal"
android:padding="8dp"
android:paddingLeft="300dp"
android:text="@string/add_more"
android:textColor="@color/white" />
<View
android:id="@+id/empty_view1"
style="@style/Space"
android:layout_width="match_parent"
android:layout_above="@+id/footer_preview"></View>
<RelativeLayout
android:id="@+id/footer_preview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical">
<EditText
android:id="@+id/preview_input_timeline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:background="@color/acticty_textbox"
android:hint="What&apos;s up, admin?"
android:inputType="textMultiLine"
android:padding="8dp" />
<Button
android:id="@+id/preview_post_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/preview_input_timeline"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:background="@drawable/savebox"
android:padding="8dp"
android:text="Post"
android:textAllCaps="true"
android:textColor="@color/white"
android:textStyle="bold" />
</RelativeLayout>
</code></pre>
<p></p>
<p><strong>This is JAVA</strong></p>
<pre><code> public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(R.layout.preview_list_view, null);
ImageButton removeBtn = (ImageButton) convertView.findViewById(R.id.remove_preview);
ImageView imageView = (ImageView) convertView.findViewById(R.id.preview_image);
VideoView videoView = (VideoView) convertView.findViewById(R.id.preview_video);
Log.e("video sizzzessssssss", String.valueOf(imagesList.size()));
if (SocialActivity.MEDIA_TYPE_IMAGE == previewType) {
videoView.setVisibility(View.INVISIBLE);
imageView.setVisibility(View.VISIBLE);
String path = imagesList.get(position);
File imgFile = new File(path);
if (imgFile.exists()) {
// Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
// imageView.setImageBitmap(myBitmap);
Bitmap d = new BitmapDrawable(context.getResources(), imgFile.getAbsolutePath()).getBitmap();
int nh = (int) (d.getHeight() * (512.0 / d.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(d, 512, nh, true);
imageView.setImageBitmap(scaled);
}
} else {
imageView.setVisibility(View.INVISIBLE);
videoView.setVisibility(View.VISIBLE);
videoView.setVideoPath(imagesList.get(position));
MediaController mediaControls = new MediaController(SocialActivity.socialActivity);
videoView.setMediaController(mediaControls);
videoView.start();
videoView.pause();
Log.e("path video", imagesList.get(position));
}
removeBtn.setOnClickListener(new ListCustomClickEvents(callback, position));
return convertView;
}
</code></pre>
| <android><android-layout> | 2016-02-01 05:41:40 | LQ_CLOSE |
35,123,750 | whereNear query doesn't seem to work properly in Parse | <p>I'm working on an Android app related to Geolocations. I'm using Parse as backend.
I need to display results based on user's current location. </p>
<p>I'm using this query:</p>
<pre><code>ParseQuery<ParseObject> query = ParseQuery.getQuery("Restaurants");
ParseGeoPoint sLatlong = new ParseGeoPoint(currentLat, currentLong);
query.whereNear("rest_location", sLatlong);
</code></pre>
<p>But the results are not sorted distance wise. </p>
<p>Can someone help me out. </p>
| <android><parse-platform> | 2016-02-01 05:49:33 | HQ |
35,123,856 | How to set objects around circle correctly on UIView | <p>I've write some code to place objects around circle that locate on center of the Custom view, but it not perfectly around the circle. I don't know where of the code is wrong.</p>
<p><a href="https://i.stack.imgur.com/HfTDD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HfTDD.png" alt="enter image description here"></a></p>
<p>Here is the code:</p>
<pre><code>func createObjectsAroundCircle() {
let center = CGPointMake(bounds.width/2 ,bounds.height/2)
let radius : CGFloat = 100
let count = 20
var angle = CGFloat(2 * M_PI)
let step = CGFloat(2 * M_PI) / CGFloat(count)
let circlePath = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.CGPath
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.strokeColor = UIColor.redColor().CGColor
shapeLayer.lineWidth = 3.0
self.layer.addSublayer(shapeLayer)
// set objects around circle
for var index = 0; index < count ; index++ {
let x = cos(angle) * radius + center.x
let y = sin(angle) * radius + center.y
let label = UILabel()
label.text = "\(index)"
label.frame.origin.x = x
label.frame.origin.y = y
label.font = UIFont(name: "Arial", size: 20)
label.textColor = UIColor.blackColor()
label.sizeToFit()
self.addSubview(label)
angle += step
}
}
</code></pre>
| <ios><swift> | 2016-02-01 05:57:42 | HQ |
35,123,890 | What is a DOMString really? | <p>I came across <code>DOMString</code> while reading the <a href="https://html.spec.whatwg.org/" rel="noreferrer">HTML spec</a>. On some research, found the following data regarding it:</p>
<p>From <a href="https://developer.mozilla.org/en/docs/Web/API/DOMString" rel="noreferrer">MDN</a>: </p>
<blockquote>
<p>DOMString is a UTF-16 String. As JavaScript already uses such strings,
DOMString is mapped directly to a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String" rel="noreferrer">String</a>.</p>
</blockquote>
<p>From <a href="https://www.w3.org/TR/DOM-Level-3-Core/core.html#DOMString" rel="noreferrer">W3C spec</a>:</p>
<blockquote>
<p>A <a href="https://www.w3.org/TR/DOM-Level-3-Core/core.html#DOMString" rel="noreferrer">DOMString</a> is a sequence of <a href="https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-16-bit-unit" rel="noreferrer">16-bit units</a>.</p>
</blockquote>
<p>But I still have the following questions:</p>
<ol>
<li>What is a <code>DOMString</code> actually and what is it used for?</li>
<li>Why is it named as <strong>DOM</strong>String and not <strong>UTF16</strong>String? More specifically, how does it relate to DOM?</li>
<li>If I UTF-16 encode a <code>String</code>, does it become a <code>DOMString</code>?</li>
</ol>
| <javascript><html><dom> | 2016-02-01 06:00:22 | HQ |
35,124,065 | What will perform better? | <p>I do have 'topics', each 'topic' has 'questions'. Both, topics and questions, have 'statistics' that will be updated at every use. </p>
<p>Should I create 'questions' as a subfield of 'topic' documents? Or I must create a collection named 'questions' and relate it to 'topic' using sort of a foreign key? </p>
<p>Further, using the independent 'questions' collections will make it 'harder/expensive' to list all the questions related with a topic? </p>
<p>I'm so noob </p>
| <mongodb><meteor><database-design> | 2016-02-01 06:15:44 | LQ_CLOSE |
35,124,179 | How print first and last row in an array using C | I have m x m array and i am trying to find out first and last row of a given matrix (using C) which is
e.g mat[3][3]={1,2,3,
4,5,6,
7,8,9};
But i could not figure out how to get first and last row using c. If some have the algorithm then please share with me.
| <c> | 2016-02-01 06:24:52 | LQ_EDIT |
35,125,912 | How to do a 2d quadratic fit in C++? | <p>How would you perform a 2d quadratic fit in C++? The equation to fit is of the form:</p>
<pre><code>f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
</code></pre>
<p>where a, b, c, d, e and f are the fit parameters. Is it straightforward to write? Is there a library that is free to use for that?</p>
| <c++><math> | 2016-02-01 08:25:54 | LQ_CLOSE |
35,126,349 | React-native android ignores navigator.geolocation.getCurrentPosition | <p>I'm trying to use <code>navigator.geolocation.getCurrentPosition</code> on my Android device (Philips Xenium). It works absolutely ok in iphone and genimotion simulator.<br>
<code>navigator.geolocation.getCurrentPosition</code> returns absolutely nothing - no errors, no success.
However, if I turn off geolocation service in my smartphone, it returns <code>No available location provider</code>.</p>
<p>Also, <code>navigator.geolocation.watchPosition</code> works fine.</p>
| <android><geolocation><react-native> | 2016-02-01 08:55:23 | HQ |
35,126,428 | Dynamic breadcrumbs using react router | <p>There is very good example of how to make a <a href="https://github.com/rackt/react-router/blob/master/examples/breadcrumbs/app.js" rel="noreferrer">breadcrumbs on site in examples folder of react-router repo</a>. But I'm wondering how to make breadcrumbs with dynamic routes.</p>
<p>Assume we have this configuration:</p>
<pre><code>ReactDOM.render((
<Router history={browserHistory}>
<Route path="/projects" component={ProjectsApp}>
<IndexRoute component={ProjectsDashboard} />
<Route path=":projectId" component={ProjectBoard}>
<Route path=":taskId" component={ProjectTaskBoard}>
</Route>
</Route>
</Router>
), document.getElementById('app'));
</code></pre>
<p>I want to make something like this:</p>
<p><em>Projects(link to '/projects') -> MyAwesomeProject (link to '/projects/11'. Title taken from somewhere (from store by id from routeParams or by another way)) -> MyTask (link to '/projects/11/999')</em></p>
<p>How can I achieve this result? Are there any best practices? Thanks.</p>
| <reactjs><react-router> | 2016-02-01 08:59:56 | HQ |
35,126,670 | android: data binding error: cannot find symbol class | <p>I am getting started for using <code>DataBinding</code> feature. I am facing problem with it.</p>
<blockquote>
<p>Error:(21, 9) error: cannot find symbol class
ContactListActivityBinding</p>
</blockquote>
<p><strong>build.gradle(Module: app)</strong></p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.letsnurture.ln_202.databindingdemo"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
}
</code></pre>
<p><strong>ContactListActivity.java</strong></p>
<pre><code>import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.letsnurture.ln_202.databindingdemo.model.Contact;
public class ContactListActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContactListActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_contact_list);
Contact user = new Contact("Chintan Soni", "+91 9876543210");
binding.setContact(user);
// setContentView(R.layout.activity_contact_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_contact_list, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p><strong>content_contact_list.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.letsnurture.ln_202.databindingdemo.ContactListActivity"
tools:showIn="@layout/activity_contact_list">
<data>
<variable
name="user"
type="com.letsnurture.ln_202.databindingdemo.model.Contact" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="@dimen/activity_horizontal_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.contactName}"
tools:text="Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.contactNumber}"
tools:text="Number" />
</LinearLayout>
</layout>
</code></pre>
<p><strong>activity_contact_list.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.letsnurture.ln_202.databindingdemo.ContactListActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_contact_list" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
</code></pre>
| <android><android-databinding> | 2016-02-01 09:13:39 | HQ |
35,127,002 | Material UI doesn't select a SelectField on hitting 'tab' | <p>Using <a href="http://www.material-ui.com/" rel="noreferrer">Material UI</a> for some components in my app.
I added a <code><SelectField /></code> <a href="http://www.material-ui.com/#/components/select-field" rel="noreferrer">select field</a> in a form. </p>
<p>Is there a way to make it work like a normal HTML <code><select></code> element, so that: </p>
<ul>
<li>When you hit <code>tab</code> on the keyboard, it highlights it when it's supposed to</li>
<li>When you hit <code>space</code> on the keyboard, it opens the dropdown</li>
</ul>
<p>Thanks in advance for your help. </p>
| <javascript><reactjs><material-design><material-ui> | 2016-02-01 09:30:31 | HQ |
35,127,109 | Date and time in 24 hours format | <p>I have a date in this format <code>Fri, 15 Jan 2016 15:14:10 +0800</code>, and I want to display time like this <code>2016-01-15 15:14:10</code>.</p>
<p>What I tried is:</p>
<pre><code>$test = 'Fri, 15 Jan 2016 15:14:10 +0800';
$t = date('Y-m-d G:i:s',strtotime($test));
echo $t;
</code></pre>
<p>But it is displaying date in this format: <code>2016-01-15 7:14:10</code>, it should be <code>2016-01-15 15:14:10</code>.</p>
<p>How can i do this?</p>
| <php><mysql><date><datetime><datetime-format> | 2016-02-01 09:36:02 | HQ |
35,127,257 | How to get the size of a filtered (piped) set in angular2 | <p>I wrote my own filter pipe as it disappeared in angular2:</p>
<pre><code>import {Pipe, PipeTransform} from 'angular2/core';
@Pipe({
name: 'myFilter'
})
export class MyFilter implements PipeTransform {
transform(customerData: Array<Object>, args: any[]) {
if (customerData == undefined) {
return;
}
var re = new RegExp(args[0]);
return customerData.filter((item) => re.test(item.customerId));
}
}
</code></pre>
<p>And use it in my template:</p>
<pre><code><tr *ngFor="#singleCustomerData of customerData | myFilter:searchTerm">
...
</tr>
</code></pre>
<p>Now I'd like to see how many matches the pipe returns. So essentially the size of the returned array.</p>
<p>In angular 1.x we were able so assign the returned set to a variable in a template like so:</p>
<pre><code><div ng-repeat="person in filtered = (data | filter: query)">
</div>
</code></pre>
<p>But we can no longer assign variables in templates in angular2.</p>
<p>So how do I get the size of the filtered set without calling the filter twice?</p>
| <filter><typescript><pipe><angular> | 2016-02-01 09:43:22 | HQ |
35,127,383 | npm http-server with SSL | <p>I'm using the npm package "http-server" (<a href="https://www.npmjs.com/package/http-server" rel="noreferrer">https://www.npmjs.com/package/http-server</a>) to set up a simple webserver, but I cannot get it to use SSL. My command in package.json is</p>
<pre><code>http-server -p 8000 -o -S
</code></pre>
<p>with a cert.pem and key.pem in my root directory (for now). The "-o" option opens a browser to the default page, but the page is served using HTTP and not even accessible through HTTPS. I don't get any errors or warnings. I've also tried adding the "-C" and "-K" options without luck. Has any one had any success with this package?</p>
| <node.js><ssl><npm><httpserver> | 2016-02-01 09:50:09 | HQ |
35,127,478 | VB equivalent code to C#; List of Strings | <p>What is the equivalent of the following code in C#?</p>
<pre><code>Dim intValidChars As New List(Of Integer)(New Integer() { Asc("0"), Asc("1"), Asc("2"), Asc("3"), Asc("4"), Asc("5"), Asc("6"), Asc("7"), Asc("8"), Asc("9"), _
Asc("A"), Asc("B"), Asc("C"), Asc("D"), Asc("E"), Asc("F"), Asc("G"), Asc("H"), Asc("I"), Asc("J")})
</code></pre>
<p>Thanks in advance.</p>
| <c#><vb.net><string><list><integer> | 2016-02-01 09:54:25 | LQ_CLOSE |
35,127,520 | asyncio queue consumer coroutine | <p>I have a <code>asyncio.Protocol</code> subclass receiving data from a server.
I am storing this data (each line, because the data is text) in a <code>asyncio.Queue</code>.</p>
<pre><code>import asyncio
q = asyncio.Queue()
class StreamProtocol(asyncio.Protocol):
def __init__(self, loop):
self.loop = loop
self.transport = None
def connection_made(self, transport):
self.transport = transport
def data_received(self, data):
for message in data.decode().splitlines():
yield q.put(message.rstrip())
def connection_lost(self, exc):
self.loop.stop()
loop = asyncio.get_event_loop()
coro = loop.create_connection(lambda: StreamProtocol(loop),
'127.0.0.1', '42')
loop.run_until_complete(coro)
loop.run_forever()
loop.close()
</code></pre>
<p>I want to have another coroutine responsible for consuming the data in the queue and processing it.</p>
<ul>
<li>Should this be a <code>asyncio.Task</code>?</li>
<li>What if the queue becomes empty because for a few seconds no data is received? How can I make sure my consumer doesn't stop (<code>run_until_complete</code>)?</li>
<li>Is there a cleaner way than using a global variable for my queue?</li>
</ul>
| <python><python-3.x><coroutine><python-asyncio> | 2016-02-01 09:56:40 | HQ |
35,127,818 | Android: Get Notified when the current Mode inside AudioManager gets changed | <p>In Android I need to get notified when the current <strong>audio mode</strong> gets changed.</p>
<p>I can get this value through <a href="http://developer.android.com/reference/android/media/AudioManager.html#getMode()" rel="noreferrer">getMode()</a> but this is polling. </p>
<p>I don't want to poll every few seconds. </p>
<p>What are my options? </p>
<p>(Please note that I'm not asking about ringerMode)</p>
| <android><android-audiomanager> | 2016-02-01 10:10:50 | HQ |
35,127,954 | Hi again XD, now I'm trying to kill/re-spawn my enemy each time my player goes through the doors | import pygame
import os,sys
import random
import math
img_path = os.path.join("punch.png")
img_blob = os.path.join("blob.png")
img_bullet = os.path.join("bullet.png")
img_heart = os.path.join("heart.png")
score = 0
class Actor(pygame.sprite.Sprite):
def __init__(self, x, y):
super(Actor,self).__init__()
self.image = pygame.Surface([116,116])
self.image.set_colorkey(black)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.speed = 2
class Enemy(Actor):
def __init__(self, x, y):
super(Enemy, self).__init__(x, y)
self.target = None
self.image.blit(pygame.image.load(img_blob),(0,0))
def update(self, enemies):
if self.target:
dx,dy = self.target.rect.x - self.rect.x, self.target.rect.y - self.rect.y
dist = math.hypot(dx,dy)
dx,dy = dx / dist,dy / dist
self.rect.x += dx * self.speed
self.rect.y += dy * self.speed
class Character(Actor):
def __init__(self, x = 275, y = 250):
super(Character, self).__init__(x, y)
self.speed = 10
self.image.blit(pygame.image.load(img_path),(0,0))
self.score = 0
self.heart = 5
def update(self, enemies):
if pygame.sprite.spritecollide(self, enemies, False):
self.heart -= 1
pygame.sprite.spritecollide(self, enemies, True)
key = pygame.key.get_pressed()
if key[pygame.K_w]:
self.rect.y -= self.speed
elif key[pygame.K_s]:
self.rect.y += self.speed
if key[pygame.K_a]:
self.rect.x -= self.speed
elif key[pygame.K_d]:
self.rect.x += self.speed
if self.rect.x > 1110:
self.rect.x = 1110
if self.rect.y < 20:
self.rect.y = 20
elif self.rect.y > 710:
self.rect.y = 710
if self.rect.x <20:
self.rect.x = 20
elif self.rect.x == 1110 and self.rect.y > 300 and self.rect.y < 400:
self.rect.x = 25
if self.rect.y == 20 and self.rect.x >500 and self.rect.x < 600:
self.rect.y = 715
elif self.rect.x == 20 and self.rect.y > 300 and self.rect.y < 400:
self.rect.x = 1090
if self.rect.y == 710 and self.rect.x >500 and self.rect.x < 600:
self.rect.y = 25
class Bullet(pygame.sprite.Sprite):
def __init__(self,mouse,bird):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(img_bullet)
self.mouse_x,self.mouse_y = mouse[0], mouse[1]
self.bird = bird
self.rect = self.image.get_rect()
def update(self,enemies):
if pygame.sprite.spritecollide(self, enemies, False):
bird.score += 10
pygame.sprite.spritecollide(self, enemies, True)
speed = -10.
range = 50
distance = [self.mouse_x - self.bird[0],self.mouse_y - self.bird[1]]
norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2)
direction = [distance[0] / norm, distance[1] / norm]
bullet_vector = [direction[0] * speed,direction[1] * speed]
self.rect.x -=bullet_vector[0]
self.rect.y -= bullet_vector[1]
pygame.init() # Pygame is initialised (starts running)
players = pygame.sprite.Group()
screen = pygame.display.set_mode([1250,850]) # Set the width and height of the screen [width,height]
pygame.display.set_caption("My Game") # Name your window
background_image = pygame.image.load("untilted.png")
done = False # Loop until the user clicks the close button.
clock = pygame.time.Clock() # Used to manage how fast the screen updates
black = ( 0, 0, 0) # Define some colors using rgb values. These can be
white = ( 255, 255, 255) # used throughout the game instead of using rgb values.
font = pygame.font.Font(None,36)
# Define additional Functions and Procedures here
score = 0
bird = Character()
bullet = Bullet(pygame.mouse.get_pos(),[bird.rect.x,bird.rect.y])
blob = Enemy(random.randint(200,1000),random.randint(200,300))
blob.target=bird
all_sprites = pygame.sprite.Group([blob, bird])
enemies = pygame.sprite.Group([blob])
# -------- Main Program Loop -----------
while done == False:
for event in pygame.event.get(): # Check for an event (mouse click, key press)
key = pygame.key.get_pressed()
if event.type == pygame.QUIT: # If user clicked close window
done = True # Flag that we are done so we exit this loop
elif key[pygame.K_e]:
bullet = Bullet(pygame.mouse.get_pos(),[bird.rect.x,bird.rect.y])
bullet.rect.x = bird.rect.x
bullet.rect.y = bird.rect.y
all_sprites.add(bullet)
screen.blit(background_image, (0, 0))
all_sprites.update(enemies)
all_sprites.draw(screen)
textImg = font.render("Score: " + str(bird.score),1,white)
textImg2 = font.render("Lives: " + str(bird.heart),1,white)
screen.blit(textImg,(10,10))
screen.blit(textImg2,(150,10))
pygame.display.update() # Go ahead and update the screen with what we've drawn.
clock.tick(20) # Limit to 20 frames per second
if bird.heart == 0:
pygame.quit()
pygame.quit()
so in the Character class, in the update part, the bottom of it is where it is going through the doors, but when it goes through the doors, i an wanting to kill the enemy and then re-spawn it so it looks as if the player is going into a different room. | <python><pygame><kill> | 2016-02-01 10:16:59 | LQ_EDIT |
35,127,981 | text-align: -webkit-center vs text-align: center | <p>Does anyone know why there is a difference between text-align: center and , text-align:-webkit-center ? For example if you have :</p>
<pre><code><section>
<h1>Title<h1>
<div class="image"></div>
</section>
</code></pre>
<p>// CSS with text-align: center;</p>
<pre><code>section{
text-align: center;
}
</code></pre>
<p>This will center just the text</p>
<p>// CSS with text-align: -webkit-center</p>
<pre><code>section{
text-align: -webkit-center;
}
</code></pre>
<p>This will center the text and the image.</p>
<p>Same goes for text-align: -moz-center;</p>
| <css> | 2016-02-01 10:18:25 | HQ |
35,128,229 | Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm | <p>I want to compile an open source android project (Netguard) using gradel (<code>gradlew clean build</code>) But I encountered this Error:</p>
<pre><code>A problem occurred configuring project ':app'.
> Exception thrown while executing model rule: NdkComponentModelPlugin.Rules#cre
ateToolchains
> No toolchains found in the NDK toolchains folder for ABI with prefix: llvm
</code></pre>
<p>I serached but didn't find enything helping. Here is the main <code>build.gradle</code>:</p>
<pre><code>buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle-experimental:0.6.0-alpha1'
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p>And here is the <code>build.gradle</code> of the <code>app</code> project:</p>
<pre><code>apply plugin: 'com.android.model.application'
model {
android {
compileSdkVersion = 23
buildToolsVersion = "23.0.2"
defaultConfig.with {
applicationId = "eu.faircode.netguard"
minSdkVersion.apiLevel = 21
targetSdkVersion.apiLevel = 23
versionCode = 2016011801
versionName = "0.76"
archivesBaseName = "NetGuard-v$versionName-$versionCode"
}
}
android.ndk {
moduleName = "netguard"
toolchain = "clang"
ldLibs.add("log")
}
android.sources {
main {
jni {
source {
srcDir "src/main/jni/netguard"
}
exportedHeaders {
}
}
}
}
android.buildTypes {
release {
minifyEnabled = true
proguardFiles.add(file('proguard-rules.pro'))
ndk.with {
debuggable = true
}
}
}
android.buildTypes {
debug {
ndk.with {
debuggable = true
}
}
}
android.productFlavors {
create("all") {
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.1.+'
compile 'com.android.support:recyclerview-v7:23.1.+'
compile 'com.squareup.picasso:picasso:2.5.+'
}
</code></pre>
<p>And I'm using <code>gradle-2.9-all</code> and <code>android-ndk-r10e</code>. I don't know if I should mention anything else, so comment if you need any information.</p>
| <android><android-ndk><android-gradle-plugin> | 2016-02-01 10:29:48 | HQ |
35,128,646 | Don't trigger the parent event when clicking on the child element | <p>See my snippet, as I click the parent element, the child element is shown but as I click the child element, the parent element events seems also triggered along with the child elements event, any ideas to trigger only parent elements event when on click and only child elements event when on click (must not bubble the parent elements event)? any ideas, help, clues, suggestions, recommendations please?</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){
$("#child").hide();
$("#parent").click(function(){
alert("parent event is triggered");
$("#child").show();
});
$("#child").click(function(){
alert("child event is triggered");
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#parent{
padding: 15px;
border: 3px dotted #cccccc;
}
#child{
padding: 4px;
border: 1px solid blue;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
This is parent element, click to show the child element
<div id="child">Child</div>
</div></code></pre>
</div>
</div>
</p>
| <javascript><jquery> | 2016-02-01 10:50:57 | LQ_CLOSE |
35,129,135 | Valgrind reporting a segment overflow | <p>When running my program with valgrind / callgrind I get the following message a lot:</p>
<p><code>==21734== brk segment overflow in thread #1: can't grow to 0x4a39000</code>
(with different addresses)</p>
<p>Note that it is not preceded by a stack overflow message.</p>
<p>I can't find any documentation on this message and I have no idea what is overflowing exactly.</p>
<p>Can anybody help me figure out what the problem is? Is this a problem of valgrind, or of my program?</p>
| <c++><overflow><valgrind><callgrind> | 2016-02-01 11:15:49 | HQ |
35,129,773 | Android push notification offline | <p>im trying to implement push notification in my app,already using GCM. But the case is i want it in the way which works offline too.
i.e: for multiple conditions inside android app it should trigger push notification.</p>
<p>Currently im trying : </p>
<pre><code>NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher);
contentView.setTextViewText(R.id.title, title);
contentView.setTextViewText(R.id.text, msg);
notification.contentView = contentView;
Intent notificationIntent = new Intent(this, HomeActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,randomNo, notificationIntent, 0);
</code></pre>
<p>But the problem is,
1.When the app doesnt running ,the notification arrives but it cases screen to blink(becoz i call it using intent).
2.i want to use same class for multiple conditions and forward it to different activities(currently i cant change the intent to another activity based on condtiop).</p>
| <java><android><push-notification><google-cloud-messaging> | 2016-02-01 11:48:42 | LQ_CLOSE |
35,129,977 | How to install latest version of openssl Mac OS X El Capitan | <p>I have used <code>brew install openssl</code> to download and install openssl v1.0.2f, however, it comes back saying:</p>
<pre><code>A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
/usr/local/etc/openssl/certs
and run
/usr/local/opt/openssl/bin/c_rehash
This formula is keg-only, which means it was not symlinked into /usr/local.
Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries
Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:
LDFLAGS: -L/usr/local/opt/openssl/lib
CPPFLAGS: -I/usr/local/opt/openssl/include
</code></pre>
<p>And when I do <code>openssl version -a</code> it always gives me:</p>
<pre><code>OpenSSL 0.9.8zg 14 July 2015
built on: Jul 31 2015
platform: darwin64-x86_64-llvm
options: bn(64,64) md2(int) rc4(ptr,char) des(idx,cisc,16,int) blowfish(idx)
compiler: -arch x86_64 -fmessage-length=0 -pipe -Wno-trigraphs -fpascal-strings -fasm-blocks -O3 -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -DL_ENDIAN -DMD32_REG_T=int -DOPENSSL_NO_IDEA -DOPENSSL_PIC -DOPENSSL_THREADS -DZLIB -mmacosx-version-min=10.6
OPENSSLDIR: "/System/Library/OpenSSL"
</code></pre>
<p>How can I replace the old version with the new one? I've searched a lot on how to do this, but the solutions online don't seem to work for me...</p>
| <macos><openssl><homebrew> | 2016-02-01 11:58:35 | HQ |
35,130,013 | How to get attribute name instead of slug in variation? | <p>I need to get attribute from woocommerce product variation. </p>
<pre><code>$terms = get_post_meta($value['variation_id'], 'attribute_pa_color', true);
</code></pre>
<p>This code is giving me an attribute slug instead of name. How can I get attribute name?</p>
<p>Thank you so much in advance!</p>
| <php><variables><attributes><woocommerce><slug> | 2016-02-01 12:00:01 | HQ |
35,130,051 | Order of notify handlers | <p>I have a task:</p>
<pre><code>- name: uploads docker configuration file
template:
src: 'docker.systemd.j2'
dest: '/etc/systemd/system/docker.service'
notify:
- daemon reload
- restart docker
</code></pre>
<p>in Ansible playbook's <a href="http://docs.ansible.com/ansible/playbooks_intro.html" rel="noreferrer">documentation</a>, there is a sentence:</p>
<blockquote>
<p>Notify handlers are always run in the order written.</p>
</blockquote>
<p>So, it is expected, that <strong>daemon reload</strong> will be ran before <strong>restart docker</strong>, but in logs, i have:</p>
<pre>
TASK [swarm/docker : uploads docker configuration file] ************************
…
NOTIFIED HANDLER daemon reload
NOTIFIED HANDLER restart docker
…
RUNNING HANDLER [swarm/docker : restart docker] ********************************
…
RUNNING HANDLER [swarm/docker : daemon reload] *********************************
…
</pre>
<p>There are no more "NOTIFIED HANDLER" in logs. Can anyone explain, what i'm doing wrong? :(</p>
| <ansible> | 2016-02-01 12:02:03 | HQ |
35,130,119 | Linux configuration -- ssmtp: Cannot open smtp.gmail.com:587 | <p>Hi I have RHEL5 with ssmtp installed on it ssmtp-2.61-22.el5.i386.rpm</p>
<p>my /etc/ssmtp/ssmtp.conf updated as below :-</p>
<pre><code>AuthUser=mymail@gmail.com
AuthPass=mypassword
FromLineOverride=YES
mailhub=smtp.gmail.com:587
UseSTARTTLS=YES
UseTLS=Yes
RewriteDomain=gmail.com
</code></pre>
<p>also revaliases updated as below :</p>
<pre><code>root:mymail@gmail.com:smtp.gmail.com:587
</code></pre>
<p>i have shutdown sendmail service </p>
<p>when i try to send email with ssmtp i get below error </p>
<pre><code>[root@ctmtest ssmtp]# echo "test" | ssmtp -vvv mymail@gmail.com
[<-] 220 smtp.gmail.com ESMTP v26sm42795996pfi.56 - gsmtp
[->] EHLO ctmtest
[<-] 250 SMTPUTF8
[->] STARTTLS
[<-] 220 2.0.0 Ready to start TLS
ssmtp: Cannot open smtp.gmail.com:587
</code></pre>
<p>i searched lots of tag with this error , but unable to fix this </p>
<p>my system is able to connect smtp.gmail.com on port 587</p>
<pre><code>[root@ctmtest ssmtp]# telnet smtp.gmail.com 587
Trying 74.125.200.108...
Connected to smtp.gmail.com (74.125.200.108).
Escape character is '^]'.
220 smtp.gmail.com ESMTP o90sm11695907pfi.17 - gsmtp
</code></pre>
<p>is there anyone who have fixed this ? please suggest </p>
| <linux><gmail><mailx><ssmtp> | 2016-02-01 12:06:03 | HQ |
35,131,143 | How to enable Live Visual Tree and Live Property Explorer in Visual Studio | <p>I'm running a .Net 4.5 WPF application in Visual Studio 2015 Update 1 in a Debug build configuration.</p>
<p>In Tools > Options > Debugging > General I have checked Enable UI Debugging Toos for XAML and Preview selected elements in Live Visual Tree.</p>
<p>However, when I run my application, both the Live Property Explorer and Live Visual Tree Windows display the following message.</p>
<p>UI Debugging is either disabled, not supported by the current application or the application execution is paused.</p>
<p>What am I missing?</p>
| <c#><wpf><visual-studio-2015> | 2016-02-01 12:57:08 | HQ |
35,131,615 | what is difference between < length() and <=length()-1? | <pre><code>'String s=" ";'//java developer
for(int i=0;i<=arg0.length()-1;i++)//it's subtracts
</code></pre>
<p>i.e length()=10-1=9.?? otherwise it's index starts from 0?
Hope u guys </p>
| <java> | 2016-02-01 13:20:46 | LQ_CLOSE |
35,131,814 | How to script Gradle in order to publish shadowjar into Artifactory | <p>I am using shadowJar in my java project.
I would like to push the outcome into artifactory.</p>
<p>My gradle script look like this, I am not sure how to connect the dots:</p>
<pre><code>shadowJar {
baseName = 'com.mycompany.myapp'
manifest {
attributes 'Main-Class': 'myapp.starter'
}
}
]
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'maven'
apply plugin: 'com.github.johnrengelman.shadow'
// rep for the project
repositories {
mavenCentral()
maven {
url 'http://repo.company:8081/artifactory/libs-release'
credentials {
username = "${repo_user}"
password = "${repo_password}"
}
}
maven {
url 'http://repo.company:8081/artifactory/libs-snapshot'
credentials {
username = "${repo_user}"
password = "${repo_password}"
}
}
}
publishing {
publications {
mavenJava(MavenPublication) {
from components.java
artifact sourceJar {
classifier "sources"
}
}
}
}
</code></pre>
<p>How do I code gradle to take the shadowjar file?</p>
<p>thanks,
ray.</p>
| <java><gradle><build> | 2016-02-01 13:31:12 | HQ |
35,131,861 | What does the --pre option in pip signify? | <p>I saw on <a href="https://github.com/neo4j-contrib/neo4j_doc_manager" rel="noreferrer">this</a> page that <code>pip install neo4j-doc-manager --pre</code> was used. What does the <code>--pre</code> flag mean?</p>
| <python><pip> | 2016-02-01 13:33:16 | HQ |
35,132,427 | Why its happening? | So, i'm tryin' to create a full width navbar using bootstrap, but theres a kind of limit in my nav [LIKE THIS][1]
This is my html:
<div class="row">
<div class="col-md-12 text-center">
<nav class="navbar navbar-default">
<div class="container-fluid">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Features</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</div>
</nav>
</div>
</div>
This is my css:
@import url(https://fonts.googleapis.com/css?family=Raleway:400,700,300,100);
body {
font-family: "Raleway", Sans-Serif;
font-weight: 400;
}
p {
text-align: justify;
font-size: 16px;
}
.navbar {
font-weight: 700;
letter-spacing: 2px;
text-transform: uppercase;
}
.navbar-default .navbar-nav .active a,
.navbar-default .navbar-nav .active a:focus,
.navbar-default .navbar-nav .active a:hover,
.navbar-default .navbar-nav li a:hover{
color:#e1b315;
}
.navbar .navbar-nav {
display: inline-block;
float: none;
}
.navbar-default .navbar-nav li {
margin: 0 15px;
}
I'm not certainly about why that happens =/
What i'm really tryin' to do is something [LIKE THIS][2]
[1]: http://i.stack.imgur.com/PJn5N.png
[2]: http://i.stack.imgur.com/kZgRo.png | <html><css><twitter-bootstrap> | 2016-02-01 14:00:23 | LQ_EDIT |
35,132,459 | how to create mysql database backup file in windows | <p>I wrote the following code in cmd but it showing an error </p>
<pre><code>> cd C:\Program Files\MySQL\MySQL Server 5.5\bin
> mysqldump.exe –e –u[username] -p[password] [database name] > C:\[filename].sql
</code></pre>
<p>error</p>
<blockquote>
<p>A required privilege is not held by client</p>
</blockquote>
| <mysql> | 2016-02-01 14:02:07 | LQ_CLOSE |
35,132,566 | How to Use LoginGdi+ theme | <p>Guys would you please tell me how to use this theme in my project ?
I like this theme & I want to know how to use it<br>
the theme link <a href="http://xertzproductions.weebly.com/login-gdi-theme.html" rel="nofollow">http://xertzproductions.weebly.com/login-gdi-theme.html</a>
I tried but I failed !
thanks in advance</p>
| <vb.net> | 2016-02-01 14:06:32 | LQ_CLOSE |
35,133,202 | How can I read a text from a php site with javascript | <p>my php site will echo a number. Now I want to read the content with JavaScript. How can i do this.</p>
| <javascript><php> | 2016-02-01 14:37:04 | LQ_CLOSE |
35,133,317 | NumPy save some arrays at once | <p>I working on different shapes of arrays and I want to save them all with <code>numpy.save</code>, so, consider I have </p>
<pre><code>mat1 = numpy.arange(8).reshape(4, 2)
mat2 = numpy.arange(9).reshape(2, 3)
numpy.save('mat.npy', numpy.array([mat1, mat2]))
</code></pre>
<p>It works. But when I have two matrices with one dimension of same size it's not working. </p>
<pre><code>mat1 = numpy.arange(8).reshape(2, 4)
mat2 = numpy.arange(10).reshape(2, 5)
numpy.save('mat.npy', numpy.array([mat1, mat2]))
</code></pre>
<p>It causes<br>
<code>Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: could not broadcast input array from shape (2,4) into shape (2)</code></p>
<p>And note that the problem caused by <code>numpy.array([mat1, mat2])</code> and not by <code>numpy.save</code></p>
<p>I know that such array is possible:</p>
<p><code>>> numpy.array([[[1, 2]], [[1, 2], [3, 4]]])
array([[[1, 2]], [[1, 2], [3, 4]]], dtype=object)</code></p>
<p>So, all of what I want is to save two arrays as <code>mat1</code> and <code>mat2</code> at once.</p>
| <python><arrays><numpy> | 2016-02-01 14:41:27 | HQ |
35,133,480 | Error Messages when I try to load ggplot2 after installatio | I get an error message when i try to load ggplot2 even after download.
Even when i tried:
install.packages('ggplot2',dependencies = T)
I get the following error message:
No package called 'Rcpp'
Error:package or namespace load failed for ggplot2.
Then i try:
install.packages('Rcpp')
i get Rcpp successfully downloaded, but when i try to load ggplot2 i get thesame error message:
No package called 'Rcpp'
Error:package or namespace load failed for ggplot2.
I was using R 3.2.1 but updated to R 3.2.3
I would appreciate any meaningful help. | <r> | 2016-02-01 14:49:50 | LQ_EDIT |
35,133,507 | How do linked list work if nothing has been added to them and you try to pring that variable. | I have a linked list and want to print it out in the end. My questions is, if the linked list variable in the struct is left untouched and nothing is added to the list, if I try to print using `while(school->student != NULL)` will this work?
Note: I have no made the list NULL at any point, I have just allocated name and not touched the list.
struct School{
char *name;
Student *list; <--- Linked list
} School;
struct Student{
char *name;
Student *next;
} Student;
Now if I want to print this list will this work? | <c><linked-list> | 2016-02-01 14:51:32 | LQ_EDIT |
35,134,036 | Macro to fill down based on number contents of adjacent cell or other sheet | I've seen a few other posts similar to this but I can seem to get mine to work. Right now I have data in Column A, from A5 to A50 but the end point is subject to change. I am looking for a macro to select B5 to Y5 and fill down to the end of column A (in this case to row 50, but this will change every time).
The amount of rows depends on another sheet. As an alternative to my question above, if there is a way to go to the other sheet, and count the rows in column A, from A4 down and then fill down in my other sheet that amount that would be just as good.
**Summary**
- I have one sheet with the data, starting at A4 and going down for an amount that will be changing.
- I would like to be able to fill down on another sheet the number of rows there are in the first sheet.
Hopefully this makes sense, and thanks for the help. | <vba><excel> | 2016-02-01 15:17:55 | LQ_EDIT |
35,134,344 | This program crashes | I made up some program that view the 7*7 table of powered by....
It's work, but from some reason the program crash at the end of the program.
My compiler is GCC and I'm using C99.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <string.h>
#define LENGTH 7
void printsTable(int arr[LENGTH][],int len);
int main()
{
int table[LENGTH][LENGTH] = {0};
int i = 0, j = 0;
for(j = 1; j <= LENGTH; j++)
{
for(i = 1; i <= LENGTH; i++)
{
table[j][i] = pow(j,i);
}
}
printsTable(table,LENGTH);
return 0;
}
void printsTable(int arr[][LENGTH],int len)
{
int i = 0, j = 0;
for(i = 1; i <= LENGTH; i++)
{
for(j = 1; j <= LENGTH; j++)
{
printf("%d\t", arr[i][j]);
}
printf("\n");
}
}
thanks :) | <c><arrays><loops> | 2016-02-01 15:34:28 | LQ_EDIT |
35,134,661 | Are there any examples of serious websites using riot.js? | <p>I have scoured the internet (clicked next page on google a couple of times) and the riot.js docs, and can't find a single high traffic website that uses riot.js. </p>
<p>Are there any large scale websites/webapps using riot.js?</p>
| <javascript><riot.js> | 2016-02-01 15:50:58 | LQ_CLOSE |
35,134,681 | Installing OpenMP on Mac OS X 10.11 | <p>How can I get OpenMP to run on Mac OSX 10.11, so that I can execute scripts <strong>via terminal</strong>?</p>
<p>I have installed OpenMP: <code>brew install clang-omp</code>.</p>
<p>When I run, for example: <code>gcc -fopenmp -o Parallel.b Parallel.c</code> the following expression returns: <code>fatal error: 'omp.h' file not found</code></p>
<p>I have also tried: <code>brew install gcc --without-multilib</code> but unfortunately this eventually returned the following (after first installing some dependencies): </p>
<pre><code>The requested URL returned error: 404 Not Found
Error: Failed to download resource "mpfr--patch"
</code></pre>
<p><strong>Any recommended work arounds?</strong></p>
| <c><gcc><openmp> | 2016-02-01 15:51:52 | HQ |
35,134,960 | Adjust size of leaflet map in rmarkdown html | <p>I'd like to change the height and width of <code>leaflet</code> map outputs in html document. Is there a simple way to do this in R markdown without getting into whole CSS business?</p>
<pre><code>```{r}
library(leaflet)
library(dplyr)
m <- leaflet() %>% setView(lng = -71.0589, lat = 42.3601, zoom = 12)
m %>% addTiles()
```
</code></pre>
<p>Ideally, I want the width of map to be the same width of code block as shown below.</p>
<p><a href="https://i.stack.imgur.com/NzgJE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NzgJE.png" alt="enter image description here"></a></p>
| <html><r><leaflet><markdown> | 2016-02-01 16:05:01 | HQ |
35,135,225 | Android WebView handle onReceivedClientCertRequest | <p>I'm developing an Android app using Client Certificate Authentication within WebView. The certificate (cert.pfx) and password are embedded in the application.</p>
<p>When executing Client Certificate Authentication request with ajax call in the WebView, the following function getting called :</p>
<pre><code>@Override
public void onReceivedClientCertRequest(WebView view, final ClientCertRequest request) {}
</code></pre>
<p>As I understend I need to call :</p>
<pre><code>request.proceed(PrivateKey privateKey, X509Certificate[] chain)
</code></pre>
<p>Any idea how to create the PrivateKey and X509Certificate objects from the embedded certificate in order to proceed with the request.
BTW, is this the correct way to implement Client Certificate Authentication on Android app ? if no, please advice.</p>
| <android><ssl><webview><client-certificates> | 2016-02-01 16:17:50 | HQ |
35,136,307 | Equivalent to get_contents_to_file in boto3 | <p>In boto3, is there an equivalent of <a href="http://boto.cloudhackers.com/en/latest/ref/s3.html#boto.s3.key.Key.get_contents_to_file" rel="noreferrer"><code>get_contents_to_file</code></a>, that copies the contents of an object to a file handle?</p>
<p>In boto, if I have an S3 object <code>key</code>, I can copy the contents to a temporary file with:</p>
<pre><code>from tempfile import TemporaryFile
key = code_that_gets_key()
with TemporaryFile() as tmp_file:
key.get_contents_to_file(key, tmpfile)
</code></pre>
<p>I haven't found an equivalent in boto3. </p>
<p>I have been able to replace usage of <a href="http://boto.cloudhackers.com/en/latest/ref/s3.html#boto.s3.key.Key.get_contents_to_filename" rel="noreferrer"><code>get_contents_to_filename</code></a> with <a href="http://boto3.readthedocs.org/en/latest/reference/services/s3.html?highlight=download_file#S3.Object.download_file" rel="noreferrer"><code>download_file</code></a>. However, that covers the case where I provide the filename. In this case, I want to provide the file handle as the argument.</p>
<p>Currently, I can get the code to work in boto3 by iterating over the body as follows:</p>
<pre><code>with TemporaryFile() as tmp_file:
body = key.get()['Body']
for chunk in iter(lambda: body.read(4096), b''):
filehandle.write(chunk)
</code></pre>
<p>Is there a better way to do this in boto3?</p>
| <python><amazon-s3><boto3> | 2016-02-01 17:10:05 | HQ |
35,136,345 | Maximum number of thread Android | <p>I want to know if there is a maximum number of threads that it is possible to run on an Android device. It depends on the type of the device?</p>
| <java><android><multithreading> | 2016-02-01 17:11:37 | HQ |
35,136,425 | Could not find or load main class java hello world | <p>I am trying to write <strong>hello world</strong> on java. My code is:</p>
<pre><code>class myfirstjavaprog
{
public static void main(String args[])
{
System.out.println("Hello World!");
}
}
</code></pre>
<p>And when I run <strong>java youtube.java</strong> on cmd I got this error:</p>
<p><strong>Error: Could not find or load main class youtube.java</strong></p>
| <java> | 2016-02-01 17:16:27 | LQ_CLOSE |
35,136,778 | This is the python code and it gives unexpected answer | <pre><code>school = 'Massachusetts Institute of Technology'
numVowels = 0
numCons = 0
for char in school:
if char == 'a' or char == 'e' or char == 'i' \
or char == 'o' or char == 'u':
numVowels += 1
elif char == 'o' or char == 'M':
print char
else:
numCons -= 1
print 'numVowels is: ' + str(numVowels)
print 'numCons is: ' + str(numCons)
</code></pre>
<p>This is the python code logically it should print 'o' 3 times but it doesn't i am unable to figure out why also the value of numcons should be -21 but it's coming -25 does anyone has an answer</p>
| <python> | 2016-02-01 17:34:22 | LQ_CLOSE |
35,136,836 | React component render is called multiple times when pushing new URL | <p>I am building a PhotoViewer that changes photos when the user presses left or right. I am using React, Redux, react-router, and react-router-redux. When the user presses left or right, I do two things, I update the url using <code>this.context.replace()</code> and I dispatch an action to update the currently viewed photo, <code>this.props.dispatch(setPhoto(photoId))</code>. I am subscribing to state changes for debugging.</p>
<p>Each of the above lines triggers a new state change. Dispatching an action updates the store since I update the <code>currentlyViewedPhoto</code> and updating the url updates the store because react-router-redux updates the url in the store. When I dispatch the action, in the first rerendering cycle, the component's <code>render</code> function gets called twice. In the second rerendering cycle, the component's <code>render</code> function gets called once. Is this normal? Here is the relevant code:</p>
<pre><code>class PhotoViewer extends Component {
pressLeftOrRightKey(e) {
... code to detect that left or right arrow was pressed ...
// Dispatching the action triggers a state update
// render is called once after the following line
this.props.dispatch(setPhoto(photoId)) // assume photoId is correct
// Changing the url triggers a state update
// render is called twice
this.context.router.replace(url) // assume url is correct
return
}
render() {
return (
<div>Test</div>
)
}
}
function select(state) {
return state
}
export default connect(select)(PhotoViewer)
</code></pre>
<p>Is this normal that render is called three times? It seems like overkill because React will have to do the DOM diffing three times. I guess it won't really matter because nothing has changed. I am new to this toolset, so feel free to ask any more questions about this problem.</p>
| <javascript><reactjs><react-router><redux> | 2016-02-01 17:37:44 | HQ |
35,137,027 | How do Pointer Arithmetic works after Pointer Casting? |
int main() {
short int a[4] = {1,1, [3] = 1};
int *p = (int*)a;
printf("p: %p %d \n ", p, *p);
printf("p+1: %p %d\n", (p +1), *(p+1));
}
why does *p = 65537 and *(p+1) = 65536? | <c><pointers><endianness> | 2016-02-01 17:47:30 | LQ_EDIT |
35,137,227 | Wrong output from dictionary in C# | <p>Why do I get output of my namespace.object when printing from dictionary?</p>
<p>This is my data object.</p>
<pre><code>namespace MoleCalculator
{
public class elementDO
{
public int AtomicNumber { get; set; }
public string Symbol { get; set; }
public string Name { get; set; }
public decimal AtomicWeight { get; set; }
}
}
</code></pre>
<p>This is the class that has my dictionary</p>
<pre><code>namespace MoleCalculator
{
public class elementDictionary
{
public Dictionary<int, elementDO> periodic_Table = new Dictionary<int, elementDO>()
{
{1,new elementDO{AtomicNumber = 1,Symbol = "H",Name = "Hydrogen", AtomicWeight = 1.007825M}},
</code></pre>
<p>This is what drives it</p>
<pre><code>var elements = new elementDictionary().periodic_Table;
Console.WriteLine(elements[1]);
</code></pre>
| <c#><dictionary> | 2016-02-01 17:58:55 | LQ_CLOSE |
35,137,280 | How to put something on the screen? | <p>I use <strong>Ubuntu Studio 15.10</strong> and I want to learn to program in <strong>C++</strong>.</p>
<p>I'm absolutely new into the <strong>C++</strong> programming world.</p>
<p>I wrote my first "code", with <strong>gedit</strong>.</p>
<p>In simple words, I want to put on the screen some text (like the old Basic: PRINT "Hello!").</p>
<p>So, I wrote:</p>
<pre><code>#include <iostream>
using namespace std;
#include <cmath>
#include <cstdlib>
const double PI = atan(1) * 4;
int main()
{
cout << "Hello" << std::endl;
cout << "This is my first code with C++." << std::endl;
cout << "Let's see what happen." << std::endl;
cout << "2 * 3 = "; cout << 2 * 3 << std::endl;
cout << "Constante pi = "; cout << PI << std::endl;
cout << "Seno de 45º = "; cout << sin((45*PI)/180) << std::endl;
cout << "Coseno de 30º = "; cout << cos((30*PI)/180) << std::endl;
cout << "Tangente de 45º = "; cout << tan((45*PI)/180) << std::endl;
return 0;
}
</code></pre>
<p>Then, I used <strong>Codelite</strong> to compile it and... I get a lot of files and folders.</p>
<p>The supposed executable file is called <strong>main.cc</strong>.</p>
<p>BUT... When I ask the system to run that file... Nothing happen!!!</p>
<p>I mean, there is not any text into any screen pane, any new window... Nothing, just Nothing!!!</p>
<p>What's wrong, here?</p>
<p>How can I get to see what I want to see into the screen?</p>
| <c++> | 2016-02-01 18:02:02 | LQ_CLOSE |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.