text
stringlengths
64
81.1k
meta
dict
Q: The component and quasi-component are productive Definition The component $C_x$ of $x\in X$ is the biggest connected subspace of $X$ that contains $x$. Definition The quasi-component $Q_x$ of $x\in X$ is the intersection of the clopen sets of $X$ that contains $x$. Statement If $\mathfrak{X}=\{(X_j,\mathcal{T}_j): j\in\ J\}$ is a collection of topological spaces then the component $C_x$ and the quasi-componet $Q_x$ of any $x\in X:=\prod_{j\in\ J}X_j$ is equal to the product of the components $C_{x_j}$ and quasi-components $Q_{x_j}$ of the projections $x_j$ of $x$ in $X_j$. Proof. Cleary $K_x=\prod_{j\in J}C_{x_j}$ is connected in $X$ and so $K_x\subseteq C_x$. Then clearly $\pi_j(C_x)$ is connected in $X_j$ for any $j\in\ J$, since the projections are continuous functions; and so $\pi_j(C_x)\subseteq C_{x_j}$ for any $j\in J$ and so $C_x\subseteq\pi_j^{-1}(C_{x_j})$ for any $j\in J$, that is $C_x\subseteq\bigcap_{j\in J}\pi_j^{-1}(C_{x_j})=K_x$. First of all I think that my proof is partially uncorrect, since for sake of completeness I should to prove that $K_x$ is embeddable in $X$ and then that $\bigcap_{j\in J}\pi_j^{-1}(C_{x_j})$ is actually equal to $K_x$. Anyway to prove that $K_x$ is embeddable in $X$ I tried to define the funcion $\phi:K_x\rightarrow X$ through the condiction $[\phi(x)](j)=x(j)$ for any $x\in K_x$ for which is obvious that $\phi$ is injective and continuous, since $\pi_j\circ\phi=\pi'_j$ for any $j\in J$, where $\pi_j$ and $\pi'_j$ are the projections in $X$ and $K_x$; then I should to prove that $\phi[K_x]= H_x:=\{z\in X:z(j)\in C_{x_j},\forall j\in J\}$ and so define an inverse of $\phi$. Then as you can see the proof is incomplete, since I didn't prove the statement about the quasi-components: so I ask to complete the proof. So could someone help me, please? A: $\prod_j C_{x_j} \subseteq C_x$ because the former set is connected (product of connected sets) and contains $x$ and $C_x$ is maximally such. OTOH, $\pi_j[C_x]$ is connected, as $\pi_j$ is continuous, and contains $x_j$ so for all $j$: $\pi_j[C_x] \subseteq C_{x_j}$, which implies $$C_x \subseteq \bigcap_j \pi_j^{-1}[\pi_j[C_x]] \subseteq \bigcap_j \pi_j^{-1}[C_{x_j}]= \prod_j C_{x_j}$$ which shows the other inclusion. The quasi-components I treated in a different definitional setting in your follow question here. (for reference)
{ "pile_set_name": "StackExchange" }
Q: Java Null Pointer Exception in Queue I have been trying to write a queue that uses a Node file, and I can't seem to figure out where the null pointer exception is an issue. I looked online a bit but I'm too new to Java I think to understand what I'm looking for here. Can anyone find it or at least lead me in the right direction?? First the Queue: public class Queue extends CharNode { public CharNode head; public CharNode tail; public Queue(){ this.head = null; this.tail = null;} public boolean isEmpty(){ return (head==null);} public void enqueue(Character character){ if (isEmpty()){ head.character = character; head.nextNode = tail;} else { CharNode oldTail = tail; tail = new CharNode(); oldTail.character = character; oldTail.nextNode = tail; } } public Character dequeue(){ if (isEmpty()) throw new RuntimeException("Queue Empty"); head.character = character; head = head.nextNode; return character; } public static void main(String[] args){ Queue queue = new Queue(); queue.enqueue('a'); queue.enqueue('b'); System.out.print(queue.dequeue()); } } My CharNode file looks like: public class CharNode { public Character character; public CharNode nextNode; public void charNode(Character character){ this.character = character; this.nextNode = null; } } And the exception I received looks like: Exception in thread "main" java.lang.NullPointerException at Queue.enqueue(Queue.java:14) at Queue.main(Queue.java:32) A: public boolean isEmpty(){ return (head==null);} public void enqueue(Character character){ if (isEmpty()){ head.character = character; // you have just said that head is NULL What may work is if (isEmpty()){ head = new CharNode (); // There is no Constructor for CharNode (Character) head.character = character;
{ "pile_set_name": "StackExchange" }
Q: Basic authentication for REST API using spring restTemplate I am completely new in RestTemplate and basically in the REST APIs also. I want to retrieve some data in my application via Jira REST API, but getting back 401 Unauthorised. Found and article on jira rest api documentation but don't really know how to rewrite this into java as the example uses the command line way with curl. I would appreciate any suggestion or advice how to rewrite: curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" "http://kelpie9:8081/rest/api/2/issue/QA-31" into java using spring rest template. Where the ZnJlZDpmcmVk is a base64 encoded string of username:password. Thank you very much. A: Taken from the example on this site, I think this would be the most natural way of doing it, by filling in the header value and passing the header to the template. This is to fill in the header Authorization: String plainCreds = "willie:p@ssword"; byte[] plainCredsBytes = plainCreds.getBytes(); byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); String base64Creds = new String(base64CredsBytes); HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Basic " + base64Creds); And this is to pass the header to the REST template: HttpEntity<String> request = new HttpEntity<String>(headers); ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class); Account account = response.getBody(); A: You may use spring-boot RestTemplateBuilder @Bean RestOperations rest(RestTemplateBuilder restTemplateBuilder) { return restTemplateBuilder.basicAuthentication("user", "password").build(); } See documentation (before SB 2.1.0 it was #basicAuthorization) A: (maybe) the easiest way without importing spring-boot. restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user", "password"));
{ "pile_set_name": "StackExchange" }
Q: xtext: Relation between AST, Metamodel and parse tree Can someone explain me the relationship between a parse tree, AST and metamodel. I know so far that xtext derive an EMF Ecore metamodel out of the grammar and generate a parser with antlr. But how will it then be parsed: An input goes first trough the lexer and then the parser creates a parse tree out of the parser rules, right? And out of the parse tree, Xtext creates also an AST? For what? And what purpose has the metamodel in this case? I'm a little bit confused of all the definitions. A: You are right about the three-step parsing procedure: first the lexer starts with the input stream, then an Antlr-based parse tree is created, finally Xtext generated an EMF-based AST from the parse tree. The first two steps are natural for every parser (generator), the third step needs some explaining. I will start a bit lengthy explanation with some motivation, then I will shortly speak about metamodels and EMF in general. First of all, the generated parsers do not support identifier resolution (required for handling variables or function calls), these functions needs to be added manually, so a manually coded post-processing step is needed for almost all languages, that needs an extension of the already existing parse tree. Second, EMF provides a nice, type-safe API for its models, together with a powerful reflective API, that allows the creation of very generic, but useful components that ease the processing of the models (e.g. code generators such as Acceleo or one aspect of Xtend, model transformation tools, such as ATL, ETL, VIATRA2). I cannot tell exactly the difference between the parse tree API of Antlr and EMF, but I worked with the API of the LPG parser generator, and in my opinion, EMF is easier to work with. Even better, the use of EMF allows the re-use of the rich Xtext functionality together with other EMF-based editors, such as GMF-based graphical editors. See an earlier EclipseCon presentation for the basic idea: TMF meets GMF - Combining Textual and Graphical Modeling. In general, if we need to extend our parse tree with resolution information, then by re-using an already used paradigm can ease the integration of our language with other tools. EMF relies on the concept of metamodeling: we have to define the set of elements usable in the models, together with additional constraints, such as information about connectivity. This concept is similar to schema definitions for XML (such as DTD or SML Schema) - we have a uniform way to describe models. Xtext works together with EMF in several ways: First of all, based on the grammar, it generates and registers an EMF metamodel that can be used in every EMF-based tooling. Then the end result of the parsing process is an EMF model, that can be read and modified using the EMF API - changes are serialized back into the textual form. I hope, the answer was clear enough. Feel free to ask for more clarifications if needed.
{ "pile_set_name": "StackExchange" }
Q: Dual visas of 2 different country Currently I am studying in the Philippines on the basis of my student visa/9f, but unfortunately due to some financial problems and family personal matters I cannot continue my studies anymore, and I have to go back to my country of India. But after that soon I'll be going to USA for work, so could there be any kind of problem if I don't degrade my student visa to 9f visa, while getting and being approved for my working visa for the USA or any other country? A: Having a valid visa (of any type) from one country, does not bar you from having another visa from another country. It is a routine matter. If you go to USA for work, all you need to ensure is that you have a proper work visa for the USA. Your student visa for Philippines does not matter either positively or negatively.
{ "pile_set_name": "StackExchange" }
Q: How to resolve errors on @Id fields, when @Column(name = "foo") annotation does not match field name I seem to be having trouble when I define a field on an entity with @Id, and also have a @Column annotation which does not match the field name. i.e. public class MyEntity { @Id @Column(name = "foo") private Long id; ... } When I attempt to persist this using the repository save() method, I get: org.springframework.beans.factory.BeanCreationExeption org.springframework.dao.DataIntegrityViolationException Integrity constraint violation: NOT Null check constraint; SYS_CT_10083 table: MyEntity column ID If the name in the @Column annotation is changed to "id" (to match the field name and getId() accessor), then it works perfectly. This is happening in a test, where I have created an embedded H2 or HSQL database (I tried both) from my entities. With a dig through logs, I can see that the table is being created incorrectly: [tool.hbm2ddl.SchemaUpdate] create table MyEntity ( foo bigint not null, ..., id integer not null, primary key (id)) Therefore the issue seems to be with how tables are generated when there is an @Id annotation. Does anybody have any thoughts on where I should be looking to resolve this? It seems to me that there may be a bug in either spring data or hibernate, but I'm not too sure on how best to attack the problem. fyi - I'm using Spring 3.2.4.RELEASE, spring-data-jpa 1.3.4.RELEASE and hibernate-entitymanager 4.0.1.Final For those who enjoy reading stack traces, an example full trace is below. Thanks for any help anybody can provide! org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.foo.integration.repositories.JobRepositoryTest': Invocation of init method failed; nested exception is org.springframework.dao.DataIntegrityViolationException: integrity constraint violation: NOT NULL check constraint; SYS_CT_10083 table: JOB column: ID; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: integrity constraint violation: NOT NULL check constraint; SYS_CT_10083 table: JOB column: ID at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:133) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:396) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1475) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:388) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:111) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: org.springframework.dao.DataIntegrityViolationException: integrity constraint violation: NOT NULL check constraint; SYS_CT_10083 table: JOB column: ID; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: integrity constraint violation: NOT NULL check constraint; SYS_CT_10083 table: JOB column: ID at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:643) at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:106) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:403) at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58) at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at com.sun.proxy.$Proxy38.saveAndFlush(Unknown Source) at com.foo.integration.repositories.JobRepositoryTest.initialiseData(JobRepositoryTest.java:31) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:344) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:295) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:130) ... 27 more Caused by: org.hibernate.exception.ConstraintViolationException: integrity constraint violation: NOT NULL check constraint; SYS_CT_10083 table: JOB column: ID at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:74) at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110) at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129) at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81) at com.sun.proxy.$Proxy42.executeUpdate(Unknown Source) at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:56) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2849) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3290) at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:80) at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:272) at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:264) at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:186) at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:326) at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52) at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1081) at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:973) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241) at com.sun.proxy.$Proxy36.flush(Unknown Source) at org.springframework.data.jpa.repository.support.SimpleJpaRepository.flush(SimpleJpaRepository.java:404) at org.springframework.data.jpa.repository.support.SimpleJpaRepository.saveAndFlush(SimpleJpaRepository.java:372) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:333) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:318) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155) ... 42 more Caused by: java.sql.SQLIntegrityConstraintViolationException: integrity constraint violation: NOT NULL check constraint; SYS_CT_10083 table: JOB column: ID at org.hsqldb.jdbc.Util.sqlException(Unknown Source) at org.hsqldb.jdbc.Util.sqlException(Unknown Source) at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source) at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122) ... 75 more Caused by: org.hsqldb.HsqlException: integrity constraint violation: NOT NULL check constraint; SYS_CT_10083 table: JOB column: ID at org.hsqldb.error.Error.error(Unknown Source) at org.hsqldb.Table.enforceRowConstraints(Unknown Source) at org.hsqldb.Table.insertSingleRow(Unknown Source) at org.hsqldb.StatementDML.insertSingleRow(Unknown Source) at org.hsqldb.StatementInsert.getResult(Unknown Source) at org.hsqldb.StatementDMQL.execute(Unknown Source) at org.hsqldb.Session.executeCompiledStatement(Unknown Source) at org.hsqldb.Session.execute(Unknown Source) ... 82 more A: Having simplified the application considerably, I established that this exception was a side-effect of having 2 entities referencing the same table, where the second table did have a field called "id". i.e. @Entity @Table(name = "my_table") public class MyEntity { @Id @Column(name = "pk") private Long id; ... } @Entity @Table(name = "my_table") public class MyOtherEntity { @Id @Column(name = "id") private Long id; ... } It looks to me as though this caused Hibernate/JPA to generate and validate against a table which was a composite of the two entities, where (in the above example) "pk" and "id" were both non-null fields, and (perhaps due to being alphabetically later) the primary key was set to be the @Id of MyOtherEntity. I'm not sure whether this is by design. Certainly, I can see that having multiple small entities referencing a huge flat table, might be useful when working with a 'legacy' database. But it certainly caught me out. Especially with the manner in which it treated the 2 separate @Id fields (both non-null, but only one primary key).
{ "pile_set_name": "StackExchange" }
Q: Swift dictionary 'else' keyword? I'm new to swift. Is there a way to define a dictionary with an 'otherwise' type of method? For example Var dictionary = ["a": 1, "b": 2, AnythingElse: 3] dictionary("$") Should return the value 3. A: If you want a default value for when the item isn't there do this: let item = dictionary["key"] ?? defaultValue Now item will be the entry in the dictionary whose key is "key" or defaultValue if there was no entry for "key" example var dictionary = ["a": 1, "b": 2] let defaultValue = 3 print(dictionary["a"] ?? defaultValue) print(dictionary["$"] ?? defaultValue) This will print 1 and 3.
{ "pile_set_name": "StackExchange" }
Q: Convert string to datetime on server 2008 i have problem when i try to convert in c# this string: Úterý, 07 Červen 2016 13:06 to datetime, because i import this to sql. I try this: DateTime.Parse("Úterý, 07 Červen 2016 13:06") DateTime.Parse("Úterý, 07 Červen 2016 13:06").Date Convert.ToDateTime("Úterý, 07 Červen 2016 13:06") On my windows 10 i havent any problem, but when i try in sql server 2008 i have this error: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0 Have you any ideas please? A: Try using DateTime.ParseExact method, like this (providing that the initial string is in Czech culture): String source = "Úterý, 07 Červen 2016 13:06"; DateTime result = DateTime.ParseExact(source, "dddd, dd MMMM yyyy H:mm", new CultureInfo("cs-CZ")); format explanation: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx dddd The full name of the day of the week. dd The day of the month, from 01 through 31. MMMM The full name of the month. yyyy The year as a five-digit number. H The hour, using a 24-hour clock from 0 to 23. mm The minute, from 00 through 59.
{ "pile_set_name": "StackExchange" }
Q: Smartwatch 2 app crashing watch on menu open I have a smartwatch 2 app on the market which has been working fine for months, but recently it has started crashing a second after the context menu is opened. The onKey code looks like this: @Override public void onKey(final int action, final int keyCode, final long timeStamp) { // Menu button click if (action == Control.Intents.KEY_ACTION_RELEASE && keyCode == Control.KeyCodes.KEYCODE_OPTIONS) { showMenu(mMenuItemsText); } } (mMenuItemsText is defined at the class level and instantiated in the constructor: mMenuItemsText[0] = new Bundle(); mMenuItemsText[0].putInt(Control.Intents.EXTRA_MENU_ITEM_ID, MENU_ITEM_REVERSE_RATE); mMenuItemsText[0].putString(Control.Intents.EXTRA_MENU_ITEM_TEXT, context.getResources().getString(R.string.converter_menu_reverse_rate)); ) When I click the watch menu button in my app, the menu opens up, and then a second later the watch crashes and disconnects from the phone before starting back up and reconnecting to the phone. Nothing in logcat and the phone doesn't show a crash prompt, it seems completely unaware that the watch has crashed. If I put Log.d statements on each line above then they all show up in logcat, it seems to be happening after the menu has finished its "swipe in" animation. Thinking the problem was in the utils app, I tried replacing the showMenu call with the same code to send the menu intent directly: @Override public void onKey(final int action, final int keyCode, final long timeStamp) { // Menu button click if (action == Control.Intents.KEY_ACTION_RELEASE && keyCode == Control.KeyCodes.KEYCODE_OPTIONS) { Intent intent = new Intent(Control.Intents.CONTROL_MENU_SHOW); intent.putExtra(Control.Intents.EXTRA_MENU_ITEMS, mMenuItemsText); sendToHostApp(intent); } } But I get the same problem. I have another SW2 app on the market with the same code and it works fine. I'm completely stumped as to how to find the problem, as I'm unable to step into the code in Eclipse. A: This issue will be fixed in the upcoming 1.4.54 host app SW to be released in the next few days. The issue has to do with the number of touch regions supported, which has been increased from 25 to 30 in the update.
{ "pile_set_name": "StackExchange" }
Q: How far can I drift from my original domain model and still have the benefits of an ORM? I have the following domain models: public class User { public int Id { get; set; } public ICollection<Product> Products { get; set; } } public class Product { public int Id { get; set; } public decimal Price { get; set; } } My User entity has a collection of Products, and no Product can be created without an User. I am using EntityFramework Code First approach, which requires me to declare the Foreign Key on my Product entity, thus changing it to: public class Product { public int Id { get; set; } public decimal Price { get; set; } public int UserId { get; set; } } I dont quite like this because, from the domain point of view, it is not interesting to have the User foreign key shown in my Product entity. This, however, does not bring any harm to me and I can live with it. Please, mind that I am using an ORM to simplify my work, so I am okay with it to an extent. Is it okay to my domain entities having properties or such things only to satisfy my ORM of choice requirements? A: I've heard Vaugn Vernon say about EF that you shouldn't spend time battling EF in order to make it look like a domain model because EF is much more inflexible than other ORMs. So his advise if you want to use EF is to just have a state object behind the scenes which fits EF and then just let your domain model use that for data storage.
{ "pile_set_name": "StackExchange" }
Q: multiple NOT LIKE operator on same column with OR condition fails in SQL Table Schema: CREATE TABLE [dbo].[Message]( [id] [int] NOT NULL, [created_on] [datetime] NULL, [message] [nvarchar](max) NULL, CONSTRAINT [PK_Message] PRIMARY KEY CLUSTERED ( [id] ASC ) ) ON [PRIMARY] Values: 1 '2013-01-01 00:00:00.000' 'error occured "BASKET_BALL"' 2 '2014-01-01 00:00:00.000' 'error occured "FOOT_BALL"' 3 '2012-01-01 00:00:00.000' 'I am not involved in like operator' 4 '2014-02-01 00:00:00.000' 'I might be involved' Query return against the table: SELECT ID,CREATED_ON,MESSAGE FROM MESSAGE WHERE MESSAGE NOT LIKE '%"FOOT_BALL"%' OR MESSAGE NOT LIKE '%BASKET_BALL%' AND CREATED_ON >= '2014-01-01' Output: 1 2013-01-01 00:00:00.000 error occured "BASKET_BALL" 2 2014-01-01 00:00:00.000 error occured "FOOT_BALL" 3 2012-01-01 00:00:00.000 I am not involved in like operator 4 2014-02-01 00:00:00.000 I might be involved Question: Could some one explain why the query returns all the table values when explicitly the date condition is mentioned for greater than 2014 ? I understand by keeping the message condition in bracket it yields proper result. However, like to know why the sql excludes date condition mentioned when the not like operator is not in bracket. A: It's because the AND operator has higher precedence than OR. Change to this: SELECT ID,CREATED_ON,MESSAGE FROM MESSAGE WHERE (MESSAGE NOT LIKE '%"FOOT_BALL"%' OR MESSAGE NOT LIKE '%BASKET_BALL%') AND CREATED_ON >= '2014-01-01' Depending on what you want maybe the parenthesis should surround the latter part, like so: MESSAGE NOT LIKE '%"FOOT_BALL"%' OR (MESSAGE NOT LIKE '%BASKET_BALL%' AND CREATED_ON >= '2014-01-01')
{ "pile_set_name": "StackExchange" }
Q: Asp.net mvc4 authentication through WCF I have a requirement for project to build a ASP.NET MVC4 (razor engine) "Front-end" and a WCF service as "backend" (with a sql server 2012 database). A requirement is to login, register etc. I want to put this logic in the backend, but in the front-end I would like to make use of the [AllowAnonymous] and the logic to authenticate a user with roles (for example use of formauthentication, webmatrix.WebSecurity, Membership provider?). Is it possible to realize? Do I have to create a login and register (and roles etc.) features by myself? Or can I use a built-in features/libraries of the ASP.NET MVC or WCF? Or both? Could you give some examples/suggestions/tutorials to realize this? Thanks in advance A: I think this should work for you: http://msdn.microsoft.com/en-us/library/bb386582.aspx Edit: To elaborate you can use custom logic for WCF authentication including calling the ASP.NET membership providers which should work fine with MVC and the security attributes you mentioned. Or is the WCF service on another server and you want to call from your ASP.NET controller to your WCF service for authentication? This is a bit more complex, but you should be able to do it by implementing your own Membership provider. Depending on the scenario you can reuse some or all of the login and register views that come with MVC. Edit: In the second scenario here are some pointers that might help: http://singlesignon.codeplex.com/ - Seems to be what you need, but I didn't check out the code. Custom membership that uses web service for authentication - No code, but it confirms that it should work.
{ "pile_set_name": "StackExchange" }
Q: MySQL select rows where its columns sum equal value I have following tables: A: +----+-----------+-------+----------+ | ID | PaymentID | Price | Quantity | +----+-----------+-------+----------+ | 1 | 1 | 128 | 1 | | 2 | 2 | 10 | 2 | | 3 | 2 | 11 | 1 | | 4 | 3 | 100 | 2 | +----+-----------+-------+----------+ B: +-----------+------------+ | PaymentID | TotalPrice | +-----------+------------+ | 1 | 128 | | 2 | 31 | | 3 | 201 | +-----------+------------+ And query: SELECT a.ID FROM a LEFT JOIN b ON b.PaymentID = a.PaymentID WHERE b.TotalPrice = (a.Price * a.Quantity) It works fine when a.PaymentID is unique, but some transactions in table A are separated and paid (table B) together. Query above return a.ID = 1 but I need to return a.ID = 1,2,3. a.PaymentID(1): 128 * 1 = 128 MATCH a.PaymentID(2): 10 * 2 + 11 * 1 = 31 MATCH a.PaymentID(3): 100 * 2 = 200 NOT MATCH SQL Fiddle A: Try this statement: SELECT a.ID, b.totalprice FROM a LEFT JOIN b ON b.PaymentID = a.PaymentID group by b.paymentID having TotalPrice = sum(a.Price * a.Quantity) SQLFIDDLE UPDATE: After clarification: select a.id from a where paymentId in( select paymentID from( SELECT a.paymentID as paymentID, b.totalprice FROM a LEFT JOIN b ON b.PaymentID = a.PaymentID group by b.paymentID having TotalPrice = sum(a.Price * a.Quantity)) as c ) A: You are trying to join sum of Price and amount from table a to table b along with the PaymentId, and using it onto a joining clause which would be calculated per row based not on aggregate based. You may need to first find the aggregate part and then join something as select a.ID from a left join ( select sum(Price*Quantity) as tot,PaymentID from a group by PaymentID )x on x.PaymentID = a.PaymentID join b on b.PaymentID = a.PaymentID and x.tot = b.TotalPrice http://www.sqlfiddle.com/#!9/3b261/45
{ "pile_set_name": "StackExchange" }
Q: Python Threading Joining a Dead Thread What happens if I call join() on a thread that has already finished? e.g. import threading import time def fn(): time.sleep(1) t = threading.Thread(target=fn) t.start() time.sleep(2) t.join() The docs don't seem to provide any clarity on this issue A: from the docs you quoted: join: Wait until the thread terminates. ... so if the thread is already terminated, of course, it exits at once. Somewhere else from the docs as well: the operation will block until the thread terminates. ok so if it's already terminated, the operation doesn't block. This method is a way to provide synchronization between the caller and the thread. After join exits, it's guaranteed that the thread ended. If the thread is already over when join is called, then of course, it does nothing. This is confirmed by the python source code (this function is called from join(): def _wait_for_tstate_lock(self, block=True, timeout=-1): # Issue #18808: wait for the thread state to be gone. # At the end of the thread's life, after all knowledge of the thread # is removed from C data structures, C code releases our _tstate_lock. # This method passes its arguments to _tstate_lock.acquire(). # If the lock is acquired, the C code is done, and self._stop() is # called. That sets ._is_stopped to True, and ._tstate_lock to None. lock = self._tstate_lock if lock is None: # already determined that the C code is done assert self._is_stopped # we see that we don't wait for anything here elif lock.acquire(block, timeout): lock.release() self._stop()
{ "pile_set_name": "StackExchange" }
Q: The graph API is returning an unknown error when I comment on a post despite the fact that the comment is posted correctly I'm trying to comment on a post via the Graph API: FB.api( "/604597322_10152198339802323/comments", "POST", { "access_token" : XXX, "message" : "comment..." }, function ( response ) { ... } ); The access token is fine, I can do other things such as post to my wall and like posts. The error I get is the singularly unhelpful "An unknown error has occurred." The comment IS succesfully posted, which makes this doubly vexing, it's just that the graph API does not report it as such. Just to confirm, if I type the following into my browser address bar with a valid access token... https://graph.facebook.com/604597322_10152198339802323/comments?method=post&message=test&access_token=XXX ...I get: { "error": { "message": "An unexpected error has occurred. Please retry your request later.", "type": "OAuthException", "code": 2 } } However the comment has been successfully posted. A: Its seems like bug in graph API. I am facing the same issue. Have a look. https://developers.facebook.com/x/bugs/218862188300393/ I have also create a bug in fb bug tracker. https://developers.facebook.com/x/bugs/570569026365902/ Facebook support and development is very slow in solving bugs. Some bugs are assigned but still not solved yet. For them it seems not important but for us it makes huge impact... :( https://developers.facebook.com/x/bugs/356391864496461/ Hope this will give you some relief. :)
{ "pile_set_name": "StackExchange" }
Q: Browser Detection using java/Java EE In order to achieve browser compatibility in an application I am in need of a Java class/Bean/Jar which will return the following information: current browser of user its name version the OS of the user Any thought on this will be really helpful. This should work well in latest versions of all the modern browsers such as Chrome, Safari and Opera. How can I solve this best? A: Since the user agent data is extremely sensitive to changes and you'd like to delegate the maintenance of the data to a 3rd party, consider to use a public webservice like http://user-agent-string.info. They also have a Java example for the XML-RPC service. You can obtain the user agent of the current request using HttpServletRequest#getHeader(). String userAgent = request.getHeader("User-Agent"); Use that as parameter for the webservice. That said, if you actually have compatibility problems in the HTML/CSS/MSIE area, you should really consider conditional comments. If in JS area, use feature detection. You should not rely on the user agent and certainly not in the server side. Consider posting a new question about the problem for which you thought that sniffing the user agent in the server side is the solution. You'll get much better suited answers.
{ "pile_set_name": "StackExchange" }
Q: Angular 6 PopUp Am working on popup window in angular 6. currently following this link https://stackblitz.com/angular/brrobnxnooox?file=app%2Fmodal-basic.html html code <div class="form-group"> <ng-template #ea_popup let-modal> <div class="modal-header"> <h4 class="modal-title" id="modal-basic-title">PopUp</h4> <button type="button" class="close" aria-labelledby="Close" (click)="modal.dismiss('Cross click')"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="dateOfBirth">Date of birth</label> <div class="input-group"> <input id="dateOfBirth" class="form-control" placeholder="yyyy-mm-dd" name="dp" ngbDatepicker #dp="ngbDatepicker"> <div class="input-group-append"> <button class="btn btn-outline-secondary calendar" (click)="dp.toggle()" type="button"></button> </div> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">Save</button> </div> </ng-template> <span></span> <button type="submit" class="btn btn-success" (click)="onClick(ea_popup)">Add</button> </div> component code import { Component, OnInit, AfterViewInit, ChangeDetectorRef } from '@angular/core'; import { Provider } from '../provider'; import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'app-providerservice', templateUrl: './providerservice.component.html', styleUrls: ['./providerservice.component.css'] }) export class ProviderserviceComponent implements OnInit { constructor(private modalService: NgbModal, public cdRef: ChangeDetectorRef) { } closeResult: string; ngOnInit() { } onClic(content) { this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => { this.closeResult = `Closed with: ${result}`; }, (reason) => { this.closeResult = `Dismissed ${this.getDismissReason(reason)}`; }); } private getDismissReason(reason: any): string { if (reason === ModalDismissReasons.ESC) { return 'by pressing ESC'; } else if (reason === ModalDismissReasons.BACKDROP_CLICK) { return 'by clicking on a backdrop'; } else { return `with: ${reason}`; } } } when i create a project having same code in stackblitz its working fine. when i implemented in my project, while debugging its shows an error in console A: Finally i got solution for this issue. Updated my bootstrap css in index.html file.Now its working fine <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> to <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
{ "pile_set_name": "StackExchange" }
Q: Different formats for different Textview defined by Custom style I have a problem figuring out how to do this: I am currently coding an app that comes with different themes (User can select the complete appereance of the app out of a list of different styles). Then the list item is selected I want to call setTheme(R.style.Own_App_Style0); to change the complete appearance. The problem is best explained by an example: Lets say we have 2 TextView. Theme1 1. TextView: TextColor should be green and TextSize 15sp. 2. TextView: TextColor should be red and TextSize 10sp. Theme2 1. TextView: TextColor should be blue and TextSize 10sp. 2. TextView: TextColor should be yellow and TextSize 10sp. Of course I know that by setting <item name="textViewStyle">@android:style/Widget.TextView</item> I can change the default appearance of TextViews. But how can it be done to have lets say two (ore more) different types of TextView with different applied styles (and by xml)? A: Found a solution (basically in this answer setTextAppearance through code referencing custom attribute). In case anyone else has this problem I shortly explain: Declare in style.xml a attribute and in the actual style definition asign a value (reference) to this attribute: <declare-styleable name="CustomTextView"> <attr name="mainTextView" format="reference"/> </declare-styleable> <style name="appstyle0" parent="android:style/Theme.Holo.Light"> <item name="@attr/mainTextView">@style/CustomTextViewAppearance1</item> <item name="android:textViewStyle">@style/CustomTextViewAppearance2</item> </style> <style name="appstyle1" parent="android:style/Theme.Holo.Light"> <item name="@attr/mainTextView">@style/CustomTextViewAppearance2</item> <item name="android:textViewStyle">@style/CustomTextViewAppearance1</item> </style> <style name="CustomTextViewAppearance1"> <item name="android:textSize">10dip</item> </style> <style name="CustomTextViewAppearance2"> <item name="android:textSize">30dip</item> </style> Now in the layout all textViews are like CustomTextViewAppearance2 (because this is set as standard in this style. And the textViews that should use the other style write into the definition: <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="blablabla" style="?mainButtonTextView"/> When you now call .setTheme (after restart the activity) the appearance of the textviews switch. Like this method you can define as many different types of View styles and switch between them only by calling .setTheme.
{ "pile_set_name": "StackExchange" }
Q: Passing variable FROM flash to HTML/php I was hoping maybe someone could provide some insight on a problem I'm having a tough time deciding how to solve. I have a rather simple flash application users can make a quick username when connected, and the username is created inside the flash swf. Now, I have a cron job deleting inactive usernames every ten minutes (on my mysql database where these usernames are all stored and accessed by the other people online) which is fine. But it can still get cluttered up if a bunch of people sign off at once, there is still that 10 minute window before the cron job clears them. The users have an option to click log out in the flash application which is fine and works great. But of course many choose not to click log off they just click the browser x. I've looked into onbeforeunload and jquery's .unload but I still need a way to get the username variable that's IN flash INTO the HTML, then use a php script to run the delete username mysql query. Is there an easier solution? If not, any insight on how I might pass the username variable to the html to hold onto it after the user makes their username so it can be involved with the .unload function running the php script? EDIT::::: Maybe is there a way to create a UNIQUE string of numbers with php then pass that var to flash to include with the mysql row then since i already have that var since it was created on the html side, just along with the unload, have it delete the row that has that unique id? If anyone things this idea would be the best approach, and if i used something like md5(uniqid(microtime()) . $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']) to make a random iD how could i go about storing the result in a var i could place in the flash vars param then again in the jquery unload or javascript onbeforeunload if that would be better . im just more familiar with jquery A: You could actually invoke an ExternalInterface command to populate a hiddenfield in your HTML coming from your SWF component. if (ExternalInterface.available) { var js:String = "yourJavaScriptFunction"; var valToPass:String; ExternalInterface.call(js(valToPass)); } And in your HTML page, you write a javascript function: <script language="javascript" type="text/javascript"> function yourJavaScriptFunction(valToPass) { document.getElementById('yourHiddenField').value = valToPass; } And from the unload event fired up by your page, you can access the value which was passed from your SWF. Take note that you can call the javascript function from your SWF as soon as you get the login credentials of your user. Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: What function should I use to solve this? Simple question ;) I need to write a simple function to be implemented in a computer program. It should have as imput a number from 2 to 9 and gives as output a number from 1 to 5. When the input is higher 6-7-8-9 the output should be lower 1-2. The opposite when the input is lower. I can implement a random function inside it. No need to satisfy any other particular requests. The important is that when I input 9 i got more low numbers as output then when I input 8 and so on. Thanks! Sorry if this is a little bit vague! A: Well, if the inputs are integers, then the solution is simple (provided I've understood you're question properly). Just pick an appropriate sequence $(z_{n})_{n = 2}^{9}$, where each $z_{n} \in \{1,2,3,4,5 \}$ and satisfying all your requirements (looks like it has to be decreasing, at least). Then define the function $f: \{ 2, 3, \ldots, 9 \} \to \{1,2,3,4,5\}$ by $f(n) = z_n$. For instance $(5,4,4,3,2,2,1,1)$ should satisfy your requirements, as far as I can tell. The function is then defined by $f(n) = z_{n}$, so $f(2) = 5, f(3) = 4, f(4) = 4, f(5) = 3, \ldots, f(9) = 1$. It is probably easiest to visualize as \begin{align*} & (2,3,4,5,6,7,8,9) \\ & (5,4,4,3,2,2,1,1) \end{align*} Each number in the top row is mapped to the one directly under it. This is also easily implemented in a computer program by using a simple, static array to look up function values. Or did you have something else in mind? Edit: To add some randomness into the mix, we could, instead of assigning a single number to each input, assign a discrete probability distribution on $\{ 1,2,3,4,5\}$. The idea would then be that the input is paired with a random, uniformly distributed number $r$ on the unit interval $[0,1]$ (you can get these by calling an appropriate random number generator in your program). A discrete probability distribution on $\{1,2,\ldots, 5\}$ is nothing but a function $p: \{1,2,3,4,5\} \to [0,1]$ such that $$ \sum_{n = 1}^{5} p(n) = 1.$$ So, for instance, if the input is $2$, and we want the function to produce the number $5$ half the time, the number $4$, say $40\%$ of the time and the number $3$ $10\%$ of the time, the function $p$ would be \begin{align*} & (1,2,\phantom{0.}3\phantom{0},\phantom{0.}4\phantom{0},\phantom{.}5\phantom{5})\\ & (0,0,0.10,0.40,0.5) \end{align*} Given an input of $2$, we use the assigned probability distribution and the randomly generated number $r$ to decide what the function value should be. In this case, we can use the following rules: $$ f(2) = \begin{cases} 3 & \text{ if } 0 \leq r \leq 0.10, \\\\ 4 & \text{ if } 0.10 < r \leq 0.50, \\\\ 5 & \text{ if } 0.50 < r \leq 1. \end{cases}$$ Does this make sense to you? (Notice that the with of the intervals for $r$ is the same as the probability we assigned that particular number; this ensures that the events happen with the correct frequencies). Edit: I'll add a quick note about implementation too, since the solution, as it stands, may be slightly awkward to deal with. I would suggest that instead of working with the probability distribution directly, use the cumulative probability distribution instead, i.e. $$ P(x \leq n) = \sum_{i = 1}^{n} p(i).$$ For the distribution above, we would have the cumulative distribution function \begin{align*} &(1,2,\phantom{0.}3\phantom{0},\phantom{0.}4\phantom{0},\phantom{1.}5\phantom{0}) \\ &(0,0,0.10,0.50,1.00) \end{align*} So, given $r$, you determine $f(n)$ by simply walking this array of numbers in increasing order, and stop when you encounter a cumulative probability P such that $r \leq P$.
{ "pile_set_name": "StackExchange" }
Q: How to set the order of for loops I do, $ awk '{ a[$0] } END{for (i in a)print i }' <(echo -e "bar\nfoo") foo bar I also tried other input files, and the order in which these for loops run seems like random. How do you say to awk: remain the order as in the file, so here it should be, bar foo Thanks, Eric J. A: You need to keep track of the order yourself. In this case, this is as simple as: awk '{a[NR] = $0} END { for( i=1; i<= NR; i++ ) print a[i]}' The arrays in awk are associative, so the index into the array can be an arbitrary string. As such, there is no natural order on the index, so the (i in a) syntax returns the indices in the order determined by the implementation. That is, the language does not impose a requirement on the order, and the implementation uses whatever data structure it wants to store the data and walks that data structure in whatever fashion is most convenient. So different versions of awk will likely give a different order. The order is not random, but cannot be easily predicted without understanding the underlying implementation. By using integers for the index, you can control the order.
{ "pile_set_name": "StackExchange" }
Q: Using x-path " | " operator I can choose several paths using .//div/h1/text() | .//div/h2/text(). However I would like to know if there's a way of doing it without explicitly writing out the part that is common for both path's - in this case .//div/ - every time? A: As for shortcuts, with XPath 2.0 you can shorten e.g. //div/h1 | //div/h2 to e.g. //div/(h1 | h2) but that syntax is not allowed in XPath 1.0. And I think XPath 3.0 will introduce a let clause to define variables. So there I think you can do e.g. let $r := /html/body/div[3]/table[2]/tbody/tr[5] return ($r/span | $r/a). Or for your corrected sample with XPath 2.0 you can shorten .//div/h1/text() | .//div/h2/text() to .//div/(h1/text() | h2/text()). But with XPath 1.0 all you can do is use .//div/*[self::h1 | self::h2]/text().
{ "pile_set_name": "StackExchange" }
Q: Angular JS Factory Variables is undefined I have been attempting to create a script that grabs session data from a PHP API using Angular JS to create authentication. I have created a factory called User and in my loginController I use User.Initialise() to check whether the session in PHP has a user_id attached to it. When using User.Initialise() in my loginController (bare in mine my session has a user attached to it) it will use $location.path("/dashboard") to change the route to the dashboard. The dashboard route has a controller that has the variable $scope.UserID which is assigned using User.Session.user_id, however, when I attempt to call User.Session it returns undefined, even though User.Initialise(); assigns it in the loginController. Can anybody shed some light on this? var $Gladium = angular.module("Gladium", ["ngRoute", "ngAnimate", "ngSanitize"]); $Gladium.config(function($routeProvider, $locationProvider){ $routeProvider.when("/",{ templateUrl: "pages/login.html", controller: "loginController" }).when("/dashboard",{ templateUrl: "pages/dashboard.html", controller: "dashboardController" }).when("/error/:error_code", { templateUrl: "pages/system_error.html", controller: "errorController" }); }); /* Controllers */ $Gladium.controller("dashboardController", function($scope, User){ console.log("Services:"); console.log(User.Session); }); $Gladium.controller("loginController", function($scope, $location, User){ User.Initialise().then(function(){ $scope.Authenticate = true; if(User.loggedIn()){ $location.path("/dashboard"); } }); /* Variables */ $scope.Email; $scope.Password; $scope.Login = function(){ if(User.logIn($scope.Email, $scope.Password)){ $location.path("/dashboard"); return true; } } }); $Gladium.controller("errorController", function($scope, $routeParams){ $scope.Errors = { "request": "We couldn't process that request at this time. Please try again later.", "unknown": "An unknown error occurred if this is persistant please contact technical support." }; $scope.currentError = $scope.Errors[$routeParams["error_code"]]; }); /* Factories */ $Gladium.factory("User", function($http, $location){ var Session; var Error; return { Initialise: function(){ return $http.get("core.php?do=getSession").then(function(requestData){ if(requestData.data["requestStatus"] == 1){ Session = requestData.data.data; }else{ $location.path("/error/request"); return false; } }); }, loggedIn: function(){ if(Session["user_id"] != 0){ return true; }else{ return false; } }, logOut: function(){ if(Session["user_id"] != 0 ){ $http.post("core.php",{ do: "logout" }).then(function(requestData){ if(requestData.data["requestStatus"] == 1){ }else{ } }); }else{ console.warn("There is no user session to logout."); } }, logIn: function(Email, Password){ $http.post("core.php",{ do: "login", email: Email, password: Password }).then(function(requestData){ if(requestData.data["requestStatus"] == 1){ Data = requestData.data; if(Data["actionStatus"] == 1){ Initialise(); }else{ Error = Data["Error"]; return false; } }else{ $location.path("/error/request"); return false; } $location.path("/error/unknown"); return false; }); } } }); A: I think that u just forget to return the Session variable which should be a property of User Service .... $Gladium.factory("User", function($http, $location){ var Session; var Error; return { // return the Session so it can be accessed via User.Session, or it is a variable in private closure Session:Session Initialise: function(){ return $http.get("core.php?do=getSession").then(function(requestData){ if(requestData.data["requestStatus"] == 1){ Session = requestData.data.data; }else{ $location.path("/error/request"); return false; } }); }, .... UPDATE Sorry the change above won't solve your problem since you are assigning the Session closure variable, which will not change User.Session.In this way it still remains undefined. There are several ways for you to solve this problem. One i think that is the most simple is to keep the Session private and access it via a get function User.getSession(). $Gladium.factory("User", function($http, $location){ var Session; var Error; return { // use get function to get Session getSession:function(){ return Session; }, Initialise: function(){ return $http.get("core.php?do=getSession").then(function(requestData){ if(requestData.data["requestStatus"] == 1){ Session = requestData.data.data; }else{ $location.path("/error/request"); return false; } }); }, .... In this way u can access your Session by User.getSession().
{ "pile_set_name": "StackExchange" }
Q: Why do we have mutableOrderedSetValueForKey yet not OrderedSetValueForKey? What about if we just want to look at what's there rather wanting to change stuff and then we want to access it by it's key rather than using dot notation? For example: I have object called CatalogData I can do CatalogData.Images to get the pages. However, say I have a function that return NSManagedObject and I want to pass @"Images" to that function. So, eventually it'll get something like [anNSManagedObjectThatisactuallyaCatalogData orderdSetforKey:@"Images"] Well, we can't have that. So why? Should we use the good old objectForKey? A: You can just use [anNSManagedObjectThatisactuallyaCatalogData valueForKey:@"Images"] which returns an NSOrderedSet if "Images" is an ordered to-many relationship.
{ "pile_set_name": "StackExchange" }
Q: How configure GWTTestCase extended class I want to write test case for GWT composite component i created, I had class Count which extends com.google.gwt.user.client.ui.Composite and in this Count i had a text box and some handler for this to display labels according to the values. Now i want to write test case for this class, i tried like code below but it always show same Error : java.lang.NoSuchMethodError: org.mortbay.thread.Timeout.(Ljava/lang/Object;)V my code is: package com.rubirules.uibuilder.client; import org.junit.Test; import com.google.gwt.junit.client.GWTTestCase; public class CountTest extends GWTTestCase { @Override public String getModuleName() { return "com.rubirules.uibuilder.client.Count"; } @Test public void testNullConstructor(){ assertFalse(true); //TODO need to add some code to test Count class } } also i want to know what is the use of getModuleName() method? I had given the string path of my class under test. the compleate error message is: java.lang.NoSuchMethodError: org.mortbay.thread.Timeout.<init>(Ljava/lang/Object;)V at org.mortbay.io.nio.SelectorManager$SelectSet.<init>(SelectorManager.java:306) at org.mortbay.io.nio.SelectorManager.doStart(SelectorManager.java:223) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39) at org.mortbay.jetty.nio.SelectChannelConnector.doStart(SelectChannelConnector.java:303) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39) at org.mortbay.jetty.Server.doStart(Server.java:233) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39) at com.google.gwt.dev.shell.jetty.JettyLauncher.start(JettyLauncher.java:672) at com.google.gwt.dev.DevMode.doStartUpServer(DevMode.java:509) at com.google.gwt.dev.DevModeBase.startUp(DevModeBase.java:1093) at com.google.gwt.junit.JUnitShell.getUnitTestShell(JUnitShell.java:707) at com.google.gwt.junit.JUnitShell.runTest(JUnitShell.java:652) at com.google.gwt.junit.client.GWTTestCase.runTest(GWTTestCase.java:441) at junit.framework.TestCase.runBare(TestCase.java:134) at junit.framework.TestResult$1.protect(TestResult.java:110) at junit.framework.TestResult.runProtected(TestResult.java:128) at junit.framework.TestResult.run(TestResult.java:113) at junit.framework.TestCase.run(TestCase.java:124) at com.google.gwt.junit.client.GWTTestCase.run(GWTTestCase.java:296) at junit.framework.TestSuite.runTest(TestSuite.java:243) at junit.framework.TestSuite.run(TestSuite.java:238) at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) [WARN] failed SelectChannelConnector@0.0.0.0:0 java.lang.NoSuchMethodError: org.mortbay.thread.Timeout.<init>(Ljava/lang/Object;)V at org.mortbay.io.nio.SelectorManager$SelectSet.<init>(SelectorManager.java:306) at org.mortbay.io.nio.SelectorManager.doStart(SelectorManager.java:223) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39) at org.mortbay.jetty.nio.SelectChannelConnector.doStart(SelectChannelConnector.java:303) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39) at org.mortbay.jetty.Server.doStart(Server.java:233) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39) at com.google.gwt.dev.shell.jetty.JettyLauncher.start(JettyLauncher.java:672) at com.google.gwt.dev.DevMode.doStartUpServer(DevMode.java:509) at com.google.gwt.dev.DevModeBase.startUp(DevModeBase.java:1093) at com.google.gwt.junit.JUnitShell.getUnitTestShell(JUnitShell.java:707) at com.google.gwt.junit.JUnitShell.runTest(JUnitShell.java:652) at com.google.gwt.junit.client.GWTTestCase.runTest(GWTTestCase.java:441) at junit.framework.TestCase.runBare(TestCase.java:134) at junit.framework.TestResult$1.protect(TestResult.java:110) at junit.framework.TestResult.runProtected(TestResult.java:128) at junit.framework.TestResult.run(TestResult.java:113) at junit.framework.TestCase.run(TestCase.java:124) at com.google.gwt.junit.client.GWTTestCase.run(GWTTestCase.java:296) at junit.framework.TestSuite.runTest(TestSuite.java:243) at junit.framework.TestSuite.run(TestSuite.java:238) at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) [WARN] failed Server@2edfcb java.lang.NoSuchMethodError: org.mortbay.thread.Timeout.<init>(Ljava/lang/Object;)V at org.mortbay.io.nio.SelectorManager$SelectSet.<init>(SelectorManager.java:306) at org.mortbay.io.nio.SelectorManager.doStart(SelectorManager.java:223) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39) at org.mortbay.jetty.nio.SelectChannelConnector.doStart(SelectChannelConnector.java:303) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39) at org.mortbay.jetty.Server.doStart(Server.java:233) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39) at com.google.gwt.dev.shell.jetty.JettyLauncher.start(JettyLauncher.java:672) at com.google.gwt.dev.DevMode.doStartUpServer(DevMode.java:509) at com.google.gwt.dev.DevModeBase.startUp(DevModeBase.java:1093) at com.google.gwt.junit.JUnitShell.getUnitTestShell(JUnitShell.java:707) at com.google.gwt.junit.JUnitShell.runTest(JUnitShell.java:652) at com.google.gwt.junit.client.GWTTestCase.runTest(GWTTestCase.java:441) at junit.framework.TestCase.runBare(TestCase.java:134) at junit.framework.TestResult$1.protect(TestResult.java:110) at junit.framework.TestResult.runProtected(TestResult.java:128) at junit.framework.TestResult.run(TestResult.java:113) at junit.framework.TestCase.run(TestCase.java:124) at com.google.gwt.junit.client.GWTTestCase.run(GWTTestCase.java:296) at junit.framework.TestSuite.runTest(TestSuite.java:243) at junit.framework.TestSuite.run(TestSuite.java:238) at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) A: Please check how Google GWT Team writes test case for widgets. You can view them in google gwt trunk code - http://code.google.com/p/google-web-toolkit/source/browse/trunk/user/test/com/google/gwt/user/client/ui Edited with answer from Comment : Change getModuleName() return string to reflect path to gwt module file com.rubirules.uibuilder.UIbuilder.
{ "pile_set_name": "StackExchange" }
Q: ffmpeg motion interpolation alternatives or speedup I use ffmpeg to create videos, it is awesome tool. I create videos from pictures and need to make them as smooth as possible. I found, that what I need called 'motion interpolation'. I started to search all forums, and found only 3 things can help me: slowmovideo, butterflow and new ffmpeg's filter minterpolate. slowmovideo needs many configuration, I was not able to get it to work as I want. with butterflow, I tried anything. From installing OpenCL, OpenGL and other stuff to switching to nvidia binary drivers and installing all sdk tools and cuda. It never worked. Some error about cuda, and google don't know about it. So third option was the only one available. When I tried it, it did exactly what I want! But it is incredibly SLOW. I have 8-core CPU, and it processes about 0.1-0.3 fps. And uses just 1 CORE, no video card. Is there any ways to motion interpolate frames on GPU or on CPU but faster? Only GNU/Linux A: Is there any ways to motion interpolate frames on GPU? Using minterpolate? No. It is using libswscale which has no video hardware acceleration support that I am aware of. or on CPU but faster? You could experiment with the various minterpolate options to possibly increase speed. Or offer a bounty on the bug tracker or Bountysource to get threading support enabled, or submit a patch enabling it (although I'm not sure if that is possible or realistic for this filter). Edit: Shortly after answering I saw that you asked this on the ffmpeg-devel mailing list where a developer suggested a bounty, so that may be your best choice if you want to use this filter and get increased speed. A: I know it's a dumb solution but it does give you the speedup you want: if you have multiple clips, you can run a separate ffmpeg command for each clip at the same time without affecting the performance of each process, until you have more processes than cores.
{ "pile_set_name": "StackExchange" }
Q: Python: write a wav file into numpy float array ifile = wave.open("input.wav") how can I write this file into a numpy float array now? A: >>> from scipy.io.wavfile import read >>> a = read("adios.wav") >>> numpy.array(a[1],dtype=float) array([ 128., 128., 128., ..., 128., 128., 128.]) typically it would be bytes which are then ints... here we just convert it to float type you can read about read here https://docs.scipy.org/doc/scipy/reference/tutorial/io.html#module-scipy.io.wavfile A: Seven years after the question was asked... import wave import numpy # Read file to get buffer ifile = wave.open("input.wav") samples = ifile.getnframes() audio = ifile.readframes(samples) # Convert buffer to float32 using NumPy audio_as_np_int16 = numpy.frombuffer(audio, dtype=numpy.int16) audio_as_np_float32 = audio_as_np_int16.astype(numpy.float32) # Normalise float32 array so that values are between -1.0 and +1.0 max_int16 = 2**15 audio_normalised = audio_as_np_float32 / max_int16
{ "pile_set_name": "StackExchange" }
Q: Data not being stored in Mongodb I am trying to run this code on a NodeJS server and make 'POST' requests from Postman. I keep getting a response that turns up an empty data field when it should be populated with data. This is the response from the server after a 'POST' request: { data: [] } The data array should not be empty. var deviceModel = new Schema({ data: [ { type: Schema.Types.Mixed, required: true} ], time: { type: Date, default:Date.now } }); This is the content of the main application file: var app = express(); app.use(bodyParser.urlencoded({extended:true})); //app.use(bodyParser.json()); var deviceData = mongoose.model('device1', deviceModel); app.post('/',function(req, res){ var devicedataat = new deviceData(req.body); console.log(req.body); devicedataat.save(); console.log(devicedataat); res.status(201); res.send(devicedataat); }); I would like to know what I'm doing wrong and how I can fix it. A: The application uses the bodyParser.urlencoded middleware so you'll need to send your data as x-www-form-urlencoded via Postman. To send an array in the 'POST' request, you'll need to send each item. You can see an example below:
{ "pile_set_name": "StackExchange" }
Q: React.js onChange make the parent aware of the changed state I have a component that is rendering <select> with <option> elements. When any change occurs, I would like to change the state of the component to keep the value of the currently selected option. As far as I know I don't have any other alternative for keeping this value since the props in React JS have to be immutable. The problem comes when I notify the parent for the change. I do this using a callback from handleChange to parent's handleChangefunction. So in the child element I actually call the handleChangefunction, set the new state and call the callback (parent's handleChange). But then in the parent function when I ask for the value of the state property I receive the older one (seems like the new one is still not set). So any ideas? A: I would suggest using a single data flow pattern (like Flux or Reflux) to structure your react apps and avoid that kind of mistake and complicated reverse data flows. From what I understood of your question, without Flux, you could do something like this. var React = require("react"); var ParentComponent = React.createClass({ handleChange: function(newOption){ console.log("option in child component changed to " + newOption); }, render: function(){ return ( <div> <ChildComponent handleChange={this.handleChange}/> </div> ) } }); var ChildComponent = React.createClass({ getInitialState: function(){ return { selectedOption: 0 }; }, handleChange: function(){ var option = this.refs.select.getDOMNode().value; this.setState({ selectedOption: option}); // I'm passing the actual value as an argument, // not this.state.selectedOption // If you want to do that, do it in componentDidUpdate // then the state will have been set this.props.handleChange(option); }, render: function(){ return ( <div> <h4>My Select</h4> {this.state.selectedOption} <select ref="select" onChange={this.handleChange}> <option>1</option> <option>2</option> <option>3</option> </select> </div> ) } }); Edit Added a couple of forgotten semi-colons. I'm coding too much Python these days. Edit2 Changed the code. Your problem might be that if you call the parent's handleChange with the value from the state (this.state.selectedOption), the state won't be set yet so you have to give the actual value as an argument instead. If you really want to use this.state.selectedOption, call parent's handleChange in componentDidUpdate.
{ "pile_set_name": "StackExchange" }
Q: Google XPATH importxml can find "show" but not "showcount" or "count" Using this webpage as an example http://forums.macrumors.com/showthread.php?t=1688317 On a google spreadsheet, the following DO NOT work with importxml(): //a[contains(@href,"showpost")]/@href //a[contains(@href,"showcount")]/@href //*[@id="postcount18545482"] The last one (//*[@id="postcount18545482"]) was copied directly from Chrome's element viewer. The following DO work but exclude any results with the word "showcount", "postcount", or "showpost": //div[contains(@id,"post_message")]/@id //a[contains(@href,"show")]/@href //a[contains(@href,"post")]/@href Is there something special about the word "count" when working with importxml() or XPATH? How can I get the missing entries? A: ImportXML function in Google Docs spreadsheet can not process data that is created in a two-step process. For example, when an authentication token must be retrieved first before making the url request, or when the URL tells the server to dynamically create an xml output after which the user is redirected to the output, even when the URL stays the same. You might want to look into Google Apps Scripts (http://code.google.com/googleapps/appsscript/index.html) to handle this case. Taken from here In your particular case the anchor parameters get set in the vbulletin_post_loader.js script called after the page container is loaded. ... pc_obj=fetch_object("postcount"+this.postid); openWindow("showpost.php?"+(SESSIONURL?"s="+SESSIONURL:"") +(pc_obj!=null?"&postcount="+PHP.urlencode(pc_obj.name):"")+"&p="+A) ... In other words, when importXML() scans the page, the nodes containing 'showpost' or 'postcount' in href are not yet on the page: Looks like importXML() works with static pages only and not able to handle dynamically loaded content. Try to find another way of obtaining the number of post in a thread.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to create stateful web service in C#? I have now something like this: public class Service1 : System.Web.Services.WebService { [WebMethod] public string Method1() { SomeObj so = SomeClass.GetSomeObj(); //this executes very long time, 50s and more return so.Method1(); //this exetus in a moment } [WebMethod] public string Method2() { SomeObj so = SomeClass.GetSomeObj(); //this executes very long time, 50s and more return so.Method2(); //this exetus in a moment } ... } Is it possible to make stateful web service so that I can reuse SomeObj so and just call methods on the same object? So the client which will use this service would first call web method which would create so object and return some ID. And then in subsequent calls the web service would reuse the same so object based on ID. EDIT Here is my actual code: [WebMethod] public List<ProcInfo> GetProcessList(string domain, string machineName) { string userName = "..."; string password = "..."; TaskManager tm = new TaskManager(userName, password, domain, machineName); return tm.GetRunningProcesses(); } [WebMethod] public bool KillProcess(string domain, string machineName, string processName) { string userName = "..."; string password = "..."; (new TaskManager(userName, password, domain, machineName);).KillProcess(processName); } A: Stateful web services are not scalable and I wouldn't recommend them. Instead you could store the results of expensive operations in the cache. This cache could be distributed through custom providers for better scalability: [WebMethod] public string Method1() { SomeObj so = TryGetFromCacheOrStore<SomeObj>(() => SomeClass.GetSomeObj(), "so"); return so.Method1(); //this exetus in a moment } [WebMethod] public string Method2() { SomeObj so = TryGetFromCacheOrStore<SomeObj>(() => SomeClass.GetSomeObj(), "so"); return so.Method2(); //this exetus in a moment } private T TryGetFromCacheOrStore<T>(Func<T> action, string id) { var cache = Context.Cache; T result = (T)cache[id]; if (result == null) { result = action(); cache[id] = result; } return result; }
{ "pile_set_name": "StackExchange" }
Q: Meaning of 座 in 口座 I don't understand why 口座, "(bank) account" is written with the kanji 座 in it... I got that 口 conveyed the idea of a number of something from the 広辞苑 which have this definition : 人または物件の数(をかぞえる語)。 But what about the other? A: 座{ざ} literally meaning a seat stands here for a place - a designated spot where a certain action (like transactions occurred). The word 座 was historically used for a trade guild (and wikipedia article further explains further theories behind its origins); the character is used in the word 銀座{ぎんざ} for a mint and is also commonly used in names of theatres (like 松竹座{しょうちくざ}) So while contemporary bank account might be just a set of records in a database, the word 銀行口座 originates from the place you go to perform bank transactions.
{ "pile_set_name": "StackExchange" }
Q: C# Index Out Of Range Exception I seem to be having a problem with C# 2008. I am creating a simple program that shows a list of all the files within a specific folder. I chose to experiment with system files in the Windows folder. It shows a list of the files and then an exception occurs. Here is the code: if (EnterNumber == "1") { Console.WriteLine("Files"); DirectoryInfo folderInfo = new DirectoryInfo("F:\\WINDOWS"); FileInfo[] Files = folderInfo.GetFiles(); String UserChoice = Console.ReadLine(); for (int index = 0; index < Files.Length; index++) { Console.WriteLine("{0}, {1} ({2})", index++, Files[index].Name, Files[index].Length); } Console.Write("Return To Main Menu?: "); if (UserChoice == "y") { So the user presses the number 1 to show the files and they appear in a list. It displays the files in the Windows folder. But can you see the console write line with several pieces of information? A line appears with a message to an error. The exception occurs saying that the index is outside the bounds of the array. I know what an array is, but I have a problem applying that information. If you can tell me of a way to remove this error then I would be grateful. So the files show normally, no matter how long the list is. Also, is there a way to allow the user to clear the screen and return to the main menu? I have tried the clear function, but should I keep adding the if statements that allow the user to input their choice again? A: for (int index = 0; index < Files.Length; index++) { Console.WriteLine("{0}, {1} ({2})", index++, Files[index].Name, Files [index].Length); } The problem is in your writeline, you are incrementing index again. I would just change it to index and not index++.
{ "pile_set_name": "StackExchange" }
Q: When I run rails server it is showing error about database.yml I have ROR version 4.0.0 and ruby version 2.0.0.After creating the project app when I try to run rails server it is showing me the error about yml file. The screen looks like this C:\Sites\app>rails s => Booting WEBrick => Rails 4.0.0 application starting in development on => Run `rails server -h` for more startup options => Ctrl-C to shutdown server Exiting C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.0.0/lib/rails/ap plication/configuration.rb:113:in `rescue in database_configuration': YAML synta x error occurred while parsing C:/Sites/app/config/database.yml. Please note tha t YAML must be consistently indented using spaces. Tabs are not allowed. Error: (<unknown>): could not find expected ':' while scanning a simple key at line 9 c olumn 3 (RuntimeError) from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.0.0 /lib/rails/application/configuration.rb:103:in `database_configuration' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4 .0.0/lib/active_record/railtie.rb:174:in `block (2 levels) in <class:Railtie>' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activesupport- 4.0.0/lib/active_support/lazy_load_hooks.rb:38:in `instance_eval' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activesupport- 4.0.0/lib/active_support/lazy_load_hooks.rb:38:in `execute_hook' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activesupport- 4.0.0/lib/active_support/lazy_load_hooks.rb:28:in `block in on_load' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activesupport- 4.0.0/lib/active_support/lazy_load_hooks.rb:27:in `each' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activesupport- 4.0.0/lib/active_support/lazy_load_hooks.rb:27:in `on_load' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4 .0.0/lib/active_record/railtie.rb:173:in `block in <class:Railtie>' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.0.0 /lib/rails/initializable.rb:30:in `instance_exec' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.0.0 /lib/rails/initializable.rb:30:in `run' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.0.0 /lib/rails/initializable.rb:55:in `block in run_initializers' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:150:in `block i n tsort_each' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:183:in `block ( 2 levels) in each_strongly_connected_component' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:219:in `each_st rongly_connected_component_from' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:182:in `block i n each_strongly_connected_component' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:180:in `each' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:180:in `each_st rongly_connected_component' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:148:in `tsort_e ach' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.0.0 /lib/rails/initializable.rb:54:in `run_initializers' Please help me on it. A: You can check your YAML file using some kind of YAML Validator Here is your valid YAML: development: adapter: postgresql database: postgres password: 191192 pool: 5 timeout: 5000 username: postgres production: adapter: postgresql database: postgres pool: 5 timeout: 5000 test: adapter: postgresql database: postgres pool: 5 timeout: 5000
{ "pile_set_name": "StackExchange" }
Q: Bounce user over to mobile site, but still allow "full site" view This is scenario I'm going for: User visits the site, site.com, meta tag detects that the user is on a mobile device, and bounces the user over to m.site.com. Then, the user sees a link for "View full site," and clicks on it. But then, the site bounces the user over again. Is there a clean way of handling this? Allowing the user to choose which version he/she wants to see, but by default, first going to the mobile site? Thanks! A: Tonnes of ways I can thing of. You could have a parameters/page which the user visits. For example google have /ncr (no country redirect). When the user visits this particular page you could set a session/cookie which can be monitored to prevent redirection. -You could only redirect the user if a particular cookie is not detected, and they are using a mobile user-agent. You could check the referer in addition to the user-agent, and if the referer has come from m.site.com then don't redirect.
{ "pile_set_name": "StackExchange" }
Q: Meaning of Exponential map I've been studying differential geometry using Do Carmo's book. There's the notion of exponential map, but I don't understand why it is called "exponential" map. How does it has something to do with our common notion of exponentiation? I read from the book The road to reality (by R. Penrose) that it is related to taking exponentiation when making (finite) Lie group elements from Lie algebra elements. It seems like using Taylor's theorem on a manifold so we have, for example, there was the following equation explaining why it is the case. $f(t) = f(0) + f'(0)t + \frac{1}{2!}f''(0) t^2+\cdots = (1+t\frac{d}{dx}+\frac{1}{2!}t^2\frac{d^2}{dx^2}+\cdots)f(x)|_{x=0} = e^{t\frac{d}{dx}}f(x)|_{x=0}$. The differential operator can be thought of as a vector field on a manifold, and it is how Lie algebra elements (which are vectors, on a group manifold (Lie group), in a tangent space at the identity element). If I understood correctly, the truth is that this is exactly the exponential map that sends a vector on a tangent space into the manifold in such a way that it becomes the end point of a geodesic (determined by the vector) having the same length. Why is the above Taylor expansion valid on a manifold? Why is the exponential map the same as taking exponentiation? A: The idea of an exponential is the continuous compounding of small actions. Suppose you start with an object $p$, perform an action on it $v$, and then add the result back to the original object. What happens if you instead take half as much action but do it twice? What about if you take one tenth the action but do it ten times? The exponential function tries to capture this idea: $$\exp (\text{action}) = \lim_{n \rightarrow \infty} \left(\text{identity} + \frac{\text{action}}{n}\right)^n.$$ On a differentiable manifold there is no addition, but we can consider this action as pushing a point a short distance in the direction of the tangent vector, $$``\left(\text{identity} + \frac{\text{v}}{n}\right)"p := \text{push }p\text{ by} \frac{1}{n} \text{ units of distance in the }v \text{ direction}.$$ Doing this over and over, we have $``\left(\text{identity} + \frac{\text{v}}{n}\right)^n"p$ means push $p$ by $\frac{1}{n}$ units of distance in the $v$ direction, then push it again in the same direction you already pushed it, and keep doing so until you have pushed it $n$ times. So long as $\frac{1}{n}$ is small enough that pushing points and vectors in a tangent direction makes sense, what we end out doing is pushing the point $p$ a total of $1$ unit of distance along the geodesic generated by $v$.
{ "pile_set_name": "StackExchange" }
Q: The existence of an algebra whose set of identities and first order theory are equivalent Is there an algebra $A$ (for example a group) such that $Th(A)$ is logically equivalent to $id(A)$? In other words, is there an algebra $A$ such that $$ Mod(Th(A))=Var(A)? $$ Clearly finite algebras do not have this property. It seems that such an algebra should be relatively free. This question is related to my previous two questions Relatively free algebras in a variety generated by a single algebra relatively free groups in $Var(S_3)$ Edition: Only trivial algebra has this property by the comment of Gerhard Paseman. So I ask again the question by $\pm id(A)$ instead of $id(A)$. Is there any algebra A (especially a group) such that $Th(A)$ is logically equivalent to $\pm id(A)$? Here $\pm id(A)$ means the set of identities and negated identities. P.S. By negated identity I mean a sentence of the form $$ \forall x_1\ldots \forall x_n: p(x_1, \ldots, x_n)\neq q(x_1, \ldots, x_n), $$ where $p$ and $q$ are terms. Is there any negated identity in a non-trivial algebra? Clearly there are no negated identities in groups but if we add constants to the language of groups there will be many negated identities. A: I imagine that definitions of $Mod, Th, Var$ and so on have not changed since I saw them decades ago. The trivial one element algebra in any finite type (and likely any infinite type) is an easy example which satisfies $Mod(Th(\textbf{A})) \approx Var(\textbf{A})$. Since it is expected that $Th(\textbf{A})$ is strong enough to indicate whether $\textbf{A}$ has more than one element, this is the only example to be expected (Thank you Joel). Gerhard "Ask Me About Trivial Algebra" Paseman, 2014.01.09 A: For an example with a negated identity, let $A$ be a vector space over an infinite field in the usual signature ($+$ and scalar multiplications) together with an additional constant $1\ne0$. EDIT: Since it was apparently not obvious (judging from the comment), this is meant to be an example of an algebra whose full first-order theory is equivalent to its set of valid identities and negated identities. (This follows here from the fact that the theory of infinite vector spaces over a field $F$ is categorical in every cardinality $\kappa>|F|$.)
{ "pile_set_name": "StackExchange" }
Q: Msg 102, Level 15, State 1, Line 33 Incorrect syntax near ')' First time I am trying dynamic query as pivot table. I solve many error using SO. Now I am stuck in following common error. Msg 102, Level 15, State 1, Line 33 Incorrect syntax near ')'. So I can't discover what mistake is..! pivotEx create table pivotEx (name varchar(1), mark int, subject varchar(1)) insert into pivotEx values ('a', 70,'t') ,('a', 80,'e') ,('b', 60,'t') ,('c', 80,'t') ,('c', 90,'e') ,('c', 40,'m') Static Query(working fine) select name, [e],[m],[t] from( select name, mark, subject from pivotEx ) f pivot ( sum(mark) for subject in ([e],[m],[t]) ) p Dynamic Query(what I am try) declare @col varchar(max) declare @sql nvarchar(100) set @col = N'' select @col += ',' + col from (select distinct quotename(subject) col from pivotex) colp select @col=SUBSTRING(@col,2,len(@col)) select @col set @sql = N'select name, '+@col+' from( select name, mark, subject from pivotEx ) f pivot ( sum(mark) for subject in ('+@col+') ) p' EXEC sp_executesql @sql Note: Using SQL Server 2014. Using SSMS 2012. I am new to Dynamic Query. Thanks, TamilPugal A: You need to change @sql data type because your query string is truncated: declare @sql nvarchar(MAX) DBFiddle Demo It is a good practice to print your query with SELECT/PRINT before execution. PRINT @sql -- select name, [e],[m],[t] from(select name, mark, subject from pivotEx ) f pivot( sum(mark) for subje
{ "pile_set_name": "StackExchange" }
Q: Xamarin MVVM passing data to other view I want to pass the data to another view page. So far I can get the data I need to pass. My problem is how do I pass the data in MVVM. I used Application.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage(), true); When I add contactId inside DatabaseSyncPage() an error occurs. "The error is 'DatabaseSyncPage' does not contain a constructor that takes 1 arguments" My code: LoginPageViewModel.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Net; using System.Text; using System.Windows.Input; using TBSMobileApplication.Data; using TBSMobileApplication.View; using Xamarin.Essentials; using Xamarin.Forms; namespace TBSMobileApplication.ViewModel { public class LoginPageViewModel : INotifyPropertyChanged { void OnProperyChanged(string PropertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName)); } public string username; public string password; public string Username { get { return username; } set { username = value; OnProperyChanged(nameof(Username)); } } public string Password { get { return password; } set { password = value; OnProperyChanged(nameof(Password)); } } public class LoggedInUser { public string ContactID { get; set; } } public ICommand LoginCommand { get; set; } public LoginPageViewModel() { LoginCommand = new Command(OnLogin); } public void OnLogin() { if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password)) { MessagingCenter.Send(this, "Login Alert", Username); } else { var current = Connectivity.NetworkAccess; if (current == NetworkAccess.Internet) { var link = "http://192.168.1.25:7777/TBS/test.php?User=" + Username + "&Password=" + Password; var request = HttpWebRequest.Create(string.Format(@link)); request.ContentType = "application/json"; request.Method = "GET"; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode); } else { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { var content = reader.ReadToEnd(); if (content.Equals("[]") || string.IsNullOrWhiteSpace(content) || string.IsNullOrEmpty(content)) { MessagingCenter.Send(this, "Http", Username); } else { var result = JsonConvert.DeserializeObject<List<LoggedInUser>>(content); var contactId = result[0].ContactID; Application.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage { myId = contactId }, true); } } } } else { MessagingCenter.Send(this, "Not Connected", Username); } } } public event PropertyChangedEventHandler PropertyChanged; } } DatabaseSyncPage.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace TBSMobileApplication.View { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class DatabaseSyncPage : ContentPage { public int myId { get; set; } public DatabaseSyncPage () { InitializeComponent (); DisplayAlert("Message", Convert.ToString(myId), "ok"); } } } A: If you want to send the int. First declare that in your DatabaseSyncPage Like below public partial class DatabaseSyncPage : ContentPage { public DatabaseSyncPage( int Id) { } } & when you are pushing your page in your code else block do like this if (content.Equals("[]") || string.IsNullOrWhiteSpace(content) || string.IsNullOrEmpty(content)) { MessagingCenter.Send(this, "Http", Username); } else { var result = JsonConvert.DeserializeObject<List<LoggedInUser>>(content); var contactId = result[0].ContactID; Application.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage(contactId), true); }
{ "pile_set_name": "StackExchange" }
Q: Renaming a Full Text Catalog in SQL Server 2008 Is there anyway to rename a full text catalog in SQL Server 2008? There is seemingly no option to do this in SSMS but I am wondering if there is a SQL command to accomplish this. A: You cannot rename a full text catalog, you can only drop and recreate it, check out this link for a script you can easily modify to to do this... http://support.microsoft.com/kb/2391904
{ "pile_set_name": "StackExchange" }
Q: RecyclerView choose every 8th item in list. How can stop it? There is an recyclerView in my project. Also, I added expandableLayout from a third library. When click layout of it has cardView, it toggle expandable layout. But, for example if click 1st item, it toggle every 8th item in order after 1st item. How can solve it and stop toggle other items? public class BusAdapter extends RecyclerView.Adapter<BusAdapter.ViewHolder> { private Context context; private List<Bus> busList; private static String phoneNumber; private static final int PERMISSION_CODE = 101; private RecyclerView recyclerView; private Locale trlocale; VoyageAdapterToResultActivityListener voyageAdapterToResultActivityListener; public BusAdapter(Context _context, List<Bus> _busList, RecyclerView recyclerView) { this.context = _context; this.busList = _busList; this.recyclerView = recyclerView; this.trlocale = new Locale("tr-TR"); voyageAdapterToResultActivityListener = (VoyageAdapterToResultActivityListener) context; } public class ViewHolder extends RecyclerView.ViewHolder { private TextView tvPrice, text_seat; private ImageView imgLogo; private ConstraintLayout relativeL_row_voyage_view; private CardView cardV_row_voyage; ExpandableLayout expandable_layout; ProgressBar progressB_dialog_seat; private ViewHolder(View view) { super(view);view.findViewById(R.id.relative_seat); expandable_layout = view.findViewById(R.id.expandable_layout); progressB_dialog_seat = view.findViewById(R.id.progressB_dialog_seat); relativeL_row_voyage_view = view.findViewById(R.id.relativeL_row_voyage_view); relativeL_row_voyage_view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { expandable_layout.toggle(); progressB_dialog_seat.setVisibility(View.VISIBLE); final Handler h = new Handler() { @Override public void handleMessage(Message message) { progressB_dialog_seat.setVisibility(View.INVISIBLE); } }; h.sendMessageDelayed(new Message(), 5000); } }); A: Try add a boolean field "isExpanded" to class Bus for your data set. In onBindViewHolder of adapter, setup UI depending on data's isExpanded flag. And when click bus item, set its isExpanded to true or false or !isExpanded as you wish, then make adapter notifyDataSetChanged(). Try: Modify your object class, add following flags. public class Bus { ... boolean isExpanded; boolean isShowProgress; public boolean isExpanded() { return this.isExpanded; } public void setExpanded(boolean expanded) { this.isExpanded = expanded; } public boolean isShowProgress() { return this.isShowProgress; } public void setShowProgress(boolean showProgress) { this.isShowProgress = showProgress; } } In your adapter: public class BusAdapter extends RecyclerView.Adapter<BusAdapter.ViewHolder> { public class ViewHolder extends RecyclerView.ViewHolder { private TextView tvPrice, text_seat; private ImageView imgLogo; private ConstraintLayout relativeL_row_voyage_view; private CardView cardV_row_voyage; ExpandableLayout expandable_layout; ProgressBar progressB_dialog_seat; private ViewHolder(View view) { super(view); view.findViewById(R.id.relative_seat); expandable_layout = view.findViewById(R.id.expandable_layout); progressB_dialog_seat = view.findViewById(R.id.progressB_dialog_seat); relativeL_row_voyage_view = view.findViewById(R.id.relativeL_row_voyage_view); } } public void onBindViewHolder(ViewHolder holder, int i) { Bus bus = busList.get(i); if (bus.isExpanded()) { holder.expandable_layout.expand(); } else { holder.expandable_layout.collapse(); } holder.progressB_dialog_seat.setVisibility(bus.isShowProgress() ? View.VISIBLE : View.INVISIBLE); holder.relativeL_row_voyage_view.setOnClickListener(new View.OnClickListener() { bus.setExpanded(!bus.isExpanded()); bus.setShowProgress(true); notifyDataSetChanged(); final Handler h = new Handler() { @Override public void handleMessage(Message message) { bus.setShowProgress(false); notifyDataSetChanged(); } }; h.sendMessageDelayed(new Message(), 5000); }); ... } }
{ "pile_set_name": "StackExchange" }
Q: select distinct columnA and columnB with sum(cloumnC) I have a table like this: importer exporter quantity A D 0.9 A B 0.9 A B 0.1 B E 9.4 B E 8.9 B D 9.4 C P 9.0 C V 1.0 C P 0.9 I want to find the distinct columnA and columnB with the sum(columnC) and the table is ORDER BY SUM(columnC) DESC. importer exporter quantity B E 18.3 C P 9.9 B D 9.4 A B 1.0 C V 1.0 A D 0.9 when I tried SELECT DISTINCT IMPORTER, EXPORTER, QUANTITY FROM Tablename; The table MYsql shows is not distinct columnA and columnB, in fact it shows duplicated columnA and columnB and the columnC is not added up. A: Try like below SELECT IMPORTER, EXPORTER, sum(QUANTITY) FROM Tablename group by IMPORTER, EXPORTER
{ "pile_set_name": "StackExchange" }
Q: Did the previous painter neglect to prime? The paint on our house is peeling badly. It's yellow paint over wood siding (clapboard). When I scrape, I get pieces of paint that are yellow on both sides, and bare wood underneath. Does that mean that the previous owner failed to use primer? A: It would appear to be that way. There should be a layer of primer. If they did I am sure you would have seen some white on the other side instead of just yellow.
{ "pile_set_name": "StackExchange" }
Q: Why are IE & Safari are not aligning this element to center? http://meowzen.com/pacific-wild.org/initiatives This is how it should be displayed (and is displayed in Firefox & Chrome): However, both IE & Safari are aligning this way: Any ideas how we can align the IE & Safari "Learn More" button to center? p.s. This is a responsive layout. A: I think the question is why it DOES work in firefox and chrome, since I don't see any horizontal positioning showing up. Does this work? .image-banner .mw-qf {left: 50%;}
{ "pile_set_name": "StackExchange" }
Q: how to have different labelling option for different set of nodes in networkx visualisation? I have a graph that consists of three sets of nodes 1. servers 2. stations 3. users I want to draw them with networks built-in visualization. In the drawing, I want to have the labels for users and stations but not for servers. However, this doesn't work. when I try this: nx.draw_networkx_nodes(network, with_labels=False, nodelist=self.servers_idx, node_size=50, node_shape='s', pos=servers_pos, node_color='r') nx.draw_networkx_nodes(network, with_labels=True, nodelist=self.stations_idx, node_size=50, node_shape='^', pos=stations_pos, node_color='g') nx.draw_networkx_nodes(network, with_labels=True, nodelist=self.users_idx, node_size=10, node_shape='o', pos=users_pos, node_color='b') I get the following figure: which as you see shows none of the labels, but I have set the with_labels variable value to True for stations and users and the expectation is that it will show them. The strange thing is that when I set all the with_labels to True it will show all the labels. But if I only set one of them to False it will not show the other two (like that I have set all of them False). Does anyone have any idea what is happening here? A: As Paul Brodersen said, it looks like a networkx bug. But you can go around it by using nx.draw_networkx_labels function for users and stations, but not for servers: import networkx as nx network = nx.Graph() network.add_nodes_from([1, 2, 3, 4, 5]) # Manually create positions and indices servers_pos = {1: (-1, 1), 2: (1, 1)} stations_pos = {3: (0, -1), 4: (1, 0)} users_pos = {5: (0, 0)} servers_idx = [1, 2] stations_idx = [3, 4] users_idx = [5] # Draw nodes (exactly your code, but without `with_labels` attribute) nx.draw_networkx_nodes(network, nodelist=[1, 2], node_size=50, node_shape='s', pos=servers_pos, node_color='r') nx.draw_networkx_nodes(network, nodelist=[3, 4], node_size=50, node_shape='^', pos=stations_pos, node_color='g') nx.draw_networkx_nodes(network, nodelist=[5], node_size=10, node_shape='o', pos=users_pos, node_color='b') # Manually create labels for users and stations stations_labels = {3: 'WAKA-3', 4: 'WAKA-4'} users_labels = {5: 'John Doe'} nx.draw_networkx_labels( network, pos=stations_pos, labels=stations_labels ) nx.draw_networkx_labels( network, pos=users_pos, labels=users_labels ) Here is the result:
{ "pile_set_name": "StackExchange" }
Q: Adding UNNotificationAction to firebase FCM push notification in Swift 4 I am trying to add some custom action when FCM push notification. I tried adding these after when registering my notification. UNUserNotificationCenter.current().delegate = self let acceptAction = UNNotificationAction(identifier: "ACCEPT_ACTION", title: "Accept", options: UNNotificationActionOptions(rawValue: 0)) let declineAction = UNNotificationAction(identifier: "DECLINE_ACTION", title: "Decline", options: UNNotificationActionOptions(rawValue: 0)) let center = UNUserNotificationCenter.current() if #available(iOS 11.0, *) { let meetingInviteCategory = UNNotificationCategory(identifier: "MEETING_INVITATION", actions: [acceptAction, declineAction], intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: "", options: .customDismissAction) center.setNotificationCategories([meetingInviteCategory]) } let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] center.requestAuthorization( options: authOptions, completionHandler: {_, _ in }) But unfortunately, the action is not still appearing. Is there anyway to achieve this? This is what I am trying to achieve. My firebase FCM setup and all notification are working fine. I just can't add action to these notifications. A: I got it. I just need to add click_action field in body of fcm/send. and set that click_action key to category identifier.
{ "pile_set_name": "StackExchange" }
Q: Probability expectation and variance of a random variable polynomial Edited: Let's say we have random variables $A,B\sim\mathcal{U}(0,1)$. We can easily calculate their expectation and variance and get $E(A)=E(B)=\frac{1}{2}$ and $Var(A)=Var(B)=\frac{1}{12}$. However, what bothers me is how we can calculate expectation and variance of a random variable that can be expressed like this for example: $$Y=3A^6-2B^2$$ How can we calculate the expectation and variance of $A^6$? I guess $B^2$ should follow from that. A and B are independent of each other. A: We may use the Linearity of Expectation and the Bilinearity of Covariance. $\begin{split}Y&\mathop{:=}3A^6-2B^2\\\therefore\qquad& \\\mathsf E(Y)&=3\mathsf E(A^6)-2\mathsf E(B^2)\\ \mathsf {Var}(Y)&=9\mathsf{Var}(A^6)+4\mathsf{Var}(B^2)-12\mathsf{Cov}(A^6,B^2) \\ &= 9\mathsf E(A^{12})-9\mathsf E^2(A^6)+4\mathsf E(B^{2})-4\mathsf E^2(B^2)-12\mathsf E(A^{6}B^2)+12\mathsf E(A^6)\mathsf E(B^2)\end{split}$ How those terms evaluate depends, of course, on how $A,B$ are jointly distributed. When $A,B$ are independent and identically uniform distributed over $(0;1)$, we first note that the covariance will be zero, so only have to worry about expectation of the powers of each variable. Now for $n\geq 1$ we have $\mathsf E(A^n)=\mathsf E(B^n)=\int_0^1 x^n~\mathsf d x =\tfrac 1{n+1}$, by definition for the uniform distribution, and the rest is just substitution. For example: $\mathsf {Var}(A)=\mathsf E(A^2)-\mathsf E^2(A)=\tfrac 13-\big(\tfrac 12\big)^2=\tfrac 1{12}$
{ "pile_set_name": "StackExchange" }
Q: embed php in c++ application or any way can it be done? i was looking for way to embed php script into c++ windows application . i found old facebook project that i dont know how much good it is or how to use it in windows app if any . is there any way to embed php in a Windows application? A: PHP isn't an executable it is a lib. php-cli, php-cgi, mod_php etc are just interfaces for the same library. You can embed the lib into your own application as well (desktop apps, network tools, etc) but its a pain because of PHP's threading issues. This isn't just an issue when trying to thread PHP, but the lib will crash or can cause undefined behavior when other parts of your app try to thread around it. However, it can be done. I've done a few projects embedding PHP, and the only one that couldn't overcome the threading related issues was when trying to mate the PHP core within a JNI project. Here's a blurb from a project where I embedded the PHP core into an SMTP server. It was able to access all of wordpress's codebase without any modifications (such as includes within wp-includes) allowing the AUTH command to authorize using wordpress. It would also deliver emails directly as blog entries based on email subject (if the user was logged on as admin via SMTP), and responses were added as comments to the post. This wasn't a hack or workaround, the SMTP service used the same codebase, configuration, and database as the HTTP service. case 11: // AUTH zval **z_auth_ret_code; zend_hash_index_find(Z_ARRVAL_P(ret_array), 2, (void**)&z_auth_ret_code); if(Z_TYPE_PP(z_auth_ret_code) == IS_LONG) { if(Z_LVAL_PP(z_auth_ret_code) == 334) { // is OK // GET AUTH TYPE zval **z_auth_type_code; zend_hash_index_find(Z_ARRVAL_P(ret_array), 3, (void**)&z_auth_type_code); if(Z_LVAL_PP(z_auth_type_code) == 3) { // AUTH LOGIN send_to_socket(client_socket, "334 AUTH LOGIN ready. Please send UID\r\n"); char *uid_input = NULL; int uid_input_len = 0; if(read_from_socket(client_socket, &uid_input, &uid_input_len, (char*)"\r\n") > 0) { ZVAL_STRING(user_name, uid_input, 1); send_to_socket(client_socket, "334 Please send password for UID\r\n"); } char *pwd_input = NULL; int pwd_input_len = 0; if(read_from_socket(client_socket, &pwd_input, &pwd_input_len, (char*)"\r\n") > 0) { ZVAL_STRING(user_pass, pwd_input, 1); } // setup session zval *function, *retval; zval *params[2]; MAKE_STD_ZVAL(function); MAKE_STD_ZVAL(retval); ZVAL_STRING(function, "open_session", 1); params[0] = user_name; call_user_function(EG(function_table), NULL, function, retval, 1, params); // do auth ZVAL_STRING(function, "smtp_auth", 1); params[0] = user_name; params[1] = user_pass; call_user_function(EG(function_table), NULL, function, retval, 2, params TSRMLS_CC); if(Z_TYPE_P(retval) == IS_LONG && Z_LVAL_P(retval) == 1) { send_to_socket(client_socket, "235 AUTH LOGIN SUCCESSFUL\r\n"); is_authorized = 1; }else { send_to_socket(client_socket, "535 AUTH LOGIN FAILED\r\n"); } } } } break;
{ "pile_set_name": "StackExchange" }
Q: Identify when multiple domains are provided using regular expression I am working on a C# form where a user provides FQDNs of two hosts and this information is later used to install some features that are only valid if the two FQDNs are on the same domain. I initially had the two hostnames and single domain name in separate fields, but it was confusing to users. Basically, I want to detect when different domains are provided in these FQDN fields. For example- Valid input: host1.domain1.example host2.domain1.example Invalid input: host1.domain1.example host2.domain2.example I want to detect the invalid input, but it's trickier than I thought it would be. A: Following Regex would help. It fulfills your current text reqt. You can make minor changes if you think your text will have. Let me know if you have any question. On the example page, on the right, it has a description of what code is doing, so refer to that explanation. Regex: (?:\w+)\.(\w+)(?:\.\w+)*\n(?:\w+)\.(?:\1)(?:\.\w+)* Example: https://regex101.com/r/ZDG4Ba/4
{ "pile_set_name": "StackExchange" }
Q: function warnings C: "warning: type of ‘char_array’ defaults to ‘int’" #include <stdio.h> #include <string.h> int myprint(char_array){ char mystring[80]; strcat(mystring, "\n"); printf("%s", mystring); return 0; } int main(int argc, char** argv){ int count = 5; char letter = 'c'; printf("decimal: %d, char: %c\n", count, letter); myprint("sup"); return 0; } I get warnings on compile: cchilders:~/projects/buildyourownlisp_in_C/ch3 [master]$ compile basics.c basics basics.c: In function ‘myprint’: basics.c:4:5: warning: type of ‘char_array’ defaults to ‘int’ int myprint(char_array){ ^ It compiles, but my myprint function doesn't work: cchilders:~/projects/buildyourownlisp_in_C/ch3 [master]$ ./basics decimal: 5, char: c I see this answer warning: return type defaults to ‘int’ [-Wreturn-type] but doesn't apply to me since I did declare int main(...) I also see this declaration of functions: return_type function_name( parameter list ) { body of the function } And for myprint I declare as taking int and return 0. What does this warning mean and why doesn't my function work? Thank you ANSWER: void myprint(char mystring[]){ strcat(mystring, "\n"); printf("%s", mystring); } quiets the warnings, but causes Segmentation fault (core dumped) Changing to void myprint(char[] mystring){ strcat(mystring, "\n"); printf("%s", mystring); } makes it worse: cchilders:~/projects/buildyourownlisp_in_C/ch3 [master]$ cc -std=c99 -Wall basics.c -o basics basics.c:4:21: error: expected ‘;’, ‘,’ or ‘)’ before ‘mystring’ void myprint(char[] mystring;){ ^ basics.c: In function ‘main’: basics.c:15:5: warning: implicit declaration of function ‘myprint’ [-Wimplicit-function-declaration] myprint("sup"); ^ I also tried void myprint(char[] mystring;){... and void myprint(char[] mystring,){... A: You are not providing a data type for char_array in int myprint(char_array) You need char * or whatever you want it to be. A: Firstly, function definitions should be like return-type function-name ( parameter-type parameter-name, parameter-type parameter-name) { ... } You did not specify either a parameter type or a parameter name. If you mean char_array to mean a type, you need to define it first, using a typedef or a struct or something else. If you mean char_array to be a parameter name, you need to specify its type, as char[] char_array say. Also, in this case, you do not actually use the variable char array anywhere in the function myprint. So the argument "sup" is not being used at all. After edit to the question: Try char str[] = "sup"; myprint(str); instead. As far as I know, you can't pass a string (a character array) by value. A: As others have pointed out, you didn't specify a type for char_array, so it is assumed to be int. Changing it to char char_array[] fixes this. Your other problem is that you're passing a string constant ("sup") to this function and are then attempting to modify it. String constants are stored in a read-only section of memory, so you can't modify it. Given that you're only printing the string with a newline, you can do this instead: void myprint(char mystring[]){ printf("%s\n", mystring); }
{ "pile_set_name": "StackExchange" }
Q: htaccess - redirect user from index.php to another file if url is more than root I have a need where I have 2 files located within the same directory index.php and room.php What I want to be able to do it if a user goes to www.example.com it will direct them to index.php If a user types in the url www.example.com/whateverelse/ it will redirect them to room.php Also I would like to capture the extra part of the URL into a variable for instance whateverelse Is this even possible? A: Yes it is very much possible. Use this code in your root .htaccess: # load index.php by default DirectoryIndex index.php RewriteEngine On RewriteBase / # remove trailing slash RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)/$ /$1 [NE,R=301,L] # for all other requests load room.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^((?!(index|room)\.php).+)$ room.php [L,NC]
{ "pile_set_name": "StackExchange" }
Q: MySQL Workbench won't allow me to create foreign keys I'm trying to create a few tables and one of them has should have foreign keys referencing the other tables, but MySQL Workbench keeps giving me "Error Code: 1215. Cannot add foreign key constraint". This happens if I try to create them during the table creation and if I just create the table and then try to add FK through ALTER. I just can't figure out the problem. I've tried both with and without ENGINE = InnoDB that I saw some people suggest on the web. And yes, tables kommune and person has been created. CREATE TABLE kommune ( Kommunenr varchar(4) NOT NULL, Kommunenavn varchar(45) NOT NULL, PRIMARY KEY (Kommunenr)); CREATE TABLE person ( PersonID varchar(4) NOT NULL, Fornavn varchar(45) NOT NULL, Etternavn varchar(45) NOT NULL, Postnr varchar(4) NOT NULL, Poststed varchar(45) NOT NULL, PRIMARY KEY (PersonID)); CREATE TABLE oppdrag ( Oppdragsnr varchar(5) NOT NULL, Eiendomnr varchar(4) NOT NULL, Gateadresse varchar(45) NOT NULL, Postnr varchar(4) NOT NULL, Poststed varchar(45) NOT NULL, Kommunenr varchar(4) NOT NULL, Prisantydning varchar(10) NOT NULL, Solgt boolean NOT NULL, PRIMARY KEY (Oppdragsnr), FOREIGN KEY (Postnr) REFERENCES person(Postnr), FOREIGN KEY (Poststed) REFERENCES person(Poststed), FOREIGN KEY (Kommunenr) REFERENCES kommune(Kommunenr)); A: Check the following lines: FOREIGN KEY (Postnr) REFERENCES person(Postnr), FOREIGN KEY (Poststed) REFERENCES person(Poststed), but in your table structure: CREATE TABLE person ( PersonID varchar(4) NOT NULL, Fornavn varchar(45) NOT NULL, Etternavn varchar(45) NOT NULL, Postnr varchar(4) NOT NULL, Poststed varchar(45) NOT NULL, PRIMARY KEY (PersonID)); Postnr, Poststed are neither unique or not primary key. To make foreign key, the referring column in the base table must be an indexed column
{ "pile_set_name": "StackExchange" }
Q: The Great Retagging Event - Episode 1: The one-taggers                 TRE will be held at $\ldots$? Famous final words The Retagging Event (TRE) What good is in working so much on cleaning tags if they're not applied to questions? I thought, we should do something extraordinary. Oh no Rationale Editing questions bumps them up; and somehow surprisingly, there's a good portion of chem.SE users who only use the 'active' tab. Thus, bumping too many questions would stop newer questions from getting the needed attention. Thus, the frequency of retagging must be small. But people just can't keep up with editing 1 question every ten minutes. They can't be consistent, and they're not to blame. Hence, if the only way we can keep editors helping is by flushing down the 'active' tab, let's do it in an organized way, in a small frequency. What we do at TRE Simply put, in an effort to coordinate chat and meta activity more, we now will have a chat event, preferably at 15:30 UTC which lasts for 90 minutes and happens every Friday in which we hunt and then retag a bunch of questions. (Friday is my holiday and the last weekday where you live, so it would be optimal) What we do at episode 1 We'll hunt and retag questions with only one tag. One possibly broad tag. They are candidate number one for a poorly tagged question, and our werewolf hunter gun will be this query. What are tags good for anyway? This question has been brought up and asked many many times, and the usefulness of tags has been proven. Trust me. If you don't trust me, I can prove their use to you, but not here, in chat or somewhere else. Please. What else? I'll try to make sure it's fun enough to keep y'all interested, and you can bring some snacks. (Though we're not responsible for damages done to keyboards) Please let me know what you think in the answers: How can we improve user experience in this event? What time do you suggest the event to be? A: TRE stats: Episode 1 — scene 1 (Friday 2015/10/02, 15:30 - 17:00 UTC): 187 edits No more nonclosed questions with only the homework tag. 120 questions tagged only with organic-chemistry were retagged. 8 people participated 88 edit reviews Here's the chat log for the whole event. Episode 1 — scene 2 (Friday 2015/10/09, 15:35 - 17:05 UTC): 115 edits Less than 76 posts left with only the organic-chemistry tag. 6 users participated 93 edits reviews Here's the chat log for the whole event. $\color{#006600}{\text{Note}}$: People were very busy, so the TRE will be held one hour later. Episode 1 — scene 3 (Friday 2015/10/16, scheduled 16:30 - 18:00 UTC) 129 edits No posts left with organic-chemistry as their only tag amines was applied to all the questions it should've been 6 users participated 52 edit reviews (We got @Ortho to 2k; yay!) Here's the chat log for the whole event. Episode 1 — scene 4 (Friday 2015/10/23, scheduled 16:27 - 18:16 UTC) 103 edits No posts left with physical-chemistry as their only tag 7 users participated 53 edit reviews and a couple of closed questions . . . Here's the chat log for the whole event. Episode 1 — scene 5 (Friday 2015/10/30, scheduled 16:32 - 18:07 UTC) $\approx$180 edits No posts left with everyday-chemistry as their only tag. No posts left with reaction as their only tag. No posts left with quantum-chemistry as their only tag. Refined the queue from the newly added or remaining homework-only questions. 7 users participated (and 3 users reviewed the edits without participating in the event itself) $\approx$130 edit reviews $\rm\color{red}{WOW!}$ This TRE was awesome. Here's the chat log for the whole event. Episode 1 — scene 6 $\color{#006600}{\text{Note}}$: This is the end of episode one. However, the love for teh retagz doesn't end$\,\ldots$ $\color{red}{\text{To be continued}\ldots}$ A: TRE notes and tips Don't edit closed questions! (This is covered with my query, but just in case) The rationale, if you ask, is an SE slogan saying "$\color{red}{\mathcal{don't~polish~turds}}$". Enough said I guess. Don't edit questions that you voted to close/flagged for closure. For the same reason I stated above. Please make substantial edits. Think of it like this: You are gonna edit tags, but are going to try very hard to edit other stuff as well. These are the tags that need to applied to more questions: smell, esters, amines. These are tags that possibly need to be applied to more questions: carbonyl-compounds, equipment. These are the tags that possibly need to be removed and be replaced with better ones: homework, water, periodic-table, everyday-chemistry. Here's how TRE will be done: I'll give the people that participate a query, or a search link. Then they'll flip a table, because that's the custom. Like this: (/¯◡ ‿ ◡)/¯ ~ ┻━┻ Then they'll give me a number: "I'll retag 30 questions", for instance. I'll tell them: Pick the first thirty questions! You should edit from this question: <a link> to this one: <a link> They'll start editing from the second question to the second question from the last. They'll finish editing by editing out those "milestone" questions. Start again from 1. $\color{red}{\text{Important tip:}}$ Please open the links to the questions you want to edit in a new tab. If you open the link in the same tab and use the 'back' button, your results wouldn't be the same as the list and finding which questions you should've edited becomes hard. A: A useful tool for finding questions that should be, but are not, tagged with a particular tag is the excluding search parameter -[tag]. Just add this parameter to some search terms that are likely to identify questions of the relevant tag. For example, searching for kinetics -[kinetics] is:question or rate -[kinetics] is:question can find potential candidates for the kinetics tag. (Usually, it is advisable to sort the results by relevance.) Some questions are very short and might not contain the words that you are looking for. However, the corresponding answers might be longer and might contain the relevant search terms. Therefore, it may be worth a try to include the answers: kinetics -[kinetics] or rate -[kinetics]
{ "pile_set_name": "StackExchange" }
Q: Oracle to_char subquery in Trigger I have a table (Meeting) with date type attribute (MeetDate) and another varchar2 type attribute (WorkWeek). I'm trying to do an After trigger to fill in the WorkWeek field based on the MeetDate value using the to_char function. Tried the following codes separately and they compile without errors but when I try to insert a row with Null for WorkWeek, it gives me a 'mutating trigger/function may not see it' error. What am I doing wrong here? thanks in advance to any help. --Code 1 Create or Replace Trigger Update_WorkWeek After Insert On Meeting For Each Row Begin Update Meeting Set WorkWeek = (Select to_char(:new.MeetDate, 'YYYY IW') From Dual) Where MeetID = :new.MeetID; End; / show Errors; --Code 2 Create or Replace Trigger Update_WorkWeek After Insert On Meeting For Each Row Begin if :New.WorkWeek is Null then Update Meeting Set WorkWeek = (Select to_char(:new.MeetDate, 'YYYY IW') From Dual) Where MeetID = :new.MeetID; End if; End; / show Errors; A: You just want a trigger to change the value of a column before it gets inserted - and it's on the same row, so you don't need an UPDATE: Create or Replace Trigger Update_WorkWeek BEFORE Insert On Meeting For Each Row Begin :new.WorkWeek := to_char(:new.MeetDate, 'YYYY IW'); End; / show Errors; You might want the column kept up-to-date if the MeetDate is changed, i.e.: Create or Replace Trigger Update_WorkWeek BEFORE Insert OR Update OF MeetDate On Meeting For Each Row Begin :new.WorkWeek := to_char(:new.MeetDate, 'YYYY IW'); End; / show Errors;
{ "pile_set_name": "StackExchange" }
Q: Permission to see Campaigns in Activity search criteria When I (admin) go to Search > Find Activities, the criteria includes a selector for Campaigns. Authenticated users, however, do not get that option. See the snippet below from such a user, in my criteria the Campaigns selector is right below the Location box. Likely means they're missing a permission (Drupal 7.69, Civi 5.21.0), but don't know which. There are a number of permissions associated w. CiviCampaign and I'd rather not open all of them because our use case is very narrow. Any guidance on which permission to grant, if that's what the issue is, appreciated. A: This is related to this bug 'CiviCampaign: access CiviCampaign' permission missing. Unfortunately at this time, in order to get Campaigns search showing in Search -> Find Activities, you have to grant permission to administer CiviCampaign. Depending on your user base (trust and size) and how bad you need this working now, you could give administer CiviCampaign and then change the menu permission for the Campaigns top nav menu item to administer CiviCRM. They would only be able to get to those menu links if they knew the URL directly (unlikely).
{ "pile_set_name": "StackExchange" }
Q: Querying values from a Google Sheets I have a table of foods with their nutritional values in a Google Sheets. My objective is to enter portions consumed of each food in a given day and calculate nutritional intake for the day. For each row that has a portion entered, I want to summarize the nutritional values times the number of portions served. I've given a very simplified version below. Can anyone tell me how to go about doing this in Google Sheets? PORTIONS FOOD CALORIES FAT PROTEIN 1 beef 250 34 25 chicken 220 22 13 carrots 20 12 23 2 beans 40 25 5 -------------------------------------------- TOTALS 330 84 35 A: In C6 place: =sumproduct($A2:$A5,C2:C5) Then copy across to D6 and E6
{ "pile_set_name": "StackExchange" }
Q: How to compute performance of a CPU in FLOPS? For a computer that took a variable number of clock cycles to execute floating point instructions, what would be the formula to estimate its performance in FLOPS assuming that it can execute either A add instructions, or M multiply instructions, or D divide instructions per second in average? Is it reasonable to use just the value of M, as was done in the first line of the table, using "About 2400 IBM 7030 Stretch supercomputers [...] IBM 7030 Stretch performs one floating-point multiply every 2.4 microseconds." to represent the performance of 1 GFLOPS, or were there better formulas? Also, converting from Whetstones to FLOPS appears unreliable. The ratio of MWIPS to MFLOPS in this table varies substantially even for the same family of processors. I don't care that In the past, FLOPS was considered a marketing term and thus subject to rather over-optimistic reporting, as mentioned in an answer below. I'm asking how it was computed. A: The TOP500 project uses the Linpack Benchmark to determine FLOPS ratings. In the past, FLOPS was considered a marketing term and thus subject to rather over-optimistic reporting. A: According to Roy Longbottom (pers. comm.), the proper way to calculate the real-life number of MFLOPS is to run the Whetstone benchmark and to take the geometric mean of the three floating point results in Millions of Floating Point Operations Per Second. My mistake was using an outdated version of the benchmark. For example, according to my experiments with simulated CU/ALU pipes of the BESM-6, this would come out to about 30% less than the geometric mean of A, M, and D, and 40% less than just M. For the curious, here's how the BESM-6 results look like: WHETSTONE BENCHMARK FOR 100.00 SECONDS DURATION 8 PASSES USED (X 100) FORTRAN WHETSTONE BENCHMARK - SINGLE PRECISION Month run 7/2017 Supplier/model IPMCE, USSR CPU chip type BESM-6 Clock MHz 9 Cache size 16 words Chipset/options CU/ALU pipes emulated using interlocks and ave. timings from the manual OS/DOS DISPAK (user mode emulated) Compiler F O R E X ИПM AH CCCP 4.12 OT 25.06.85 Options default LOOP CONTENT RESULT MFLOPS MOPS SECONDS N1 FLOATING POINT -1.12398256285086973 0.524 0.293 N2 FLOATING POINT -1.12187081181764370 0.402 2.674 N3 IF THEN ELSE 1.00000000000000000 0.185 4.477 N4 FIXED POINT 12.00000000000000000 0.346 7.280 N5 SIN,COS ETC. 0.49902906717352380 0.036 18.361 N6 FLOATING POINT 0.99999958804255584 0.121 35.720 N7 ASSIGNMENTS 3.00000000000000000 0.106 13.963 N8 EXP,SQRT ETC. 0.75100162294984329 0.018 16.087 MWIPS 0.809 98.856 MFLOPS per the benchmark come out to 0.295; the theoretical max numbers are A=0.820, M=0.500, and D = 0.180, based on the CPU manual; their geometric mean is 0.418.
{ "pile_set_name": "StackExchange" }
Q: programmatically deploy to site collection level using c# I would like to use c# to remotely deploy my sharepoint site collections and sites, I can easily write the code to perform most operations. However I can't seem to find a way of deploying the code to sitecollection level rather than farm level. Leaving my laptop at work I don't have the exact code but it goes like this so far -> Create sitecollection add a sitecollection (http://server/managed-wildcard-path/sitecollection-name to it open up the solution DeployLocal to sitecollection. The solution is found and DeployLocal runs without errors, however the solution isn't deployed not even on the route. Does anyone know how to go about this? If I have the right idea but possibly the wrong idea of how it works, please also inform me. [update] Here is the code: try { // Attempt to add the solution to the solution store SPSolution solution = new SPSolution(); solution = SPFarm.Local.Solutions.Add(wspUrl); } catch (Exception ex) { OutPutMessage("--------------------\r\n" + wspUrl + ": This solution already exists in the solution store"); } finally { // Create a new sitecollection collection and add the target site too it Collection<SPWebApplication> webapps = new Collection<SPWebApplication>(); SPWebApplication webapp = SPWebApplication.Lookup(new Uri(siteUrl)); webapps.Add(webapp); // Open the target wsp SPSolution solutionToDeploy = new SPSolution(); txtConsole.Text += "Solution name: \"" + SPFarm.Local.Solutions[strSolutionName].DisplayName + "\"\r\n"; solutionToDeploy = SPFarm.Local.Solutions[strSolutionName]; // and deploy solutionToDeploy.DeployLocal(true, webapps, true); OutPutMessage("----------------\r\nSolution Deployed\r\n----------------"; } A: I believe that this line: SPFarm.Local.Solutions.Add(wspUrl); is actually trying to add the solution to the farm. You want to add it the SPSite's solution gallery, and a think your use of DeployLocal is an error - I think it's for the actual deployment of the files. If site is your site collection try: SPSite site = ... SPFile sourceSolutionFile = ... //Get the Solution Gallery for the SPSite SPDocumentLibrary solutionGallery = (SPDocumentLibrary)site.GetCatalog(SPListTemplateType.SolutionCatalog); //Add the WSP File. I've used a source that is an SPFile, but really it's a string and byte array SPFile solutionFile = solutionGallery.RootFolder.Files.Add(sourceSolutionFile.File.Name, sourceSolutionFile.File.OpenBinary()); // Activate Solution SPUserSolution newUserSolution = newSite.Solutions.Add(solutionFile.Item.ID); Certainly, that works for deploying Site Templates into the solution gallery by code for me. A: It appears that this method only works on Sandbox solutions. So I went back to basics and ran STSADM from inside a form application that also had the other functionality to set up the site collections built in. So in a similar fashion to wait_pid() in c++ I looked it up for c# and used the solution presented here: https://stackoverflow.com/questions/611094/async-process-start-and-wait-for-it-to-finish then read the output using a similar method to the one found here https://stackoverflow.com/questions/6597800/capture-output-of-process-synchronously-i-e-when-it-happens, then checking the Gallery to see if it was in correctly, then deployed etc etc, basically following the exact method from the output in visual studio. Not a perfect solution but it will do for now, if anyone has any ideas please feel free to shout.
{ "pile_set_name": "StackExchange" }
Q: Display:none for video element, will it still be buffered? I have a website with a video playing below the header on the front page, the video is pretty large and I am using media queries to remove it from the mobile browsers etc. It displays fine, just as I want. But I wonder, if I simply set it to display:none, will it still be buffered in the background? So phone users will have a slower load time for no reason at all? How should I do it instead, if that's the case? I searched for this question and I only found one remotely related. But there, the question was if the code would be loaded or not. And I can live with loading an extra line of HTML. So that's not the issue. A: To be on the safe side, I would first write a general CSS rule for the video container that has display: none in it, and then add a rule inside a media query (@media screen and (min-width: 768px) {...}) for screens above 768px (or whatever your breakpont is) that contains display: block. That would be a mobile-first approach that makes sure it's not loaded on smaller screens.
{ "pile_set_name": "StackExchange" }
Q: ngClass Not working on activating class with click? I am trying to show activated class as active but It's not working It goes to that class for half a sec and comes back, I have tried something like this. <ion-row > <ion-col col-3 (click)="deviceType('Light')" ><div class="circle-text " [ngClass]="{'active-class': (selectedItem == 'Light')}"><div class="circle-inside"><ion-icon name="custom-icon-lights"></ion-icon></div></div><div class="circle-head-txt">Lights</div></ion-col> <ion-col col-3 (click)="deviceType('Ac')"><div class="circle-text" [ngClass]="{'active-class': (selectedItem == 'Ac')}"><div class="circle-inside"><ion-icon name="custom-icon-ac"></ion-icon></div></div><div class="circle-head-txt">AC</div></ion-col> <ion-col col-3 (click)="deviceType('Sensor')"><div class="circle-text" [ngClass]="{'active-class': (selectedItem == 'Sensor')}"><div class="circle-inside"><ion-icon name="custom-icon-humidity"></ion-icon></div></div><div class="circle-head-txt">Sensors</div></ion-col> <ion-col col-3 (click)="deviceType('Camera')"><div class="circle-text" [ngClass]="{'active-class': (selectedItem == 'Camera')}"><div class="circle-inside"><ion-icon name="custom-icon-camera"></ion-icon></div></div><div class="circle-head-txt">Camera</div></ion-col> </ion-row> this is My .ts file I am setting selectedItem by default to Light deviceType(type: string) { this.selectedItem = type; if(type == "Light"){ this.navCtrl.setRoot(LightPage); }else if(type == "Sensor"){ this.navCtrl.setRoot(SensorsPage); } else if(type == "Camera"){ this.navCtrl.setRoot(CameraPage); }else if(type == "Ac"){ this.navCtrl.setRoot(AcPage); }else if(type == "Rgb"){ this.navCtrl.setRoot(RbglightPage); }else if(type == "Fan"){ this.navCtrl.setRoot(FanPage); }else if(type == "Curtain"){ this.navCtrl.setRoot(CurtainPage); } else { this.deviceTypeChild.emit(type); } } this is scss file .active-class:after { background: #dbdff1!important; } A: Try to do another way [class.active-class]="selectedItem == 'Light'"
{ "pile_set_name": "StackExchange" }
Q: Rails Images issue I have something like this in my rails app: <a class="fancybox" rel="gallery1" href="gal5.jpg" title="something"> <img hspace="12" src="images/gal5thumb.jpg" alt="Something" /> </a> I have my images saved in /assets/images. For some reason this doesn't work but when I save the images on some website like cloudinary and then use the url everything works perfectly. Can someone please point out what I am doing wrong? I am using rails 5 on Ubuntu. Thanks. A: => If you place images in your app/assets/images directory, then you should be able to call the image directly with no prefix in the path. ie. image_url('logo.png') or asset_url('gal5thumb.jpg') <a class="fancybox" rel="gallery1" href="gal5.jpg" title="something"> <img hspace="12" src="/assets/gal5thumb.jpg" alt="Something" /> </a> Or <a class="fancybox" rel="gallery1" href="gal5.jpg" title="something"> <img hspace="12" src="<%=asset_path('gal5thumb.jpg')%>" alt="Something" /> </a> Or => If you are using it inline in the view, then you will need to use the built in image_tag helper in rails to output your image. without prefixing <%= image_tag "gal5thumb.jpg", alt: "something", hspace: "12" %>
{ "pile_set_name": "StackExchange" }
Q: How to get the event target in my case? I am using Jquery ui to do the drag and drop. I want to do something on the draggable item after I drop it. I have something like this.. $('#drag-me').draggable({ scroll:false, cursor:'pointer', revert: 'invalid' }); $('.box').droppable({ drop:function(event, ui){ //I want to append the #drag-me element to the .box. How do I do that? //event.target -> get .box not #drag-me $(this).appendTo(event.target) } }) Thanks for the help! A: You're looking for ui.draggable, as per the droppable API drop event docs: http://api.jqueryui.com/droppable/#event-drop So you would do: $('.box').droppable({ drop:function(event, ui){ $(this).appendTo(ui.draggable) } });
{ "pile_set_name": "StackExchange" }
Q: How login in a website in python Im trying to scrap this site using this example code: https://github.com/kazuar/login_scraper_example/blob/master/login_scraper_example.py But always print the login page and return 200 http code, what is wrong? import requests from lxml import html USERNAME = "my_mail" PASSWORD = "my_pwd" LOGIN_URL = "http://www.empaquetador.cl" URL = "http://www.empaquetador.cl/dashboard/turnos-historial?fecha=2017-12-01" # this a available url after login success def main(): session_requests = requests.session() # Get login csrf token result = session_requests.get(LOGIN_URL) tree = html.fromstring(result.text) # Create payload payload = { "nombre": USERNAME, "contrasena": PASSWORD } # Perform login result = session_requests.post(LOGIN_URL, data = payload, headers = dict(referer = LOGIN_URL)) # Scrape url result = session_requests.get(URL, headers = dict(referer = URL)) tree = html.fromstring(result.content) bucket_names = tree.xpath("//div[@class='tbl-generales table-nohover table table-bordered']/a/text()") print(bucket_names) if __name__ == '__main__': main() A: The login form has action set to /login/index/process <form id="login" name="login" class="form-horizontal" enctype="application/x-www-form-urlencoded" action="/login/index/process" method="post" accept-charset="UTF-8"> You need to set LOGIN_URL to the same in order to post the form to the correct URL: LOGIN_URL = "http://www.empaquetador.cl/login/index/process"
{ "pile_set_name": "StackExchange" }
Q: What's that best way to move through directories? Are both of the examples below OK, or is the second one bad style? Case 1: Stay in top directory and use catdir to access subdirectories #!/usr/bin/env perl use warnings; use strict; my $dir = 'my_dir_with_subdir'; my ( $count, $dh ); use File::Spec::Functions; $count = 0; opendir $dh, $dir or die $!; while ( defined( my $file = readdir $dh ) ) { next if $file =~ /^\.{1,2}$/; my $sub_dir = catdir $dir, $file; if ( -d $sub_dir ) { opendir my $dh, $sub_dir or die $!; while ( defined( my $file = readdir $dh ) ) { next if $file =~ /^\.{1,2}$/; $count++; } closedir $dh or die $!; } else { $count++; } } closedir $dh or die $!; print "$count\n"; Case 2: Change to subdirectories and restore top directory before exit use Cwd; my $old = cwd; $count = 0; opendir $dh, $dir or die $!; chdir $dir or die $!; while ( defined( my $file = readdir $dh ) ) { next if $file =~ /^\.{1,2}$/; if ( -d $file ) { opendir my $dh, $file or die $!; chdir $file or die $!; while ( defined( my $file = readdir $dh ) ) { next if $file =~ /^\.{1,2}$/; $count++; } closedir $dh or die $!; chdir $dir; } else { $count++; } } closedir $dh or die $!; chdir $old or die $!; print "$count\n"; A: For your example, it's best to change to subdirectories, and don't bother changing back to the original directory at the end. That's because each process has its own "current directory", so the fact that your perl script is changing it's own current directory does not mean that the shell's current directory is changed; that stays unaltered. If this was part of a larger script it would be different; my general preference then would be not to change directory, just to reduce confusion over what the current directory is at any point in the script.
{ "pile_set_name": "StackExchange" }
Q: What does the code $('body').on('hidden.bs.modal', '.modal', function (){....} do and when does it gets called? I've following HTML to show the bootstrap modal dialog: <div class="panel-body" data-toggle="modal" href="ajax_event_detail.php?event_id=512" data-target="#myModal-event" style="cursor: pointer;"></div> Bootstrap modal dialog code is as below : <div id="myModal-event" class="modal fade" role="dialog"> <!-- <div role="document" class="modal-dialog"> --> <div role="document" style="width:600px;position:relative;margin:auto;margin-top:10px;"> <div class="modal-content" style="border:0;"> <!-- <button aria-label="Close" data-dismiss="modal" class="close" type="button"><span aria-hidden="true"> x </span></button> --> <div class="modal-header"> <h4 id="myModalLabel" class="modal-title">Event Details</h4> </div> <div class="modal-body"> Loading... </div> <div class="modal-footer"> <button data-dismiss="modal" class="btn btn-default" type="button">Close</button> </div> </div> <!-- /.modal-content --> </div> </div> and another code as follows : <div class="modal-content"> <!-- <button aria-label="Close" data-dismiss="modal" class="close" type="button"><span aria-hidden="true">×</span></button> --> <div class="modal-header"> <h4 id="myModalLabel" class="modal-title">Event Details</h4> </div> <div class="modal-body"> <div class="row"> <div class="col-sm-6 col-md-6 col-sm-12"> <div class="event-title"> {$eventDetails.event_details.title} <input type="hidden" name="hid_event_id" id="hid_event_id" value="{$eventDetails.event_details.event_id}"> </div> <ul> <li><img src="{$user_img_url}/time.png" alt=""> {$eventDetails.event_details.start_time_phrase_stamp}</li> <li><img src="{$user_img_url}/calender.png" alt=""> {$eventDetails.event_details.start_time_phrase}</li> {if $eventDetails.event_details.location} <li> <a href="javascript:void(0)" onClick="viewLocationOnMap();"> <img src="{$user_img_url}/location.png" alt=""></a> <a href="javascript:void(0)" onClick="viewLocationOnMap();">{$eventDetails.event_details.location}</a> </li> {/if} {if $eventDetails.event_details.group_name} <li><img src="{$user_img_url}/group_event.png" alt="">Group: {$eventDetails.event_details.group_name}</li> {/if} <li><button type="button" class="btn btn-info" data-toggle="popover">Edit Event</button></li> </ul> <ul id="popover-content" class="list-group" style="display: none"> <a data-toggle="modal" href="ajax_event_detail.php?event_id={$eventDetails.event_details.event_id}" data-target="#myModal-edit-event" style="cursor: pointer;" class="list-group-item">Edit Event</a> <a href="#" class="list-group-item">Invite Members</a> <a href="#" class="list-group-item">Delete Event</a> </ul> </div> <div class="col-sm-6 col-md-6 col-sm-12"> <div class="form-group" align="right"> <select name="user_event_responce" id="user_event_responce" class="form-control" style="width:150px;" > <option value="0">I am..</option> <option value="1" {if $myEventGoingStatus eq 'attending_user'} selected="selected" {/if} >Going</option> <option value="2" {if $myEventGoingStatus eq 'mayBeAttending_user'} selected="selected" {/if} >Maybe</option> <option value="3" {if $myEventGoingStatus eq 'notComing_user'} selected="selected" {/if}>Not Going</option> </select> </div> <!-- <div class="form-group" align="right"> <select name="event_actions" id="event_actions" class="form-control" style="width:150px;"> <option value=""></option> <option value="edit_event">Edit Event</option> <option value="invite_members">Invite members</option> <option value="delete_event">Delete event</option> </select> </div> --> </div> </div> <hr> <div class="row"> <div class="event-menu"> <ul class="nav nav-tabs" id="myTab"> <li><a href="#description" data-toggle="tab">Description</a></li> <li><a href="#feeds" data-toggle="tab">Feeds</a></li> <li><a href="#going" data-toggle="tab">Going</a></li> <li><a href="#maybe" data-toggle="tab">Maybe</a></li> <li><a href="#notgoing" data-toggle="tab">Not Going</a></li> </ul> </div> </div> <hr> <div class="tab-content"> <div class="tab-pane active" id="description"> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> {$eventDetails.event_details.description} </div> </div> </div> <div class="tab-pane" id="feeds"> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> Work In Progress </div> </div> </div> <div class="tab-pane" id="going"> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> {foreach from=$eventDetails.attending_user item=eachUser key=key} <div class="col-md-2 col-sm-2 col-xs-12 no-padding"> <div class="block"> <img src="{$eachUser.profile_image}" class="img-event" alt=""> <span class="author">{if $eachUser.full_name neq ''}{$eachUser.full_name}{else}{$eachUser.user_name}{/if}</span> <span class="degree">{$eachUser.group_name}</span> </div> </div> {/foreach} </div> </div> </div> <div class="tab-pane" id="maybe"> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> {foreach from=$eventDetails.mayBeAttending_user item=eachUser key=key} <div class="col-md-2 col-sm-2 col-xs-12 no-padding"> <div class="block"> <img src="{$eachUser.profile_image}" class="img-event" alt=""> <span class="author">{if $eachUser.full_name neq ''}{$eachUser.full_name}{else}{$eachUser.user_name}{/if}</span> <span class="degree">{$eachUser.group_name}</span> </div> </div> {/foreach} </div> </div> </div> <div class="tab-pane" id="notgoing"> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> {foreach from=$eventDetails.notComing_user item=eachUser key=key} <div class="col-md-2 col-sm-2 col-xs-12 no-padding"> <div class="block"> <img src="{$eachUser.profile_image}" class="img-event" alt=""> <span class="author">{if $eachUser.full_name neq ''}{$eachUser.full_name}{else}{$eachUser.user_name}{/if}</span> <span class="degree">{$eachUser.group_name}</span> </div> </div> {/foreach} </div> </div> </div> </div> </div> <div class="modal-footer"> <button data-dismiss="modal" class="btn btn-default" type="button">Close</button> </div> </div> Now what's happening in my code is when user clicks on above <div class="panel-body" data-toggle="modal" href="ajax_event_detail.php?event_id=512" data-target="#myModal-event" style="cursor: pointer;"></div> The first part of code opens up, then the data fetch is going on then suddenly the second part of code i.e. the data fetched gets added to the modal. I'm not understanding how this is happening. The jQuery which is doing this is as follows but I didn't understand what it is doing when that hide event is being called etc. etc. Please clear my doubts by making me understand below code. $('body').on('hidden.bs.modal', '.modal', function () { console.log('Hi *'); $("#myModal-event .modal-body").html(' Loading... '); $(this).removeData('bs.modal'); }); Thanks. A: This executes when the .modal (modal window) gets closed. So, whenever you open a modal window with the class modal (obviously), at some point it gets closed. When that modal window gets hidden (or closed) the event hidden.bs.modal gets triggered and the function gets executed. This is not managed by the user (you didn't write explicit code) but the Bootstrap library has it built in. From the Bootstrap Documentation: hidden.bs.modal: This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete). Sample Code: $('#myModal').on('hidden.bs.modal', function (e) { // do something when this modal window is closed... }); To answer the queries in the comments, you have: $("#myModal-event .modal-body").html(' Loading... '); sets the content of the modal window to be Loading.... $(this).removeData('bs.modal'); - This tells Bootstrap to clear everything on the close of the modal window, so you won't get cached content. See more at Clear Bootstrap Modal content after close.
{ "pile_set_name": "StackExchange" }
Q: Magnetic Flux conservation My teacher said that after switch is shifted (after very long time), $\phi_i = \phi_f$ $\implies i_oL = i3L \implies i = \dfrac{i_o}{3} $ where $i_o$ is $\dfrac{\varepsilon}{R}$ So the initial current in the circuit after switch is shifted is $\dfrac{i_o}{3}$ But, I really didn't understand why the flux should be conserved in this case i.e. why $\phi_i = \phi_f$. I would like to know about this concept and the reasons involved. $\phi_i$ and $\phi_f$ are the total flux in both inductors immediately before and immediately after the switch is shifted? A: A better arrangement would be as follows the reason being that at no time will there be an open circuit as the switch position is changing? With the switch in position 1 a current flows though the switch but no current flow through inductor $2L$ as it is short circuited by the switch. The right loop consisting of the two inductors, the cell and the resistor has a magnetic flux passing through it $\Phi_{\rm i} = L \,i_{\rm i}$ When the switch is moved to position 2 the magnetic flux linked with that loop cannot change instantaneously and so the right loop adjusts itself by having the having the same magnetic flux linked with it but now that magnetic flux is contributed by both inductors with $\Phi_{\rm f} = L \,i_{\rm f}+ 2L \,i_{\rm f}$. You may wonder as to the origin of the magnetic flux linked with the circuit. Some time ago I was trying to explain Faraday's law and why two turns produced double the flux linkage than one turn. Being unable to draw a satisfactory sketch of the area through which the magnetic field was passing I hit on the idea of using a soap film to represent the area. There is an equivalent circuit for capacitors which perhaps is intially easier to analyse? In this case it would be charge which is conserved and on moving the switch to position 2 the initial voltage across the two capacitors would drop to $\frac v 3$. Note that in both case energy is not conserved
{ "pile_set_name": "StackExchange" }
Q: Secury Benefits of PHP PDO vs mysql_*() Are there any security benefits of using PHP PDO instead of the mysql_connect(), etc.? A: No need even to bindParam, just do $stmt = $pdoConnection->prepare('SELECT foo FROM bar WHERE baz = :baz'); $stmt->execute(array(':baz' => 1)); foreach ($stmt as $row) { } That easy. A: No. There is no security benefit to PDO vs the MySQL extension (except for what Murphy's law has taught us, which applies to both). Both will render input safe by escaping the same characters. However, PDO has other advantages: Support for prepared statements; Object-oriented interface; Data access abstraction; and Produces cleaner code because you can escape multiple values at once These are generally considered as the most important.
{ "pile_set_name": "StackExchange" }
Q: Reference to the Preferences environment value When answering the question Check if scheduled local agents can run in Notes client I found a forum post by Javed Khan indicating that this can be checked by checking if a bit in the Preferences environment value is set. Const LOCAL_AGENTS = &H8000000 Call Session.SetEnvironmentVar("Preferences", Cstr( Clng( Session.GetEnvironmentValue( "Preferences", True )) Or LOCAL_AGENTS ), True ) The "Scheduled local agents" settings is apparently the 28:th bit. My question is: Is there any online documentation for the meaning of the other bits? A: Here is the list, taken from http://www-10.lotus.com/ldd/46dom.nsf/55c38d716d632d9b8525689b005ba1c0/e870840587eed796852568f6006facde?OpenDocument 0 <0> = Keep workspace in back when maximized (Enabled=1) 1 <2> = Scan for unread 2 <4> = 3 <8> = Large fonts 4 <16> = 5 <32> = Make Internet URLs (http//:) into hotspots 6 <64> = 7 <128> = Typewriter fonts only 8 <256> = Monochrome display 9 <512> = Scandinavian collation 10 <1024> = 11 <2048> = 12 <4096> = Sign sent mail (Enabled(1)) 13 <8192> = Encrypt sent mail 14 <16384> = Metric(1)/Imperial(0) measurements 15 <32768> = Numbers last collation 16 <65536> = French casing 17 <131072> = empty trash folder (prompt during db close=0/always during db close=1/manual=1 18 <262144> = Check for new mail every x minutes (Enabled=0) 19 <524288> = Enable local background indexing 20 <1048576> = Encrypt saved mail 21 <2097152> = 22 <4194304> = 23 <8388608> = Right double-click closes window 24 <16777216> = Prompt for location 25 <33554432> = 26 <67108864> = Mark documents read when opened in the preview pane 27 <134217728> = Enable local scheduled agents 28 <268435456> = Save sent mail (Always prompt=10/Don't keep a copy=00/Always keep a copy=01) 29 <536870912> = 30 <1073741824> = New mail notification (None=10/Audible=00/Visible=01) 31 <2147483648> =
{ "pile_set_name": "StackExchange" }
Q: How do I correctly extend the django admin/base.html template? This seems like it should be simple but I must be doing something wrong. I've extended admin templates for individual apps before, but this is the first time I've tried extending to modify something across the board. I want to change the color of the help text across the entire admin, so I want to extend the extrastyle block of the base.html template. So in my main templates folder I created admin/base.html with this code in it: {% extends 'admin/base.html' %} {% block extrastyle %} {# Changing the color of the help text across the entire admin #} <style> .help, p.help { font-size: 10px !important; color: #f00; } </style> {% endblock %} Now, when I try and access the admin, the server completely crashes with a 'bus 10' error. I believe this is because it is trying to extend itself. Since Django looks first in my app template folders, {% extend 'admin/base.html' %} finds itself first and the world explodes. However, if I try placing the base html anywhere else it doesn't work. If I place it in one of my apps it works only for that app, but if I place it anywhere else it is just ignored. From my understanding it's a best practice to extend instead of override django templates, so I would like to get this working. However if the only way I can do it is by overriding it, then that's the route I'll take. A: Indeed, your problem is an infinite recursion loop as base.html extends itself. To achieve what you want you should override admin/base_site.html instead (which in turn extends base.html). That way you can replace only the blocks you're interested in.
{ "pile_set_name": "StackExchange" }
Q: GWT collections performance and recommended practices What is the best way and/or recommended practices for working with collections in GWT, specially if looking for performance? The options I have found so far are: JRE emulated collections. The most natural way for a Java developer but, in GWT team words "not an ideal match for the constraints of running inside browsers, especially mobile browsers". A performance comparaison can be found here and here GWT Lightweight Collections. Between other improvements they promised to bring minimum size of compiled script and absolute maximum speed. However there are no news regarding this project for 7 months. Guava Libraries Is it safe to use Guava in GWT? If so, does it brings real performance improvement? Any other alternatives? Many thanks A: If you're looking for absolute optimal performance on the browser, you should use something like Lightweight Collections -- native JS arrays and maps only, and all contained objects as JavaScriptObjects (overlay types). However, this will severely limit your coding efficiency, since they aren't at all as easy to use as JRE collections. There is no contains(), no enhanced for loops, none of the niceties of Java. And after all, "the niceties of Java" are presumably why you're programming in GWT and not JS. Guava doesn't aim to bring any particular efficiency benefits to a GWT app, it mostly just provides a simpler coding experience, and occasionally a tiny optimization here and there that you may not have considered. Guava is not optimized for GWT, it's merely available on GWT. So, it's up to you. If you want to have the convenience of using regular Java collections, you should use Guava. If you want the absolute fastest performance, do everything in native collections. A: Agree with previous answer and providing some additional details: GWT Lightweight collections designed to be client-side only. If you will want to transfer those using RPC mechanism you will likely end in the exception. Another approach to speed up your JavaScript is to use Arrays instead of Collections where it is possible both for transport and processing. Arrays are closer to its JavaScript analogues and GWT does not compile-in too much wrapping code for compatibility purposes. Would not expect any performance benefits from Guava as well.
{ "pile_set_name": "StackExchange" }
Q: Memory deallocation and exceptions I have a question regarding memory deallocation and exceptions. when I use delete to delete an object created on the heap . If an exception occurs before this delete is the memory going to leak or this delete is going to execute ? A: In the case you describe, memory is going to leak. Two tricks to avoid this problem : use smart pointers, which don't suffer from the same problem (preferred solution) --> the smart pointer in constructed on the stack, its destructor is therefore called, no matter what, and deletion of the pointed content is provided in the destructor use try/catch statements, and delete the item in catch statement as well A: This depends on where that delete is. If it's inside the catch that catches the exception, it might invoke. try { f(); // throws } catch( ... ) { delete p; // will delete } If it's after the catch that catches the exception and that catch doesn't return from the function (i.e. allows execution flow to proceed after the catch block) then the delete might be called. try { f(); // throws } catch( ... ) { // execution proceeds beyond catch } delete p; // will delete If the delete is not in a catch block or after a catch block that allows execution to proceed then the delete will not call. try { f(); // throws delete p; // will not delete } // ... As you may imagine, in the two first cases above the delete will not be invoked if there is a throw before the delete: try { f(); // throws } catch( ... ) { g(); // throws delete p; // will not delete }
{ "pile_set_name": "StackExchange" }
Q: can't change value of variable unless you do the command strcpy I am reading the "C programming book" and I understand how this program functions, but, I don't understand one thing. I don't understand how fahr is functioning as a variable. does fahr have two values or one? Cause I thought once you write a value for a variable you can't change it unless you do the command strcpy. Maybe I am wrong, can some one help me clarify? Source: #include <stdio.h> #include <stdlib.h> int main() { float fahr, celsius; int lower,upper, step; lower = 0; upper = 700; step = 2; fahr = lower; printf("Fahrenheit\tCelsius\n"); while (fahr <= upper) { celsius = (5.0/9.0) * (fahr-32.0); printf("%3.0f \t %6.1f\n", fahr, celsius); fahr = fahr + step; } } A: When you declare a variable for example float fahr you define a memory space in which will be saved the number that you give to your variable. The content of the the variable fahr can change with an assignment expression such as float = lower where now the content of fahr is the same with the content of lower variable .You can assign values to a variable as many times you want. Assigning a value to a variable has nothing to do with strcpy .strcpy is a function that copies one string to another for example: char src[40]; strcpy(src, "This is a sentence ");
{ "pile_set_name": "StackExchange" }
Q: running validation on form array I have a form which is dynamically built from an xml file and looks like this with all the meaningless info stripped out: foreach($xml->config->popup as $popup_item) { <label for="fm-popup_name[]">* Popup Name:</label> <input id="fm-popup_name[]" name="fm-popup_name[]" type="text" value="<?php echo $popup_name ; ?>" /> <label class="fm-req" for="fm-popup_desc[]">* Popup Description:</label> <textarea rows="4" cols="50" id="fm-popup_desc[]" name="fm-popup_desc[]" /></textarea> <label for="fm-popup_image[]">* Popup Image:</label> <input id="fm-popup_image[]" name="fm-popup_image[]" type="file" /> } Now i have a validation script i use for client side function validate() { if(document.getElementById('fm-popup_desc').value == "" || document.getElementById('fm-popup_desc').length < 4 || document.getElementById('fm-popup_desc').value > 30){ alert( "The Description should be between 4 and 65,000 characters" ); document.getElementById('fm-popup_desc').focus() ; return false; } var image_value = document.getElementById("fm-popup_image").value; var ext_image = image_value.substring(image_value.lastIndexOf('.') + 1); if(ext_image != "gif" && ext_image != "GIF" && ext_image != "JPEG" && ext_image != "jpeg" && ext_image != "jpg" && ext_image != "JPG" && ext_image != "png" && ext_image != "bmp"){ alert("Invalid image type, please try again using one of the following formats: gif, jpg, jpeg, bmp or png"); return false; } return(true); } Then i run the following on the form: onSubmit="return validate() Now that works fine for a static form but on my dynamic form im not sure how to make it run the validation for every loop. I have a similar situation for my server side validation and i use the following to access each one for the file size and type validation: $file_size = $_FILES[$form_field_name]['size'][$key]; But im not sure how to do a similar thing for the javascript as the current script runs onSubmit and im not sure how to access each value client side. A: First of all, you want you IDs to be unique. Assuming $popup_item is a good varname string: foreach($xml->config->popup as $popup_item) { <input id="<?php echo $popup_name ; ?>" name="<?php echo $popup_name ; ?>" type="text" value="" /> etc. But then do another loop to generate your validation code: foreach($xml->config->popup as $popup_item) { var image_value = document.getElementById("<?php echo $popup_name ; ?>").value; etc.
{ "pile_set_name": "StackExchange" }
Q: Alipay Integration Does anybody know anything about Alipay payment service? Does alipay.com have an API (Like paypal or moneybookers)? Does anybody have documentation? I cannot find anything. Thanks in advance. A: I have also started development with alipay. Maybe this can be helpful: https://globalprod.alipay.com/order/integrationGuide.htm A: Stripe has just added support for Alipay. Using this is likely to be far easier than trying to reinvent the wheel. A: I just recently needed to integrate Alipay into my site, and decided to open up a derivative of my work. It's pretty basic, doesn't include refunds, etc. But it will hopefully point you in the right direction: https://github.com/bitmash/alipay-api-php I will improve the library over time (hopefully). Keep in mind this is not the GLOBAL Alipay version. It is the domestic Alipay version for Chinese merchants. However, the APIs are very similar.
{ "pile_set_name": "StackExchange" }
Q: "NoSuchMethodError" when initialising object from pthread I have an Android/Java application which calls down to C++ code through JNI to start a blocking operation. The C++ code starts a thread to do this blocking operation which should then call back through JNI when it's finished. Calling down to C++ works without any issues. However, when calling back to JNI a mix of error's are being reported. Getting a jclass reference from a new thread is apparently not legal. Performing that action gives "unpredictable behaviour" so all class lookup's are being performed in the JNI_OnLoad() method and look like this: static jclass sampleClazz; jint JNI_OnLoad(JavaVM *vm, void *reserved) { jvm = vm; JNIEnv* env = NULL; jint result = jvm->GetEnv((void**)&env, JNI_VERSION_1_6); if(env == NULL) { __android_log_print(ANDROID_LOG_DEBUG, "JNI_OnLoad", "NULL");} sampleClazz= env->FindClass("com/sample/SampleClazz"); sampleClazz= (jclass) env->NewGlobalRef(sampleClazz); ...etc... } In one of these threads I'm trying to call back to the Java code. The callback method looks similar to this: void cCallBackOne() { JNIEnv* env; jvm->AttachCurrentThreadAsDaemon(&env, NULL); jmethodID init = env->GetMethodID(sampleClazz, "<init>", "()V"); if(init == NULL) { __android_log_print(ANDROID_LOG_DEBUG, "START", "NULL HERE"); } else { __android_log_print(ANDROID_LOG_DEBUG, "START", "ALL FINE"); } Unfortunately for some unknown reason this is logging/throwing: Exception Ljava/lang/NoSuchMethodError; thrown while initializing Lcom/sample/SampleClazz; NULL HERE While working through different solution's I tried moving the GetMethodId to the JNI_OnLoad method in order to see if I could correctly pull the method reference from the original Java thread. It works fine... But strangely, once I do this The code inside the callback also begins to work. I'm massively stumped. I have no idea what is going on and am not sure what to try next. A: So far I've put it down to an error being thrown elsewhere and this being a symptom of just such a problem. I have created these set of methods and am now using check() after each of my calls: void check(jclass toCheck) { if(toCheck == NULL) { __android_log_print(ANDROID_LOG_ERROR, "Check", "Error retrieving jclass"); } } void check(jmethodID toCheck) { if(toCheck == NULL) { __android_log_print(ANDROID_LOG_ERROR, "Check", "Error retrieving jmethodID"); } } void check(jfieldID toCheck) { if(toCheck == NULL) { __android_log_print(ANDROID_LOG_ERROR, "Check", "Error retrieving jfieldID"); } } void check(jobject toCheck) { if(toCheck == NULL) { __android_log_print(ANDROID_LOG_ERROR, "Check", "Error retrieving jobject"); } } Just adding these checks have so far solved my issue... For the sake of sanity I hope there is a reason other than "magic" to explain why this is... I'm afraid though I'm going to have to admit there was some strange exception being thrown earlier in the code execution and this was simply a symptom of an earlier crash. The lesson: Remember to insulate your code people! If JNI crashes it keep's it to itself and something down the road will break instead.
{ "pile_set_name": "StackExchange" }
Q: Show that continuous functions preserve sequence convergence in topological spaces Let $(X, \mathcal{T}) and (Y, \mathcal{U})$ be topological spaces and let $f : X \rightarrow Y$. Suppose $f$ is continuous, and $\{x_n\}_{n=1}^{\infty}$ is a sequence in $X$ converging to a point $x$. I need to show that $\{f(x_n)\}_{n=1}^{\infty}$ converges to $f(x)$. This is what I have so far: Since $f$ is continuous, we have that $f(\overline A) =$ $\overline{f(A)}$. We see that $\overline{\{x_n\}_{n=1}^{\infty}} =$ $\{x_n\}_{n=1}^{\infty} \cup \{x\}$ and so we have $f(\{x_n\}_{n=1}^{\infty} \cup \{x\}) =$ $\overline{\{f(x_n)\}_{n=1}^{\infty}} = \{f(x_n)\}_{n=1}^{\infty} \cup$ $f(x)$. Therefore, there exists a sequence in $\{f(x_n)\}_{n=1}^{\infty}$ that converges to $f(x)$. But now I'm stuck because I don't know how to show that this sequence is $\{f(x_n)\}_{n=1}^{\infty}$ and not just some subsequence of it? A: For any neighborhood $V$ of $f(x)$, $f^{-1}(V)$ is a neighborhood of $x$, so there exists some $N\in \mathbb{N}$ such that $x_n\in f^{-1}(V) \forall n>N,$ $i.e. f(x_n)\in V\forall n>\mathbb{N}$.
{ "pile_set_name": "StackExchange" }
Q: Second report in Project always fails Ok, So I am learning SSRS, and I have come across the wierdest problem. I created a new report project in 2008 studio. Now I added a report just fine. It runs, and everything is great! So now I am trying to add a report that uses a parameter. I figured it would be simple, just add a parameter to the query, and "poof" microsoft would handle, but the report always fails. So, I decided to take the query from my good report, Fail! So I remove the query all together, Fail! I delete the report and start over with no query, Fail! I simply add a text box to the most basic of reports, and Fail! I keep getting the same error: Could not find file 'C:\MyReports\MYReports\bin\Debug\ReportFile.rdl' Does anybody have an idea of why this is happening? Thanks A: Right click the solution and go to the properties. In the 'Debug' section use the name of the report that you want to run. It sounds like project looking to run a report that does not exists.
{ "pile_set_name": "StackExchange" }
Q: SugarORM in AndroidManifest I've one problem: I use SugarORM for my app and in AndroidManifest I need to set this: <meta-data android:name="DATABASE" android:value="moneyManager.db" /> <meta-data android:name="VERSION" android:value="1"/> <meta-data android:name="QUERY_LOG" android:value="true"/> <meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="ua.marinovskiy.moneymanager" /> And this: android:name="com.orm.SugarApp" And now, when I'm using startActivityForResult from adapter: Intent intent = new Intent(context, NewOperation.class); ((Activity) context).startActivityForResult(intent, MainFragment.REQUEST_CODE); I take this error: java.lang.ClassCastException: com.orm.SugarApp cannot be cast to android.app.Activity My question: how I can cut this android:name="com.orm.SugarApp" from Manifest file or another way to resolve this problem? EDIT: public class MainFragment extends Fragment { public final static int REQUEST_CODE = 1; ViewPager viewPager; PagerAdapter viewPagerAdapter; List<List<CategoryParent>> list; List<Integer> balance_list = new ArrayList<>(); List<String> periods_list = new ArrayList<>(); SugarHelper sugarHelper; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_main, container, false); sugarHelper = new SugarHelper(); list = sugarHelper.readAllOoerations(MainActivity.type_of_period, MainActivity.min_date, MainActivity.max_date, MainActivity.addedDate, balance_list); periods_list = sugarHelper.getPeriods(); viewPager = (ViewPager) view.findViewById(R.id.pager); viewPagerAdapter = new ViewPagerAdapter(getActivity().getApplicationContext(), list, balance_list, periods_list); viewPager.setAdapter(viewPagerAdapter); viewPager.setCurrentItem(MainActivity.addedDate); return view; } @Override public void onResume() { super.onResume(); list.clear(); list.addAll(sugarHelper.readAllOoerations(MainActivity.type_of_period, MainActivity.min_date, MainActivity.max_date, MainActivity.addedDate, balance_list)); if (!list.isEmpty()) { viewPagerAdapter.notifyDataSetChanged(); viewPager.setAdapter(viewPagerAdapter); viewPager.setCurrentItem(MainActivity.addedDate); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == getActivity().RESULT_OK) { Toast.makeText(getActivity().getApplicationContext(), "done", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity().getApplicationContext(), "cancel", Toast.LENGTH_SHORT).show(); } } } And my ViewPagerAdapter class: public class ViewPagerAdapter extends PagerAdapter { private OperationsAdapter operationsAdapter; private List<CategoryParent> categoryParentArrayList; private ExpandableListView expandableListView; TextView tv_balance, empty, current_period; Context context; List<List<CategoryParent>> list; List<Integer> balance_list; List<String> periods; LayoutInflater inflater; SugarHelper sugarHelper; public ViewPagerAdapter(Context context, List<List<CategoryParent>> list, List<Integer> balance_list, List<String> periods) { this.context = context; this.list = list; this.balance_list = balance_list; this.periods = periods; } @Override public int getCount() { return list.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == ((RelativeLayout) object); } @Override public Object instantiateItem(ViewGroup container, int position) { inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.viewpager_item, container, false); sugarHelper = new SugarHelper(); tv_balance = (TextView) view.findViewById(R.id.balance_operations); current_period = (TextView) view.findViewById(R.id.current_period); current_period.setText(periods.get(position)); setBalance(balance_list, position); expandableListView = (ExpandableListView) view.findViewById(R.id.expListView); categoryParentArrayList = list.get(position); if (!categoryParentArrayList.isEmpty()) { empty = (TextView) view.findViewById(R.id.if_empty); empty.setVisibility(View.INVISIBLE); operationsAdapter = new OperationsAdapter(context, categoryParentArrayList); expandableListView.setAdapter(operationsAdapter); expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { v.setBackgroundColor(Color.parseColor("#B2EBF2")); Intent intent = new Intent(context, NewOperation.class); MainFragment mainFragment = new MainFragment(); mainFragment.startActivityForResult(intent, MainFragment.REQUEST_CODE); return false; } }); expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { Toast.makeText(context, "group", Toast.LENGTH_LONG).show(); return false; } }); } ((ViewPager) container).addView(view); return view; } @Override public void destroyItem(ViewGroup container, int position, Object object) { // Remove viewpager_item.xml from ViewPager ((ViewPager) container).removeView((RelativeLayout) object); } public void setBalance(List<Integer> balance_list, int position) { tv_balance.setText("Balance: $" + balance_list.get(position)); if (balance_list.get(position) < 0) { tv_balance.setBackgroundResource(R.drawable.balance_minus_style); } else { tv_balance.setBackgroundResource(R.drawable.balance_plus_style); } } And exception: 09-03 14:40:03.915 13091-13091/ua.marinovskiy.moneymanager E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.IllegalStateException: Fragment MainFragment{426ee278} not attached to Activity at android.support.v4.app.Fragment.startActivityForResult(Fragment.java:906) at ua.marinovskiy.moneymanager.adapter.ViewPagerAdapter$1.onChildClick(ViewPagerAdapter.java:95) at android.widget.ExpandableListView.handleItemClick(ExpandableListView.java:583) at android.widget.ExpandableListView.performItemClick(ExpandableListView.java:522) at android.widget.AbsListView$PerformClick.run(AbsListView.java:2812) at android.widget.AbsListView$1.run(AbsListView.java:3571) at android.os.Handler.handleCallback(Handler.java:725) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:153) at android.app.ActivityThread.main(ActivityThread.java:5297) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) at dalvik.system.NativeStart.main(Native Method) ua.marinovskiy.moneymanager.adapter.ViewPagerAdapter$1.onChildClick(ViewPagerAdapter.java:95) at mainFragment.startActivityForResult(intent, MainFragment.REQUEST_CODE); SOLUTION: I leave ((Activity) context).startActivityForResult(intent, MainFragment.REQUEST_CODE); and change in fragment, when I call adapter getActivity().getApplicationContext() on getActivity(). A: You MUST specify com.orm.SugarApp in your manifest, there is no avoiding this. You are trying to cast context to an Activity in this line: ((Activity) context).startActivityForResult(intent, MainFragment.REQUEST_CODE); context is actually an instance of com.orm.SugarApp hence why you are getting the crash. Since you are executing this from a Fragment then use the following code instead: getActivity().startActivityForResult(intent, MainFragment.REQUEST_CODE); UPDATE: Don't pass an Application context to your adapter, pass an Activity context: This is wrong: viewPagerAdapter = new ViewPagerAdapter(getActivity().getApplicationContext(), list, balance_list, periods_list); viewPager.setAdapter(viewPagerAdapter); Do this instead: viewPagerAdapter = new ViewPagerAdapter(getActivity(), list, balance_list, periods_list); viewPager.setAdapter(viewPagerAdapter); UPDATE: You're instantiating a Fragment, not attaching it to anything and then trying to use it to fire off a startActivitiesForResult intent. This is wrong, use the context you already have within the adapter for this: Change this: MainFragment mainFragment = new MainFragment(); mainFragment.startActivityForResult(intent, MainFragment.REQUEST_CODE); To this: ((Activity) context).startActivityForResult(intent, MainFragment.REQUEST_CODE);
{ "pile_set_name": "StackExchange" }
Q: Maven build successful but .class files not found I am using Maven 2.2.1. I have an enterprise java maven project which I am trying to build. When I run mvn clean install the EAR is generated. No compilation errors are found. In the logs I get the message that 1980 source files are compiled to ApplicationWeb\target\classes directory. But I cannot find these class files in the location and they are not present in WAR. How to solve this ? Edit: When built from Eclipse using Maven plugin, its working fine. It gives issue when run from Windows Command Prompt. Why the difference ? A: That sort of thing usually happens when you're using a different version of Maven. I'm betting your Eclipse is using 3.x which is the in built version. You have 2 choices: Make Eclipse use the same version as your command line Install a new version of Maven. (3.0.3 is the latest) I'd recommend upgrading Maven to the latest and getting both your command line and Eclipse to use the same installed version.
{ "pile_set_name": "StackExchange" }
Q: Android dont print ARGB color like #c01c2112 Does Android not supporting printing the color like #c01c2112 with the format ARGB? It display error because of invalid color. This part of my code is Store 1 and 0 into the arraylist. ArrayList<String>arrayList = new ArrayList<>(); for(int a = 0; a < bitmap1.getWidth(); a++){ for(int b = 0; b < bitmap1.getHeight(); b++){ String a1 = String.valueOf(arrayInput1[a][b]); String a2 = String.valueOf(arrayInput2[a][b]); String a3 = String.valueOf(arrayInput3[a][b]); String a4 = String.valueOf(arrayInput4[a][b]); String a5 = String.valueOf(arrayInput5[a][b]); String a6 = String.valueOf(arrayInput6[a][b]); String a7 = String.valueOf(arrayInput7[a][b]); String a8 = String.valueOf(arrayInput8[a][b]); arrayList.add(a1+a2+a3+a4+a5+a6+a7+a8); // Store 1110001 into ArrayList } }//End of nested For Then here is the part to pass the data to an array. String [] hexArrayRed = new String[arrayList.size()]; arrayList.toArray(hexArrayRed); Then I input myself the #ff and the 0000 and combine with the data as I convert the data to hexadecimal value type. It is working fine here. for(int a = 0; a < hexArrayRed.length; a++){ int dec = Integer.parseInt(String.valueOf(arrayList.get(a)),2); String hexString = Integer.toString(dec, 16); String alpha = "#ff"; String behind = "0000"; hexArrayRed[a] = alpha+hexString+behind; /* Red Hexadecimal Value --> #ff _ _ 0000 */ } Then there is the problem. QRCodeWriter qwRed = new QRCodeWriter(); try { HashMap<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); hints.put(EncodeHintType.MARGIN, 2); BitMatrix matrix = qwRed.encode(finalText, BarcodeFormat.QR_CODE, bitmap1.getWidth(), bitmap1.getHeight(), hints); //START OF RED final Bitmap newBitmapRed = Bitmap.createBitmap( bitmap1.getWidth(), bitmap1.getHeight(), Bitmap.Config.ARGB_8888 ); int counter1 = 0; for (int a = 0; a < bitmap1.getWidth(); a++) { for (int b = 0; b < bitmap1.getHeight(); b++) { //int c = 0; int[] color = new int[hexArrayRed.length]; color[counter1] = Color.parseColor(hexArrayRed[counter1]); //Error is right here int d = matrix.get(a,b)? color[counter1]: Color.WHITE; newBitmapRed.setPixel(a,b,d); counter1++; } } //END OF RED Then I get the error of printing the unknown color. Process: kopilim.scs.prototyping, PID: 9890 java.lang.IllegalArgumentException: Unknown color Is it the Android dont support color like #f212cc12 some sort like this the ARGB color? A: Your code of converting from binary to decimal to hex works fine, except for one tiny part. The problem is related to this part of your code: String hexString = Integer.toString(dec, 16); The problem with using Integer.toString() is that it'll give you the integer as a String, without the extra 0 padding. What I mean by this is, for example: if your binary String was 00000111. Using Integer.parseInt("00000111", 2); would give you a decimal int of 7. Finally, using String hexString = Integer.toString(7, 16); would give you a String of "7". Therefore, when you plug that value into your hexArrayRed[a], instead of plugging it in as #AARRGGBB, you're plugging it in as #AARGGBB which is an improper format. So to fix this, you simply have to check the length of hexString to see if it only has a size of 1. If it is, append an extra 0 to the front of it when you create your full hex string.
{ "pile_set_name": "StackExchange" }
Q: Python List generation: Force new Object Is there a way in Python to force to generate a new object when creating a list? Assume I have a class Test of which I want to store 5 objects in a list. I use the following code to generate the list: myList = [Test()] * 5 With this code python creates only 1 Object which is stored 5 times. Of course I could use a for-loop to generate the list. But in my real program this would blow up the code extremly, because I have about 30 lists, which are partly nested in another List. So Is there a fast way (maybe a one-liner) to force python to generate a new Object in each entry? A: Use a list comprehension to execute an expression more than once: myList = [Test() for _ in range(5)] Since this would ignore the range()-produced index, I named the for loop target _ to signal the variable is ignored; this is just a naming convention.
{ "pile_set_name": "StackExchange" }
Q: Divergence Theorem Clarification. Given that $\textbf{F} = \langle 3x,y^3,-2z^2 \rangle$, and the region bounded by $ x^2 + y^2 = 9$ and $z=0, \: z=5$ I'm trying to use the divergence theorem to find the line integral. $$\iint_{D} \textbf{F} \cdot \textbf{N} \: dS = \iiint_E \nabla \cdot \textbf{F}\:d\textbf{V}$$ Attempt: Top disk: Since the normal vector of a disk on the xy-plane is $\langle 0, 0, 1 \rangle$ and z = 5 on the top disk, Now, $\iint_T \langle 3x , y^3, -2(5)^2 \rangle \cdot \langle 0 , 0, 1\rangle \: d\textbf{S} = \int_0^{2\pi} \int_0^3 -50 r\: dr\: d\theta = -45\pi $. But this is not right! Similarly, for the bottom disk, $\iint_B \langle 3x , y^3, -2(0)^2 \rangle \cdot \langle 0 , 0, -1\rangle \: d\textbf{S} = 0$ However, the answer given for both of the disk is $\frac{-45}{4}\pi$ Any help would be appreciated! Thank you A: Your method of calculating the surface integrals on the top and bottom surfaces is correct! (Although, as Doug pointed out, the top contribution should be $-450\pi$.) But you also need to work out the surface integral on the curved surface of the cylinder! Let's parametrise the curved surface by $$ (x,y,z) = (3 \cos \phi, 3 \sin \phi, z), \ \ \ \ \ 0 \leq \phi < 2\pi , \ \ 0 \leq z \leq 5. $$ Then $$ \vec F = (9\cos \phi, 27 \sin^3 \phi, -z^2), \ \ \ \vec n = (\cos \phi, \sin \phi, 0), \ \ \ \ \ dS = 3d\phi dz. $$ So the contribution from the curved surface is $$ \iint \vec F. \vec n dS = \int_{z = 0}^{z = 5} \int_{\phi = 0}^{\phi = 2\pi} (9\cos^2 \phi + 27 \sin^4 \phi) 3d\phi dz = \frac{1755\pi}{4}.$$ I plugged this into mathematica, but you can work it out explicitly. Anyway, the sum of all three contributions is $$-450\pi + 0 - \frac{1755\pi}{4} = - \frac {45\pi}{4}.$$ Of course, you can also work out the volume integral of the divergence. Here, $$\nabla . \vec F = 3 + 3y^2 - 4z = 3 + 3 \rho^2 \sin^2 \phi - 4z$$ in cylindrical polars, and a quick calculation on mathematica gives $$ \iiint \nabla . \vec F dV = \int_{\rho = 0}^{\rho = 3} \int_{z = 0}^{z = 5} \int_{\phi = 0}^{\phi = 2\pi} (3 + 3 \rho^2 \sin^2 \phi - 4z) \rho d\phi dz d \rho= - \frac{45\pi}{4}$$
{ "pile_set_name": "StackExchange" }
Q: Magento 2 - Area code not set when running script via command line CLI I have created module for exporting my product data to script outside of Magento2. This is my Data.php <?php namespace Oktarin\Nabavanet\Helper; class Data extends \Magento\Framework\App\Helper\AbstractHelper { protected $markup=1.03; protected $markup_extra=1.02; protected $price_limit=1500.00; protected $pricefile; protected $prices; protected $pdv=0.25; protected $base_url="https://domain.com/index.php/catalog/product/view/id/"; protected $base_image_url="https://domain.com/pub/media/catalog/product"; protected $shipping_cost=35.00; protected $cats; protected $appState; /* public function __construct(\Magento\Framework\App\Helper\Context $context,\Magento\Framework\App\State $state) { $this->appState = $state; parent::__construct($context); } public function execute() { $originalArea = $this->state->getAreaCode(); $this->appState->setAreaCode('frontend'); //reset original code $this->appState->setAreaCode($originalArea); } */ public function getProductCollection() { $collection = $this->_productCollectionFactory->create(); return $collection; } // end of function getProductCollection public function makeXml(){ /* */ // $originalArea = $this->state->getAreaCode(); $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $this->appState= $objectManager->create('Magento\Framework\App\State'); $this->appState->setAreaCode('frontend'); $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory'); $collection = $productCollection->create() ->addAttributeToSelect('*') // ->addAttributeToFilter('sku', array('like' => '%702638%')) ->load(); $product=array(); foreach ($collection as $product_data){ if(!empty($product_data->getEntity_id())){ //Load the product categories $categories1 = $product_data->getCategoryIds(); //Select the last category in the list $categoryId = end($categories1); $categoryObject=\Magento\Framework\App\ObjectManager::getInstance(); $category=$categoryObject->create('Oktarin\Nabavanet\Helper\CategoryTree'); $categoryTreepath=$category->getTreeByCategoryId($categoryId); if(!empty($product_data->getspecial_price())){ $price=$product_data->getspecial_price(); $regular_price=$product_data->getprice(); } else{ $price=$product_data->getprice(); $regular_price=false; } // Dostupnost proizvoda switch($product_data->getproduct_availability()){ case "3929": // Po narudžbi $availability="Po narudžbi"; break; case "3930": // Na stanju $availability="Raspoloživo"; break; case "3931": // Zalihe pri kraju $availability="Raspoloživost potrebno provjeriti"; break; } $product[]=array( "internal_product_id" => $product_data->getEntity_id(), "sku" => $product_data->getsku(), "ean" => $product_data->getean(), "name" => $product_data->getName(), "url" => $this->base_url.$product_data->getEntity_id()."/s/".$product_data->geturl_key()."/", "availability" => $availability, "category" => $categoryTreepath, "image_url" => $this->base_image_url.$product_data->getimage(), "additional_image_url" => $this->base_image_url.$product_data->getsmall_image(), "description" => $product_data->getshort_description(), "shipping_cost" => $this->shipping_cost, "regular_price" => $regular_price, "brand" => $product_data->getbrand(), "part_number" => $product_data->getpart_number(), "warranty" => $product_data->getgarancija_proizvoda(), "price" => $price, "specialPrice" => $product_data->getspecial_price(), "tehnickaSpecifikacija" => $product_data->getdescription() ); } // end of of entity_id isnt empty } // end of foreach //reset original code $this->appState->setAreaCode($originalArea); return $product; } // end of function makeXml } // end class Method makeXml() I am calling from another script in file nabavanet-export.php that is designed to be run from cron/CLI/command line: #!/usr/bin/php <?php (PHP_SAPI !== 'cli' || isset($_SERVER['HTTP_USER_AGENT'])) && die('cli only'); require_once __DIR__ . "/include.php"; $nabavanet=new Xml(); /* MAGENTO start */ // calling on Magento Helpers use Magento\Framework\App\Bootstrap; require '../app/bootstrap.php'; $params = $_SERVER; $bootstrap = Bootstrap::create(BP, $params); $obj = $bootstrap->getObjectManager(); $nabava = $obj->get('\Oktarin\Nabavanet\Helper\Data'); // end of Magento Helpers /* END Magento */ try{ $filename="nabavaexport"; $xml=$nabavanet->createNabavanetXMLfile($nabava->createXml(),$filename); if($xml==1){ echo "XML ".$filename.".xml generated!\n"; copy($filename.".xml", "../nabavanet/".$filename.".xml"); } else{ echo "XML ".$filename.".xml not generated\n"; } } catch (PDOException $e) { // detaljan ispis grešaka slanjem // PDOException objekta preko varijable $e // PDO objekta preko varijable $db // PDOStatement objekta preko varijable $stmt showPDOErrors($e, $db_read, $stmt_read); showPDOErrors($e, $db_write, $stmt_write); } ?> Script nabavanet-export.php was working fine when run through browser, however when I run it through command line I get this: Fatal error: Uncaught Magento\Framework\Exception\LocalizedException: Area code is not set in /usr/www/users/shopyb/vendor/magento/framework/App/State.php:152 Stack trace: #0 /usr/www/users/shopyb/vendor/magento/framework/Session/SessionManager.php(173): Magento\Framework\App\State->getAreaCode() #1 /usr/www/users/shopyb/generated/code/Magento/Framework/Session/Generic/Interceptor.php(50): Magento\Framework\Session\SessionManager->start() #2 /usr/www/users/shopyb/vendor/magento/framework/Session/SessionManager.php(130): Magento\Framework\Session\Generic\Interceptor->start() #3 /usr/www/users/shopyb/generated/code/Magento/Framework/Session/Generic/Interceptor.php(14): Magento\Framework\Session\SessionManager->__construct(Object(Magento\Framework\App\Request\Http), Object(Magento\Framework\Session\SidResolver\Proxy), Object(Magento\Framework\Session\Config), Object(Magento\Framework\Session\SaveHandler), Object(Magento\Framework\Session\Validator), Object(Magento\Framework\Session\Storage), Object(Magento\Framework\Stdlib\C in /usr/www/users/shopyb/vendor/magento/framework/Session/SessionManager.php on line 175 As you can see I have tried implementing fix as said many times: public function __construct(\Magento\Framework\App\State $state, $name=null) { $this->appState = $state; parent::__construct($name); } But this also generated error So I have tried modifing it like this but without success: public function __construct(\Magento\Framework\App\Helper\Context $context,\Magento\Framework\App\State $state) { $this->appState = $state; parent::__construct($context); } I hope someone can give me pointers how to make file nabavanet-export.php run as command line. I need that outside script because it is depending on other methods required for generating xml. UPDATE 1 Fix by Sukumar Gorai worked for me however new problem occured, I got this error: Fatal error: Uncaught Magento\Framework\Exception\NoSuchEntityException: No such entity with id = in /usr/www/users//vendor/magento/framework/Exception/NoSuchEntityException.php:49 The script in Data.php should get product information, and it seems that it gets product without ID? UPDATE 2 The problem with entity_id was due to false value returned while fetching categroy ids in another class. I have managed to get around it :). Thank you all for great help! A: You need to change your script nabavanet-export.php like below: <?php (PHP_SAPI !== 'cli' || isset($_SERVER['HTTP_USER_AGENT'])) && die('cli only'); require_once __DIR__ . "/include.php"; $nabavanet=new Xml(); /* MAGENTO start */ // calling on Magento Helpers use Magento\Framework\App\Bootstrap; require '../app/bootstrap.php'; $params = $_SERVER; $bootstrap = Bootstrap::create(BP, $params); $obj = $bootstrap->getObjectManager(); // Set area code $state = $obj->get('Magento\Framework\App\State'); $state->setAreaCode('adminhtml'); $nabava = $obj->get('\Oktarin\Nabavanet\Helper\Data'); // end of Magento Helpers /* END Magento */ try{ $filename="nabavaexport"; $xml=$nabavanet->createNabavanetXMLfile($nabava->createXml(),$filename); if($xml==1){ echo "XML ".$filename.".xml generated!\n"; copy($filename.".xml", "../nabavanet/".$filename.".xml"); } else{ echo "XML ".$filename.".xml not generated\n"; } } catch (PDOException $e) { // detaljan ispis grešaka slanjem // PDOException objekta preko varijable $e // PDO objekta preko varijable $db // PDOStatement objekta preko varijable $stmt showPDOErrors($e, $db_read, $stmt_read); showPDOErrors($e, $db_write, $stmt_write); } ?>
{ "pile_set_name": "StackExchange" }
Q: Replace string values in pandas to their count I`m trying to calculate count of some values in data frame like user_id event_type 1 a 1 a 1 b 2 a 2 b 2 c and I want to get table like user_id event_type event_type_count 1 a 2 1 a 2 1 b 1 2 a 1 2 b 1 2 c 2 2 c 2 In other words, I want to insert count of value instead value in data frame. I've tried use df.join(pd.crosstab)..., but I get a large data frame with many columns. Which way is better to solve this problem ? A: Use GroupBy.transform by both columns with GroupBy.size: df['event_type_count'] = df.groupby(['user_id','event_type'])['event_type'].transform('size') print (df) user_id event_type event_type_count 0 1 a 2 1 1 a 2 2 1 b 1 3 2 a 1 4 2 b 1 5 2 c 2 6 2 c 2
{ "pile_set_name": "StackExchange" }
Q: If we pay for a font, are we fully authorized to use it in our website? I'm finishing a project, and I was thinking to use a font that I liked a lot, but it is paid; I don't mind to pay, because it is not very expensive, and I think it's worth it. On the font website says, "You may use the fonts to create Web Pages" and "Bariol font can be used with @ font-face". So I'm in doubt, if I can or not use this font in my project if I pay it, because even I pay, the people that access the website have access to the font... So is using this font in my website allowed? Here below I have some text using this font: Does anyone know of a Google font similar to this? Because of this situation, I'm already looking for a Google font, in case that is not allowed to use Bariol font. I saw open-sans, and I like it, but it is not very similar to Bariol, but as I have not much experience, I came here to ask your help. A: Always look at what the license says. If it specifically allows use of font on webpages, then it's not your concern if other users are able to access the font file.
{ "pile_set_name": "StackExchange" }
Q: Threejs: PropertyBinding: Cannot parse trackName: .bones[].position Version: THREE.WebGLRenderer 91dev I'm trying to get a simple animation for a chest opening to work in three.js, but I keep getting the following error when attempting to create an action. PropertyBinding: Cannot parse trackName: .bones[].position The full version of the animation JSON object is here on pastebin: Full JSON String. A short summary is below: { "name": null, "fps": 30, "length": 0.5333333333333333, "hierarchy": [{ "parent": -1, "keys": [{ "time": 0, "rot": [ 0, 0, 0, 1 ], "scl": [ 1, 1, 1 ], "pos": [ 0, 0, 0 ] }, I create an Animation clip with the following commands. var clip = THREE.AnimationClip.parseAnimation(animation, armSkeleton.bones); geometry.animations.push(clip); The value of clip is as follows: duration: 0.6 name: "default" tracks: […] 0: Object { name: ".bones[].position", times: […], values: […], … } 1: Object { name: ".bones[].quaternion", times: […], values: […], … } 2: Object { name: ".bones[].scale", times: […], values: […], … } 3: Object { name: ".bones[].position", times: […], values: […], … } 4: Object { name: ".bones[].quaternion", times: […], values: […], … } 5: Object { name: ".bones[].scale", times: […], values: […], … } length: 6 __proto__: Array[] uuid: "3E37E10B-74D0-4421-92AF-7A366CF3804F" The problem is when I try and use the clip with: mixer = new THREE.AnimationMixer(mesh); mixer.clipAction(mesh.geometry.animations[0]).play(); I get the error that threejs cannot parse the trackname ".bones.position" even though that's the name that the parseAnimation function returns? I'm super confused if anyone can point out something stupid I'm doing I would appreciate it. A: After playing around with the problem some more I found the reason for the error was because AnimationClip expects the bones to be named. So managed to get this error to go away by simply giving each bone a unique name before passing it into THREE.AnimationClip.parseAnimation.
{ "pile_set_name": "StackExchange" }
Q: When updating a Chrome window, what does "drawAttention" actually do? The chrome.windows.update method lets you update a window like this: chrome.windows.update(windowId, { drawAttention: true }); The docs say this about the drawAttention option: If true, causes the window to be displayed in a manner that draws the user's attention to the window, without changing the focused window. The effect lasts until the user changes focus to the window. This option has no effect if the window already has focus. Set to false to cancel a previous draw attention request. What does that mean in practice? I can't see any effect on OS X. Does it do something on Windows? A: On a Windows or Linux system, it'll cause the taskbar button for that window to start flashing. There's no standard way for a window to request attention on Mac OS X (bouncing the Dock icon applies to applications, not windows), so that option isn't implemented there.
{ "pile_set_name": "StackExchange" }
Q: How to classify text when pre defined categories are not available I have a problem and not getting idea which algorithm have to apply. I am thinking to apply clustering in case two but no idea on case one: I have .5 million credit card activity documents. Each document is well defined and contains 1 transaction per line. The date, the amount, the retailer name, and a short 5-20 word description of the retailer. Sample: 2004-11-47,$500,Amazon,An online retailer providing goods and services including books, hardware, music, etc. Questions: 1. How would classify each entry given no pre defined categories. 2. How would do this if you were given pre defined categories such as "restaurant", "entertainment", etc. A: 1) How would classify each entry given no pre defined categories. You wouldn't. Instead, you'd use some dimensionality reduction algorithm on the data's features to them in 2-d, make a guess at the number of "natural" clusters, then run a clustering algorithm. 2) How would do this if you were given pre defined categories such as "restaurant", "entertainment", etc. You'd manually label a bunch of them, then train a classifier on that and see how well it works with the usual machinery of accuracy/F1, cross validation, etc. Or you'd check whether a clustering algorithm picks up these categories well, but then you still need some labeled data.
{ "pile_set_name": "StackExchange" }
Q: the JAR of this class file belongs to container 'Junit 4' which does not allow modifications to source attachements on its entries I am new to Junit framework. I am trying to invoke private method in another class from Junit test class using reflection API. I am getting below error while running JUnit test: java.lang.ExceptionInInitializerError at com.test.eb.X.XConnection.dbOpen(XConnection.java:32) at com.test.eb.X.admin.XRefTablePersister.getDbConnect(XRefTablePersister.java:33) at com.test.eb.persistence.Persister.getSortedList(Persister.java:485) at com.test.eb.X.entity.SearchPlan.<init>(SearchPlan.java:49) at com.test.eb.X.entity.Tests.SearchPlanTest.testSearchPlan(SearchPlanTest.java:41) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:176) at junit.framework.TestCase.runBare(TestCase.java:141) at junit.framework.TestResult$1.protect(TestResult.java:122) at junit.framework.TestResult.runProtected(TestResult.java:142) at junit.framework.TestResult.run(TestResult.java:125) at junit.framework.TestCase.run(TestCase.java:129) at junit.framework.TestSuite.runTest(TestSuite.java:255) at junit.framework.TestSuite.run(TestSuite.java:250) at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: java.util.MissingResourceException: Can't find bundle for base name X_bootstrap, locale en_US at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1427) at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1250) at java.util.ResourceBundle.getBundle(ResourceBundle.java:705) at com.test.eb.X.XProperties.<clinit>(XProperties.java:12) ... 24 more When I am debugging the application I do see the following: the JAR of this class file belongs to container 'Junit 4' which does not allow modifications to source attachements on its entries. Actual class public class SP { private java.lang.String searchText; private java.lang.String searchOption; private Hashtable searchResult; private Persistable[] plnCategoryList; private plnCategory persistplnCategory; //CSS, for displaying the result private String cssText; private String cssTableHeader; private String cssTable; private boolean allowDelete; public SP() { super(); persistplnCategory =new plnCategory(); searchText= ""; searchOption = ""; RefTablePersister persister = new XRefTablePersister(); setAllowDelete(false); //Default CSS values cssText="mainbody"; cssTableHeader = "bodytableheader"; cssTable="bodytable"; try { persistplnCategory.setplnCatgCd(""); Class persClass = Class.forName("com.org.plnCategory"); plnCategoryList = persister.getSortedList( persClass, new PersistableDescriptionComparator()); } catch (Exception e) { e.printStackTrace(); } } private int searchpln() throws XException { XConnection XConn = new XConnection(); searchResult = new Hashtable(); pln plnItem = new pln(), plnItem2; cont contItem; CoverageCode covcdItem; Vector tempList; Hashtable tempTable; StringBuffer sqlContr = new StringBuffer(""); StringBuffer sqlCovCd = new StringBuffer(""); ResultSet rsContr; ResultSet rsCovCd; String plnCat=""; if (! persistplnCategory.getplnCatgCd().equals("") && ! persistplnCategory.getplnCatgCd().equals("0")){ plnCat = persistplnCategory.getplnCatgCd(); } sqlContr.append("SELECT ") .append(" p.pln_cd, ") .append(" p.pln_version_nbr, ") .append(" pcr.pln_catg_desc, ") .append(" p.pln_eff_dt, ") .append(" p.pln_end_dt, ") .append(" cp.cont_nbr "); sqlContr.append(" FROM ") .append(" pln p, ") .append(" pln_category_ref pcr, ") .append(" cont_pln cp "); sqlContr.append(" WHERE ") .append(" p.pln_cd = " + getSearchText().trim()) .append(" AND p.pln_catg_cd = pcr.pln_catg_cd ") .append(" AND p.pln_cd = cp.pln_cd ") .append(" AND p.pln_version_nbr = cp.pln_version_nbr "); if (!plnCat.equals("")){ sqlContr.append(" AND p.pln_catg_cd = '" + plnCat + "' "); } sqlContr.append(" ORDER BY ") .append(" p.pln_cd, ") .append(" p.pln_version_nbr, ") .append(" cp.cont_nbr "); try { XConn.dbOpen(); rsContr = XConn.doQuery(sqlContr.toString()); tempTable = new Hashtable(); if (rsContr.next()){ plnItem = new pln(); plnItem.setNumber(rsContr.getString(1).trim()); plnItem.setVersion(rsContr.getString(2).trim()); plnItem.setplnCategoryText(rsContr.getString(3).trim()); plnItem.setEffectiveDate(rsContr.getDate(4)); plnItem.setEndDate(rsContr.getDate(5)); contItem = new cont(); contItem.setNumber(rsContr.getString(6).trim()); tempTable.put(contItem.toString(), contItem); while(rsContr.next()){ plnItem2 = new pln(); plnItem2.setNumber(rsContr.getString(1).trim()); plnItem2.setVersion(rsContr.getString(2).trim()); //just add cont if it is still the same if (plnItem.equals(plnItem2)) { contItem = new cont(); contItem.setNumber(rsContr.getString(6).trim()); tempTable.put(contItem.toString(), contItem); } else { //save the pln info plnItem.setconts(tempTable); searchResult.put(plnItem.toString(), plnItem); //create the pln plnItem = new pln(); plnItem.setNumber(rsContr.getString(1).trim()); plnItem.setVersion(rsContr.getString(2).trim()); plnItem.setplnCategoryText(rsContr.getString(3).trim()); plnItem.setEffectiveDate(rsContr.getDate(4)); plnItem.setEndDate(rsContr.getDate(5)); tempTable = new Hashtable(); contItem = new cont(); contItem.setNumber(rsContr.getString(6).trim()); tempTable.put(contItem.toString(), contItem); } } //save the last pln plnItem.setconts(tempTable); searchResult.put(plnItem.toString(), plnItem); } plnItem2 = (pln) searchResult.get(plnItem.toString()); if (plnItem2 != null){ plnItem2.setCoverageCodes(tempList); searchResult.put(plnItem2.toString(), plnItem2); } } } return searchResult.size();} Junit Class public class SPTest extends TestCase{ public java.lang.String searchText; public java.lang.String searchOption; @Before public void setUp() throws Exception { searchText = "963 - 1"; searchOption = "pln"; } @Test public void testSearchpln() { try { Searchpln searchpln = new Searchpln(); Method method = Searchpln.class.getDeclaredMethod("searchpln", null); method.setAccessible(true); int plnresults = (Integer) method.invoke(searchpln, null); assertNotNull(plnresults); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } finally{ //pbdbConn.dbClose(); } } } A: When I am trying to invoke the searchpln() method it is failed to initialize database connection and hence I am getting java.lang.ExceptionInInitializerError. The issue is now fixed. I have changed code by setting dbDriver,dbURL,dbUser & dbPassword details in class.
{ "pile_set_name": "StackExchange" }
Q: Sums of sets of lower density 0 We say that a set $A\subseteq \mathbb{N}$ has lower density 0 if $$\text{lim inf}_{n\to\infty}\frac{|A\cap\{1,\ldots,n\}|}{n} = 0.$$ Given $A,B\subseteq \mathbb{N}$ we set $A+B = \{a+b: a\in A, b\in B\}$. Are there $A, B\subseteq \mathbb{N}$ with lower density 0, but $A+B$ does not have lower density 0? A: It is relatively easy to prove that the set of perfect squares has asymptotic density equal to $0$. Then either the set $Q_2 := \{x^2+y^2: x,y \in \mathbf N\}$ has positive lower asymptotic density, and we're done, or the lower density of $Q_2$ is zero, and then we just consider that $\mathbf N = Q_2 + Q_2$ (by Lagrange's four-squares theorem). By the way, it follows, e.g., from E. Landau, Über die Einteilung der positiven ganzen Zahlen in vier Klassen nach der Mindeszahl der zu ihrer additiven Zusammensetzung erforderlichen Quadrate, Arch. Math. Phys. 13 (1908), 305-312 that the asymptotic density of $Q_2$ is actually zero, but this is more than what you need to answer the question in the OP. A: Let $A$ be the set of all natural numbers having digit $0$ in every odd-numbered place (counting from the decimal point), and let $B$ be the set of all numbers having a $0$ in every even-numbered place. Then $A$ and $B$ have density $0$, while $A+B=\mathbb N\setminus(A\cup B)$ has density $1$.
{ "pile_set_name": "StackExchange" }
Q: Why doesn't columns.render execute when DataTable().draw() is called? I'm puzzled to why columns.render is not included in the execution pipeline of DataTable().draw(). An example: HTML <table id="data"> <thead> <tr> <th>TimeColumn</th> <th>Column 2</th> </tr> </thead> <tbody> <tr> <td>123</td> <td>234</td> </tr> <tr> <td>345</td> <td>456</td> </tr> <tr> <td>567</td> <td>678</td> </tr> </tbody> </table> <button id="refresh">Refreh</button> jQuery $(document).ready(function () { $('#data').DataTable({ columnDefs: [{ targets: 0, render: function(data, type, row, meta) { return data + ' time:' + Date.now(); } }] }); $('#refresh').on('click', function() { $('#data').DataTable().draw(); }); }); The expected result when clicking the Refresh button is that the time value should advance in the first column, but it doesn't. The assigned render function is never called after initialization. (jsFiddle of the example.) Is there any workaround or do I have to dig into the code of DataTables? A: Instead of destroying the datatable and repopulating it I ended up modifying jquery.datatables.js version 1.10.2. The main issue is that the line 1935 in jquery.datatables.js checks if the row is already created: if ( aoData.nTr === null ) { _fnCreateTr(oSettings, iDataIndex); } One option to remedy this is to set aoData.nTr = null. But this might break other functionality or cause unwanted side effects so this is not an acceptable solution. I opted to instead add an argument to the .draw() function (line 7137) and adding a setting called bForceReDraw (draw() already takes an argument so we add a second argument): _api_register('draw()', function (resetPaging, forceReDraw) { return this.iterator( 'table', function ( settings ) { settings.bForceReDraw = forceReDraw === true; _fnReDraw(settings, resetPaging === false); } ); } ); Then I changed the null check on line 1935 to: if ( aoData.nTr === null || oSettings.bForceReDraw === true ) { _fnCreateTr(oSettings, iDataIndex); } In the function _fnCreateTr() there is also a null check on nTr (line 1586) so I needed to modify that as well: if ( row.nTr === null || oSettings.bForceReDraw === true ) { nTr = nTrIn || document.createElement('tr'); ... Now we simply call draw() with the new argument and everything works as expected. $('#data').DataTable().columns.adjust().draw(false, true); A: Everybody has problems dynamically reloading DataTables. Consider this approach. Destroy the DataTable first to re-render. var dataSet = []; if ($.fn.dataTable.isDataTable('#yourTable')) { $('#yourTable').DataTable({ "destroy": true, "processing": true, "data": dataSet }); } else { $('#yourTable').DataTable({ "processing": true, "data": dataSet }); }
{ "pile_set_name": "StackExchange" }
Q: No module named 'sklearn.neighbors._base' I have recently installed imblearn package in jupyter using !pip show imbalanced-learn But I am not able to import this package. from tensorflow.keras import backend from imblearn.over_sampling import SMOTE I get the following error --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-20-f19c5a0e54af> in <module> 1 # from sklearn.utils import resample 2 from tensorflow.keras import backend ----> 3 from imblearn.over_sampling import SMOTE 4 5 ~/.virtualenvs/p3/lib/python3.6/site-packages/imblearn/__init__.py in <module> 32 Module which allowing to create pipeline with scikit-learn estimators. 33 """ ---> 34 from . import combine 35 from . import ensemble 36 from . import exceptions ~/.virtualenvs/p3/lib/python3.6/site-packages/imblearn/combine/__init__.py in <module> 3 """ 4 ----> 5 from ._smote_enn import SMOTEENN 6 from ._smote_tomek import SMOTETomek 7 ~/.virtualenvs/p3/lib/python3.6/site-packages/imblearn/combine/_smote_enn.py in <module> 8 from sklearn.utils import check_X_y 9 ---> 10 from ..base import BaseSampler 11 from ..over_sampling import SMOTE 12 from ..over_sampling.base import BaseOverSampler ~/.virtualenvs/p3/lib/python3.6/site-packages/imblearn/base.py in <module> 14 from sklearn.utils.multiclass import check_classification_targets 15 ---> 16 from .utils import check_sampling_strategy, check_target_type 17 18 ~/.virtualenvs/p3/lib/python3.6/site-packages/imblearn/utils/__init__.py in <module> 5 from ._docstring import Substitution 6 ----> 7 from ._validation import check_neighbors_object 8 from ._validation import check_target_type 9 from ._validation import check_sampling_strategy ~/.virtualenvs/p3/lib/python3.6/site-packages/imblearn/utils/_validation.py in <module> 11 12 from sklearn.base import clone ---> 13 from sklearn.neighbors._base import KNeighborsMixin 14 from sklearn.neighbors import NearestNeighbors 15 from sklearn.utils.multiclass import type_of_target ModuleNotFoundError: No module named 'sklearn.neighbors._base' Other packages in the environment numpy==1.16.2 pandas==0.24.2 paramiko==2.1.1 matplotlib==2.2.4 scikit-learn==0.22.1 Keras==2.2.4 tensorflow==1.12.0 tensorboard==1.12.0 tensorflow-hub==0.4.0 xlrd==1.2.0 flask==1.0.2 wtforms==2.2.1 bs4==0.0.1 gensim==3.8.1 spacy==2.2.3 nltk==3.4.5 wordcloud==1.6.0 pymongo==3.10.1 imbalanced-learn==0.6.1 I checked the sklearn package, it contains base module, not _base. But modifying it may not be the right solution. Any other solution to fix this issue. A: Previous sklearn.neighbors.base has been renamed to sklearn.neighbors._base in version 0.22.1. You have probably a version of scikit-learn older than that. Installing the latest release solves the problem: pip install -U scikit-learn or pip install scikit-learn==0.22.1
{ "pile_set_name": "StackExchange" }
Q: PHP header redirect not working after update query I am sending a verification link to an email address. The link will direct the user to a page with only a small amount of code. I am essentially just changing one row in my database from a "0" to a "1" indicating they have been verified PHP: <?php include( 'database/sql_link.php' ) ; //This is my link to the database $clientName = mysqli_real_escape_string( $db , $_GET[ 'client' ] ) ; $sql = " UPDATE clients SET verifiedUser = '1' WHERE userName = '$clientName' " ; if ( !mysqli_query( $db , $sql ) ) { die( ' Error: <br> <br> ' . mysqli_error( $db ) ) ; } header( "Location: http://www.example.net/portal.php" ) ; exit() ; The code above will modify the database properly, but it won't redirect to "portal.php". Any input is appreciated. Thanks in advance! Edit - Solved by Shehary - details below in my reply to the thread. A: So my problem was rooted in my initial database link php file. include( 'database/sql_link.php' ); the file had a tab before the starting <?php. Thanks to Shehary. Updated PHP <?php error_reporting(-1); include( 'database/sql_link.php' ) ; $clientCompany = mysqli_real_escape_string( $db , $_GET[ 'comp' ] ) ; $clientName = mysqli_real_escape_string( $db , $_GET[ 'client' ] ) ; $clientAddress = mysqli_real_escape_string( $db , $_GET[ 'address' ] ) ; $sql = " UPDATE clients SET verifiedUser = '1' WHERE userName = '$clientName' " ; if ( !mysqli_query( $db , $sql ) ) { die( ' Error: <br> <br> ' . mysqli_error( $db ) ) ; } header( "Location: http://www.etheritwiki.net/evanJustinProject_Portal_Client.php" ) ; exit() ; $db -> close() ; $sql -> free() ;
{ "pile_set_name": "StackExchange" }
Q: add more white space in content pseudo class How can I add more space using content pseudo class I am using below code to add single space. h3:before{content:" "} I need to add more space by using content. PS: No addition in html pls A: What about using some padding-right instead of spaces? h3 { padding-right: 10px }
{ "pile_set_name": "StackExchange" }
Q: Why isn't Meteor Collection behaving reactively? TLDR: I want to track the dependencies of a Meteor Collection to work out why my template helper isn't reactive. I have been trying to create a reactive checklist component in Meteor that can be reused in different templates. Live Demo Github Template: <template name="checklist"> <ul> {{#each items}} <li> <label> <input type="checkbox" value="{{value}}" checked="{{isChecked}}" data-id="{{_id}}" /> {{name}} </label> <span>&nbsp;&nbsp;&nbsp; Status: {{status}}</span> </li> {{/each}} </ul> {{checkedIds}} </template> Javascript: if (Meteor.isClient) { var list; /** * * Creates a Checklist instance, with a local collection that maintains the status * of all checkboxes: 'checked', 'unchecked' or 'indeterminate' * */ function createChecklist() { var _checked = new Meteor.Collection(null), check = function(id) { return _checked.upsert({_id: id}, {_id: id, status: 'checked'}); }, getStatus = function(id) { var item = _checked.findOne({_id: id}) return item && item.status; }, isChecked = function(id) { return _checked.find({_id: id, status: 'checked'}).count() > 0; }, getCheckedIds = function() { return _checked.find({status: 'checked'}).map(function(doc){return doc._id}); }, toggle = function(id) { if ( isChecked(id) ) return uncheck(id); else return check(id); }, uncheck = function(id) { return _checked.upsert({_id: id}, {_id: id, status: 'unchecked'}); }; return Object.freeze({ 'check': check, 'getCheckedIds': getCheckedIds, 'getStatus': getStatus, 'isChecked': isChecked, 'toggle': toggle, 'uncheck': uncheck }); } Template.checklist.helpers({ items: [ {_id: 0, name: 'Item 1', value: 10}, {_id: 1, name: 'Item 2', value: 20}, {_id: 2, name: 'Item 3', value: 40}, {_id: 3, name: 'Item 4', value: 20}, {_id: 4, name: 'Item 5', value: 100}, ], isChecked: function() { return list.isChecked(this._id); }, status: function() { return list.getStatus(this._id); }, checkedIds: function() { return EJSON.stringify(list.getCheckedIds()); } }); Template.checklist.events({ 'change [type=checkbox]': function(e, tmpl) { var id = e.target.dataset.id; list.toggle(id); } }); Template.checklist.created = function() { list = createChecklist(); } } You'll notice that the checkedIds helper is reactively updating whenever you check a box. However, the status helper is not reactively updating. I am trying to: Track the dependencies of the _checked collection in order to work out if the status helper has been added as a Computation. Understand why this helper is not reactively updating. If anyone could help with either of these items, I'd be really grateful. So far I have done the following: Confirmed that Deps.active = true inside the status helper (and its function calls) Put the following code inside the status helper to check if it is invalidated when I tick a checkbox (it is never invalidated): var comp = Deps.currentComputation; comp.onInvalidate(function() { console.track(); }); A: The _id is stored as a string in Mongo. Change to: getStatus = function(id) { var item = _checked.findOne({_id: String(id)}) return item && item.status; },
{ "pile_set_name": "StackExchange" }
Q: Deserializing JSON array containing objects with an array using GSON I have a JSON response representing a Band that looks like this: [ { "Picture": { "Small": "someurl "Medium": "someurl", "Large": "someurl", "XLarge": "someurl" }, "Name": "Tokyo Control Tower", "Guid": "TCT", "ID": 15 } ] And I'm trying to use GSON to deserialize it into a class called SearchResults which contains a list of Bands. My SearchResults and Band classes look like this: public class SearchResults { public List<Band> results; } public class Band { @SerializedName("Name") public String name; @SerializedName("Guid") public String guid; @SerializedName("ID") public Integer id; @SerializedName("Picture") List<Photo> pictures; } In my code I try to convert the json string like this: protected void onPostExecute(String result) { Gson gson = new Gson(); SearchResults results = gson.fromJson(result, SearchResults.class); Band band = results.results.get(0); bandName.setText(band.name); } When I run this code, I get an error from GSON saying Expected BEGIN_OBJECT but was BEGIN_ARRAY. Any ideas on how to fix? A: You have a couple issues. First and foremost, what is causing the error you post is that you are telling Gson that your JSON represents an object (SearchResults) when it doesn't; your JSON is an array of objects (specifically, an object you're mapping to your Java Band class). The correct way to do this is via: Type collectionType = new TypeToken<Collection<Band>>(){}.getType(); Collection<Band> bands = gson.fromJson(jsonString, collectionType); Once you do that you're going to have a problem in that in your Java class you're saying that "Picture" in your JSON is an array of Photo objects when in fact it's not; it's a single object.
{ "pile_set_name": "StackExchange" }
Q: LocationMatch negative expression I want password protection for the site just webservice URL stay allow all. This expression work perfectly in apache, just need turn opposite. <LocationMatch "^(.*service).*$"> AuthType Basic AuthName "Restricted Files" AuthUserFile /storage/www/xxxxx/.htpasswd Require valid-user </LocationMatch> I try many many form, but doesn't work. I tried this and work perfectly in reguler tester just not in apache (2.2) <LocationMatch "^(?!.*service).*$"> How can negate that expression? .htaccess content if matter. RewriteEngine on RewriteBase / # .... RewriteRule txxxx/(.*) index.php?config=main_lite&r=script/xxx/deliverData&url=$1 # rule 1 -- let these requests pass through (S=1 skips the next rule) RewriteCond %{REQUEST_FILENAME} favicon.(gif|ico) [NC,OR] RewriteCond %{REQUEST_FILENAME} .+\.(pdf|js|css|txt|jpg|jpeg|gif|png|bmp|ico|swf|html|log|svg|ttf|eot|woff|woff2)$ [OR] RewriteCond %{REQUEST_URI} rsc/ [OR] RewriteCond %{REQUEST_URI} index.php$ RewriteRule (.*) - [S=1] # rule 2 - pass every request to index.php RewriteRule .* index.php A: It seems Apache regexp support is too limited.. However, you easily may "negate" your expression by defining all you want for it in an enclosing clause (say, "Location") and then reverting to the 'default' settings under your (non-negated) LocationMatch. Something like this: https://serverfault.com/questions/591591/apache-locationmatch-regex-behaviour-does-not-seem-correct
{ "pile_set_name": "StackExchange" }
Q: Batch file minimize with using coloured text Can anyone help me with a problem that I am having. I have made a number of scripts that I run with calling the main script (Run.sikuli). Now I haven't done much with batch files before, but I am trying to make a batch file to execute my scripts. I have the following code: @ECHO OFF REM Change the colours: Background = Black, Letters = Light Green color 0A REM Start up the test scripts. C:\Users\<userName>\Documents\SiKuLi\runIde.cmd -r C:\Users\<userName>\Documents\SiKuLi\Run.sikuli I would like green text is my prompt, so we don't confise it some other prompt. I also would like to get this window get minimized when it pops up. I now I can use this code for that: start /min And it also works, but then my coloured text is white again because a new command prompt gets opened. Does anyone know how to get my prompt minimized while keeping my coloured letters? A: start /min "" cmd /c "color 0a & C:\Users\<userName>\Documents\SiKuLi\runIde.cmd -r C:\Users\<userName>\Documents\SiKuLi\Run.sikuli" Run a color command inside the started console.
{ "pile_set_name": "StackExchange" }
Q: Why is this array of type Any? Why is Q of type Any? I am trying to multiply it against a Float64 array and getting "no matching method" qi=5000.0 b=0.9 di=0.6 mnths=600.0 t=1.0 AI=(1/b)*((1-di)^-b-1) ai=AI/12 q(t)=qi/(1+b*ai*t)^(1/b) Q=[q(t-1) for t=1:mnths] A: Type inference in the global scope is harder (since global variables can be reassigned anywhere). So either do Q=Float64[q(t-1) for t=1:mnths] or wrap everything in a function (which could be a good idea anyway).
{ "pile_set_name": "StackExchange" }
Q: Coreplot on iOS - How to remove the default padding so the chart fills the view completely without axis labels I am trying to put 6 Coreplot charts on an iPad in landscape mode so each chart is 128pixels in height (ie. 768/6) The issue I am having is that if I set all the padding to 0 the chart still has lots of padding around the chart being plotted. Is there a way to remove this default padding from the chart? Thanks in advance Damien The pink marks in the image are the padding I want to remove http://i.stack.imgur.com/nXzFv.png or http://s10.postimage.org/d2rl0ajsn/Image13.png Here is the chart without the theme applied (The padding is still present) I added a pink border so you can see the actual size I also tried setting the padding to -20.0 and the same padding was present but the visible chart area was cutting the chart off. There seems to be an outer frame which is setting this padding and holding the chart area.. A: The default padding on the graph itself (not the plot area frame) is 20 pixels on each side. You can change that, too. graph.paddingLeft = 0.0; graph.paddingTop = 0.0; graph.paddingRight = 0.0; graph.paddingBottom = 0.0;
{ "pile_set_name": "StackExchange" }