Codeigniter: Selecting different columns from 3 tables

Question: Today i encountered a problem developing my app.
I restructured my database.
I have 3 tables for posts, photos, and for the tags of the posts.
I joined the two other tables(photos, tags).
I would like to query the first 3 post with only one SELECT with photos and tags, but only the first row showing up from the results.
Heres is my code:
<code>$this->db->select('owner, title, time, LEFT(content, 75) as content, category, url, price, county');

$this->db->from(POSTS_TABLE);

$this->db->join(PHOTOS_TABLE, PHOTOS_TABLE.'.post_id = '.POSTS_TABLE.'.url');

$this->db->join(TAGS_TABLE, TAGS_TABLE.'.post_url = '.POSTS_TABLE.'.url');

$this->db->order_by('time', 'desc');

$this->db->limit(3);

$query = $this->db->get();

$posts = $query->result();
</code>
My DB structure:
posts table:
<code>id, owner, title, content, url
</code>
tags table: id, post_id (same as the url column from the posts table), photo (the link to the photo)
tags table:
<code> id, post_url (same as the url column from the posts table), tag.
</code>
Please help.How can i achieve that with only one SELECT and showing up the correct results ?
I cannot use the WHERE clause, since i dont know the exact post_url
Answer: Considering column name 'url' is the id of the row
Try:
<code>// Code before
$this->db->join('PHOTOS_TABLE', 'PHOTOS_TABLE.post_id = POSTS_TABLE.url');
$this->db->join('TAGS_TABLE', 'TAGS_TABLE.post_url = POSTS_TABLE.url');
// Code After
</code>
Comment: "Considering column name 'url' is the id of the row"

not really, url is the unique id of the post in the posts table.There can be multiple rows with the same 'url' column in the photos and tags table.


How to retrieve JNDI using Spring @Configuration instead of XML configuration

Question: I've started development of a new Spring 3.2.4 application and am trying to use Java based configuration instead of XML files as I have used in the past.  However, I am having trouble making the transition.
Using XML, I would code it as follows:

<bean id="dataSource.jndi" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton" lazy-init="true">
    <property name="jndiName" value="java:comp/env/jdbc/liment" />
</bean>

<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
    <property name="persistenceUnitName" value="persistenceUnit"/>
    <property name="dataSource" ref="dataSource.jndi"/>
</bean>

However, I am very much stuck trying to figure out how to do this in Java.  I'm trying to replicate the configuration, but running into trouble:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages={"com.ia"})
public class AppConfigJPA {
    @Bean
    public DataSource dataSource() {
        // configure and return the necessary JDBC DataSource
        JndiObjectFactoryBean dataSource = new JndiObjectFactoryBean();
        dataSource.setJndiName("java:comp/env/jdbc/liment");
        try {
            dataSource.afterPropertiesSet();
        } catch (IllegalArgumentException | NamingException e) {
            // rethrow
            throw new RuntimeException(e);
        }
        return (DataSource)dataSource.getObject();
    }

    @Bean
    public EntityManagerFactory entityManagerFactory(){
        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setPersistenceUnitName("persistenceUnit");
        emf.setDataSource(dataSource());
            emf.afterPropertiesSet
        return emf.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager(entityManagerFactory());
    }

}

However, I get the following error message:
Caused by: java.lang.IllegalStateException: No persistence exception translators found in bean factory. Cannot perform exception translation.
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators(PersistenceExceptionTranslationInterceptor.java:142)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.setBeanFactory(PersistenceExceptionTranslationInterceptor.java:117)
    at org.springframework.data.repository.core.support.PersistenceExceptionTranslationRepositoryProxyPostProcessor.<init>(PersistenceExceptionTranslationRepositoryProxyPostProcessor.java:44)
    at org.springframework.data.repository.core.support.TransactionalRepositoryFactoryBeanSupport.setBeanFactory(TransactionalRepositoryFactoryBeanSupport.java:85)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1502)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1470)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
    ... 33 more

What am I missing or doing wrong?
EDIT
Following @SotiriosDelimanolis response, I have modified my code to read the following:
@Autowired DataSource dataSource;
@Autowired EntityManagerFactory entityManagerFactory;

@Bean
public JndiObjectFactoryBean dataSource() {
    // configure and return the necessary JDBC DataSource
    JndiObjectFactoryBean dataSource = new JndiObjectFactoryBean();
    dataSource.setJndiName("java:comp/env/jdbc/josak");
    return dataSource;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setPersistenceUnitName("persistenceUnit");
    emf.setDataSource(dataSource);
    return emf;
}

@Bean
public PlatformTransactionManager transactionManager() {
    return new JpaTransactionManager(entityManagerFactory);
}

But am getting Autowired exceptions instead now:
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: javax.sql.DataSource com.ia.system.configuration.AppConfigJPA.dataSource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
    ... 31 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:988)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
    ... 33 more

Comment: Can you verify that the reference returned by `dataSource.getObject();` is `null`? That shouldn't happen if you called `afterPropertiesSet()`. And please post the longer stack trace.
Comment: @SotiriosDelimanolis Actually, I just caught a mistake in the code before I saw your comment.  I had forgotten an "afterPropertiesSet()" call in the entityManagerFactory().  But now, I get a different Exception relating to a persistence exception translator.
Answer: please refer below link -
http://forum.spring.io/forum/spring-projects/container/724356-how-to-use-javaconfig-to-declare-a-jndi-datasource
the datasource need to be created like this  -
@Bean
    public DataSource dataSource() {
        final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
        dsLookup.setResourceRef(true);
        DataSource dataSource = dsLookup.getDataSource("jdbc/yourJdbcGoesHere");
        return dataSource;
    }

Comment: `setResourceRef` is not necessary in this context as JndiDataSourceLookup sets it to true. The code is simply `new JndiDataSourceLookup().getDataSource("jdbc/yourJdbcGoesHere")`
Comment: You should actually use @Bean(destroyMethod="")
Answer: This is a weird design (for PersistenceExceptionTranslator) that I don't immediately understand, but here is the solution.
Your LocalContainerEntityManagerFactoryBean is a FactoryBean but also a PersistenceExceptionTranslator (implements both). But you aren't putting the LocalContainerEntityManagerFactoryBean into your context, you are only getting its created object.
Instead of
@Bean
public EntityManagerFactory entityManagerFactory(){
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setPersistenceUnitName("persistenceUnit");
    emf.setDataSource(dataSource());
        emf.afterPropertiesSet
    return emf.getObject();
}

do
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setPersistenceUnitName("persistenceUnit");
    emf.setDataSource(dataSource());
    return emf;
}

@Autowired
private EntityManagerFactory entityManagerFactory;

@Bean
public PlatformTransactionManager transactionManager() {
    return new JpaTransactionManager(entityManagerFactory);
}

Spring will take care of calling afterPropertiesSet() and getObject() to put a EntityManagerFactory bean into the context.
Basically you end up with two beans, a EntityManagerFactory and a LocalContainerEntityManagerFactoryBean. Your JPA configuration requires a PersistenceExceptionTranslator bean in the context. That will be satisfied by LocalContainerEntityManagerFactoryBean.

FYI, you can do the same thing for your JndiObjectFactoryBean or any other FactoryBean.
Comment: The JpaTransactionManager is expecting an EntityManagerFactory as its constructor type.  If entityManagerFactory() returns a LocalContainerEntityManagerFactoryBean, how do I instantiate the transactionManager()?  Similarly, if I return a JndiObjectFactoryBean from dataSource(), how do I set the emf.setDataSource() with teh JndiFactoryBean?
Comment: @EricB. Spring is magic that way. It proxies the `@Bean` method calls and returns the `FactoryBean` created bean instead of the `FactoryBean` itself.
Comment: I don't understand.  Returning the factory bean makes the compiler complain on `return new JpaTransactionManager(entityManagerFactory())` : `The constructor JpaTransactionManager(LocalContainerEntityManagerFactoryBean) is
 undefined`
Comment: @EricB. Oh that. My bad. A workaround is to `@Autowired` beans of the type of object your `FactoryBean` beans create into some `@Configuration` class fields. Then use them instead of calling their respective methods.
Comment: This seems very complicated.  Can you post an example please?  I tried what you suggested, but obviously am doing something wrong as I am getting NoSuchBeanDefnExceptions when it is trying to autowire my DataSource bean.  I'm editing the question above to post my new code and exception
Comment: Thanks for the update, but still no dice.  I'm getting circular bean referencing errors: `Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'entityManagerFactory': Requested bean is currently in creation: Is there an unresolvable circular reference?`
Comment: @ericB. At worst, you can call the `@Bean` methods and call the `getObject()` method on their returned references. You will have to cast the return value of `JndiObjectFactoryBean`. [Something similar](http://stackoverflow.com/questions/5541094/factorybeans-and-the-annotation-based-configuration-in-spring-3-0). A `FactoryBean` is typically meant to return the same instance on each call.


Skype installation fails, cannot install ia32-libs

Question: When I try to install it from the Software Center, it displays an error:
The following packages have unmet dependencies:
 skype: Depends: skype-bin but it is a virtual package

Running sudo apt-get install Skype gives the same error.
When I download it from the official website, the .deb file opens in Software Center and displays "Cannot install 'ia32-libs'" and doesn't even show the install button.
Please help. How can I install Skype?
Answer: Try install ia32-libs with this: ia32-libs installation askubuntu answer.
Then try install Skype again.
Comment: I've tried but didn'nt work...
Thanks..
Answer: Type from terminal sudo apt-get install skype-bin, this should get you the latest version of Skype from the repositories
The other option is to download the package from skype official website.
Answer: I had similar kind of problem and this seemed to do the trick immediately:
http://www.gmjjavadesigns.com/content/ubuntu-1304-skype-wont-load-because-error-finding-libglso1
Or simply in terminal:

gksu gedit /etc/ld.so.conf.d/skype.conf
Add line:
/usr/lib32
Ctrl+S
Ctrl+Q
sudo ldconfig -v
Run Skype


What are the issues that will be difficult to change once software is built?

Question: Software architecture focuses on "Issues that will be difficult or impossible to change once the software is built." How is this statement justified?
Comment: with feedback , and reported issues
Comment: Well why would you spend time on the things that are *easy* to change once the software is built? They're easy to change, you can change them.
Answer: There are things that are easy and cheap to change, like individual functions, page layouts, fields... More difficult is the overall design and infrastructure.  If you start out with a relational model, and after the software is built, decide to switch to a NOSQL model, it's going to be expensive.  If you designed your software to be a monolith, and then switch to microservices, it's going to be expensive.  If you build an object-oriented design, and you switch to functional design, it's going to be expensive.
Those decisions are architectural, and should be made as early in the project as possible.


How can I prevent, in Angular, two incompatible directives to be assigned to the same element?

Question: I have to similar directives that shouldn't be added to the same HTML element to avoid weird behaviour.
Is there any standard way to establish to directives as incompatible or to check whether these to directives are assigned to the same element and throw an error or a warning?
Answer: You could achieve that with a custom rule in linter such as eslint. Configure it as error and the linting will fail when the rule is met. I believe it's a better approach than trying to detect it in the code of the directives themselves during runtime. There are plenty of resources discussing custom eslint rules such as https://flexport.engineering/writing-custom-lint-rules-for-your-picky-developers-67732afa1803


What is the difference between self-modifying code and reflection?

Question: Self-modifying code is code that "alters its own instructions while it is executing".  This is not typically done outside of assembly language or viruses.
Reflection is just the ability of a program to access its own namespace dynamically, in order to reference functions and classes and variables dynamically.  According to this article, reflection is not just introspection (a program's ability to examine itself), but also intercession (a program's ability to modify itself).
So, is the difference that reflection refers to a mild form of self-modifying code where only the variable/class/function name gets "modified" within the instructions?  That is, reflection is a milder, less "dramatic" form of modification compared with the ability to modify the nature of the entire instruction itself as in self-modifying code.
Do I have this distinction right?
Answer: No, one is about changing the code during execution. The other about reading the structure and metadata (introspection) of the code during execution.
They can be mutually exclusive. You don't need to know how the code is to modify it (if the OS allows you that is).
Typically you can use reflection to execute code in a non 'normal use case' manner, but it's still the same code. contrast this to modifying the code.
The goals are completely non aligned.
However I suppose one example where they intersect in a small way is to consider a function (F) that calls two other functions - A then B. You could reflect that knowledge and then call B then A (thus modifying the use case of (F)). as you can see it's not not modifying code, rather just the intended use case.


How to wrap PHPUnit to control command line reporting?

Question: So I've got a lot of PHPUnit tests (they are actually Selenium tests running as PHPUnit tests). When I run them from the command line, I get this sort of reporting as the tests complete:
..E..F..E.FF...

Then I have to wait until all the tests finish running before it will tell me the errors and what failed. I would like to be able to control this so I can do some more useful reporting. For example:
testLogin ....... passed
testFoobar ...... failed
    - Failed asserting that foo = true on line 123
testBazbat ...... passed

How can I get control over how PHPUnit displays the results?
Answer: PHPUnit has a few command line parameters to control the output format. The most useful ones for your are --testdox and --tap
They work like this:
]> phpunit --tap FooTest.php
TAP version 13
not ok 1 - Failure: FooTest::test_add
  ---
  message: fark
  severity: fail
  ...
ok 2 - FooTest::test_exists
ok 3 - FooTest::test_show_html
ok 4 - FooTest::test_show_array
ok 5 - FooTest::test_show_empty
ok 6 - FooTest::test_find
1..6

]> phpunit --testdox FooTest.php
PHPUnit 3.5.0 by Sebastian Bergmann.

Foo
 [ ] test add
 [x] test exists
 [x] test show html
 [x] test show array
 [x] test show empty
 [x] test find

As you can see --testdox does not show the failure reason, its ment to be used like a kind of specification generator. But --tap comes pretty close.
And you can always write your own test listener - a custom class that implements PHPUnit_Framework_Testlistener interface (has methods like startTest, endTest, addFailure, addError etc; the names are pretty self-explanatory, respective code will be called for events that happen when your testsuite runs).
Such code is hooked up into phpunit using the xml configuration file.
One good example of such custom listener can be viewed here: http://raphaelstolt.blogspot.com/2010/06/growling-phpunits-test-status.html
Comment: Thanks. That's really helpful. Could you elaborate a bit more on what you mean by "test listener" and "loader"? That might be where I want to go with it, but I wouldn't know where to start.
Comment: I edited the answer with more details about test listeners. Custom test loader is actually not relevant at all for your issue, so I removed that part.
Comment: `--tap` does not display any useful information on errors. IMO `--verbose` is more useful.
Answer: use the
--printer path/to/MyTestListener

option to point to your custom MyTestListener class
http://www.phpunit.de/manual/3.6/en/textui.html#textui.clioptions
or it can be set in your phpunit.xml config file with the printerClass property
see http://www.phpunit.de/manual/3.6/en/appendixes.configuration.html#appendixes.configuration
Here's the instructions how to make your own printer class
http://www.phpunit.de/manual/current/en/extending-phpunit.html#extending-phpunit.examples.SimpleTestListener.php
If you don't want to start from scratch just rename and modify the default printer
https://github.com/sebastianbergmann/phpunit/blob/master/PHPUnit/TextUI/ResultPrinter.php
Answer: If you want pretty HTML report pages, try to use phing's phpunitreport task. For Screenshots, see my blog entry. Very helpful for larger test suites.


Set url to be used for assets

Question: I have a rails app
salmonfishing.com

which has a database. I have another app
salmonfishing-test.com

How can I alias the root url so that when a user goes to
http://salmonfishing-test.com

the assets and data from the
http://salmonfishing.com database

will be used.
My database.yml points to the 'salmonfishing' database, but the generated url for an image is
http://salmonfishing-test/bigfish.png

That is as would be expected, however internally I would like that to be aliased to
http://salmonfishing.com/bigfish.png

...basically so all assets and data are served from 'salmonfishing' database, and saved to it. Ran across various ways of setting sub-paths, but not root for assets and data.
Cheers,
 Jet

Comment: Two questions: Your assets are stored in the database, what kind? Are you speaking of app-related assets (like javascript, stylesheets and images for things like logos and UI) or user-related assets (like avatar images)?
Answer: If your only problem is the wrong domain name in your asset URLs, you can change it in your environment config file: config/environments/[whatever].rb:
config.action_controller.asset_host = "http://salmonfishing.com"

This line is already present in production.rb, but it's commented out.

Set url to be used for assets


Loading relevant data into browser for Grails app

Question: I am building a grails application for large datasets and facing various problems due to loading a large json file on the javascript side (client side) of my application, due to which the browser crashes.
Now, I have realized I am taking all user selections on the javascript side only, but I'm assuming it can be done on the grails controller side also using the  tag and "params"
I am looking at :
http://grails.org/doc/latest/ref/Tags/link.html
http://grails.org/doc/latest/ref/Tags/form.html

But, I'm very new to this and needed some direction if what I'm trying to do is feasible or not?
Basically, I want the user to select a bunch of dropdowns, the values of which are passed to my grails controller and the controller sends the filtered data to the javascript to load, such that only the relevant data is sent to the browser and it runs properly.
UPDATE
package marchmock2
class Tablev1class {
Date date_hour
String mv
String pagetype
Integer visits
Integer visits_ly
Integer visits_lw
String time_period
String platform
String device
String browser

static mapping = {
table "pgtyp"
version false
date_hour column: "date_hour"
mv column: "mv"
pagetype column: "pagetype"
visits column: "visits"
visits_ly column:"visits_ly"
visits_lw column:"visits_lw"
time_period column:"time_period"
platform column:"platform"
device column:"device"
browser column:"browser"
}
static constraints = {
}
}

This is how my domain class looks like and there is no dependency. All I want is create selects from various mv, pagetype, platform, device, browser and make the selections made pass to the controller which has a query to be made to the database
Comment: Create g:select elements that list the same table set optionValue to be different objects I.e. first selwct optionValue mv 2nd pagetype and so on. If you need it to calc something as user selects then look at onchange and a remotecall on it to xall controller that processes selected element
Answer: I think you may need to edit question and redefine your requirements in the the last section.
You could take a look here:
I want my selects dropdowns to auto populate with Ajax in Grails website
On this question I sort of broke up how you can use remote calls to collect data from one field to generate the next selection ? is this part of the requirements or are these all single selections that have no dependencies on each other ?
If dependency related selection then take at ajaxdependancyselection plugin where proper nested selections can be achieved.If selection is from large data set then maybe advice on primary question would probably be quicker.....
UPDATE
Since they are independent, You could load up the
<g:select name="input1" from="${domainClass1.list()}" ...>

for each domainClass call
Post it back to your controller
In your controller
def d1=domainClass1.get(params.input1)
def d2=domainClass2.get(params.input2)

render (view: 'something', model: [ d1: d1, d2:d2 ] )

and so on
then you could expand on each of the domainClass objects passed and get specific related elements out of each d1 d2 etc....
I am really unsure of objective so apologies if it is not what your looking for
UPDATE UPDATE
Unsure why you need to have selections per object, maybe as you say you want to then do something with the values..
In which case look at the last example the optionKey and optionValue are all set to device so it will show device in the selection and user selection will end up being actual device selection
<g:select id="mv" name="mvid" from="${marchmock2.Tablev1class.list()}" optionKey="id"   optionKey="mv" required="" value="${params?.mvid}" class="many-to-one"/>
<g:select id="mv" name="mvid" from="${marchmock2.Tablev1class.list()}" optionKey="id"   optionKey="pagetype" required="" value="${params?.mvid}" class="many-to-one"/>

<g:select id="mv" name="mvid" from="${marchmock2.Tablev1class.list()}" optionKey="id"   optionKey="platform" required="" value="${params?.mvid}" class="many-to-one"/>

<g:select id="mv" name="mvid" from="${marchmock2.Tablev1class.list()}" optionKey="device"   optionKey="device" required="" value="${params?.mvid}" class="many-to-one"/>

Now to expand this
<g:select id="mv" name="mvid" from="${marchmock2.Tablev1class.list()}" optionKey="device"   optionKey="device" required="" value="${params?.mvid}" class="many-to-one" onchange="${remoteFunction (
        controller: 'someController',
        action: 'someAction',
        params: "'device=' + this.value",
        update: 'newDivId'
    )}"/>

Comment: There is no dependency related selection needed in my application. All dropdowns are independent
Comment: There is no dependency related selection needed in my application. All dropdowns are independent. Also, we have huge datasets, hence filtering on these datasets inside the browser is not a good idea. Hence, I somehow want to do the filtering of data (on the dimesions selected in GSP) inside the controller and then send it to browser so that the load to the browser can be reduced. Also,being new to Grails, i don't even know whether this is actually feasible or not.In case you have any suggestions, do let me know.It will be of great help
Comment: Oh wait..I have one domain class with many fields(or whatever it is called). These dropdowns that I have mentioned about are few of the various fields inside my domain class.My apologies , if I am being very stupid but , is this what you call a dependent selects??
Comment: And also, why I mentioned that my selects are not inter dependent because, no matter what is selected in the first select, the other selects need to have all the value every time. Hence, I called out them being not dependent.
Comment: I am still confused, can you post a sample domainClass example, if you have lets say primary domainClass that has  MULTIPLE hasMany relationships so a Country hasMany Cities and Citizens. Are you saying you want the country selected to then show the relevant cities and citizens all together ? if so this is supported in ajaxdependancyselection you just declare domain2 domain3 domain4 etc check the examples further down for multi domain selection.. Or do you wish to create select fields for different fields in one domainClass - set by optionKey optionValue each time... you just declare field nam
Comment: Please have a look at this http://stackoverflow.com/questions/24572811/remotefunction-not-working


How to get System.Data.SQLite Database File Option in DataSource

Question: I've followed below tutorials
http://geekswithblogs.net/danielggarcia/archive/2013/12/22/portable-databases-ii-using-sqlite-with-entity-framework.aspx
But after installation of System.Data.SQLite using Net-Gu Package manager, no option is available for SQLite Database File in

Answer: I found myself in the same problem. What it works for me is follow the explanation in this ticket: https://system.data.sqlite.org/index.html/tktview/2be4298631c01be99475
But basically, after deleting the following lines in the App.config it worked:
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />

<remove invariant="System.Data.SQLite" />
Answer: You need to install SQLite pre required dll for window from following link:
http://www.sqlite.org/download.html
Comment: Above works only on x86 Architecture or 32-bit machines. But I've 64-bit machine.
Comment: @PrakashVishwakarma Try in Visual Studio 10
Answer: Download this file if you use VS 2013:
https://system.data.sqlite.org/downloads/220.127.116.11/sqlite-netFx451-setup-bundle-x86-2013-18.104.22.168.exe
For complete list: https://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki


2 blue wires on furnace

Question: Today I was trying to put in my smart thermostat and have had no luck. My old thermostat (pictured below) did not have a C wire connected but did have the wire behind the old thermostat.

After the power not coming on to my new Smart thermostat, I checked the furnace to make sure the blue wire was hooked up to the furnace. To my surprise, there were two blue wires that I found. There was a wire "pack" that had all the wires bundled together (including a blue wire) but that blue wire wasn't connected to anything. On the other hand, there was another lone blue wire that was connected to the furnace. It seemed odd to me that the blue wire including in the bundled wires wasn't connected, and a random other blue one was. Any thoughts on this? Any help is appreciated!
Comment: Can you get us a clearer view of the wiring block at the furnace please?
Answer: The blue wire at the furnace is likely feeding an airconditioner relay or something that was added later to the furnace.  The unconnected blue wire in the "bundle" needs to go to the c terminal so both of them are connected there.

2 blue wires on furnace


Angular JS - input value from another input value

Question: Is it possible to bind the value of an input to the value of another input? The following is not working:
<input ng-model="val">
<input value="Hello {{val}}">

Comment: What is not working?  It seems to work for me.
Answer: Here is simple solution: http://plnkr.co/edit/7HxnM3O1UE1RxCCPvvJ0?p=preview
app.js
app.controller('MainCtrl', function($scope) {
    $scope.formatText = function() {
        return "Hello " + $scope.text;
    };

    $scope.$watch('text', function(newValue) {
        $scope.formatedText = "Hello "+ (newValue ? newValue : "");
    })
});

index.html

    <input type="text" ng-model="text"/>
    <input type="text" ng-model="formatedText"/>

For more common way you can use $scope.$eval together with your own directive.
Answer: For your simple use case you posted you can use dot notation.
Fiddle example Fiddle
<input ng-model="new.val">
<input value="Hello {{new.val}}">

By using dot.notation you avoid collision with scoping issues and conflict with global namespace. Not knowing all the variables involved this might have been the issue.
Anything $scope.val would interfere.
<input ng-model="val">
<input value="Hello {{val}}">

By using dot notation and deep linking you can avoid a lot of common issues.
Comment: The OPs code works as is.  What advantage to you get from using dot notation?
Comment: Added more explanation. With limited info I tried posting a common issue I've seen.
Answer: Yes.  Here is a working plunker with your code.
js:
var myApp = angular.module('myApp', []);

myApp.controller('Ctrl', function($scope) {

  $scope.val = 'Guy';

  });

html:
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />

Hello Plunker!

    <input ng-model="val">
    <input value="Hello {{val}}">

*Note: you aren't required to add val to the controller unless you want to initialize its value.


Exponential function inequality

Question: How can you show that $$(1-\frac{1}{n})^r \leq e^{-r/n}\ ?$$
I'm not really too sure how to do it.
Comment: can you tell us something about the variables?
Comment: How do you mean?
Comment: what kind of numbers are $$r,n$$?
Comment: Tell us whether $n$ is a natural number or not and so on.
Comment: from where does this inequality come?.
Comment: Oh of course. Both $r$ and $n$ are natural numbers ($\neq 0$).
Answer: I showed in THIS ANSWER that the sequence $e_n$, given by $e_n=\left(1-\frac1n\right)^n$ is monotonically increasing.  Recalling that $\lim_{n\to \infty}e_n=e^{-1}$ we have
$$\left(1-\frac1n\right)^n<e^{-1} \tag 1$$
whence raising both sides of $(1)$ to the $r/n$, where $r\in \mathbb{N}$, power yields the coveted inequality
$$\left(1-\frac1n\right)^r<e^{-r/r}$$
as was to be shown!
Answer: taking the logarithm on both sides we obtain
$$r\ln\left(1-\frac{1}{n}\right)<-\frac{r}{n}$$
if $$r>0$$ then we can divide by $$r$$ and we get $$\ln\left(1-\frac{1}{n}\right)<-\frac{1}{n}$$ multipliying by $-1$ we get $$-\ln\left(1-\frac{1}{n}\right)^n>1$$
can you finish this?

Exponential function inequality


Yii2: How to change font-family of Select2 widget

Question: I have a select2 widget and I need to change its font-family.
<?= $form->field($model, 'my_number')
    ->widget(Select2::classname(), [
        'items' => ['One' => 'One', 'Two' => 'Two', 'Three' => 'Three'],
        'class' => 'form-control',
]) ?>

Bootstrap doesn't have a class to change it so I think I need to change its style.
Answer: As you are using Kartik Select2 and to customize the Font-family for the select2 you need to update the following classes that are added in the select2-krajee.css file.They are divided into 2 groups if you want to change the font-family
Changing Font Family
For the Placeholder and selected Option
.select2-container--krajee .select2-selection{
   font-family:Roboto, sans-serif !important;
}

For the Drop-down Options
.select2-container--krajee .select2-results__option{
   font-family:Roboto, sans-serif !important;
}

Changing Font color/size
For the Selected option
.select2-container--krajee .select2-selection--single .select2-selection__rendered{
    color:red !important;
}

For the Default Placeholder
.select2-container--krajee .select2-selection--single .select2-selection__placeholder{
    color:red !important;
}

For changing the color for the dropdown option the same class is used that is listed for the font-family option in the first section on top, i.e .select2-container--krajee .select2-results__option.
Hope it helps
Answer: you can add style to it like follows:
<?= $form->field($model, 'my_number')
->widget(Select2::classname(), [
    'items' => ['One' => 'One', 'Two' => 'Two', 'Three' => 'Three'],
    'class' => 'form-control',
    'options' => ['style' => 'font:yourfontfamilly'],
]) ?>

Comment: In this way, you are changing the style of the hidden element. Why do you need to change the style of something you can't see?


PHP Number Format with a calculation

Question: I am still relatively new at this so I am sorry if this seems like an easy fix, I am doing a calculation and I want the answer to present 2 numbers after the decimal. Right now it is giving me the results above my table and not replacing the numbers in the table.
http://www.cnghl.biz/cnghldb/cnghlgoalieinfo.php?GoalieID=71
This is what I currently have set up
    Print "
";
Print "".$row['Sea']."	 ";
Print "".$row['Team']."	 ";
Print "".$row['GP']."	 ";
Print "".$row['Min']."	 ";
$iGAA = $row['GA'] * 60 / $row['Min'];
Print $english_format_number = number_format($iGAA, 2);
Print "".$iGAA."	 ";
Print "".$row['W']."	 ";
Print "".$row['L']."	 ";
Print "".$row['OTL']."	 ";
Print "".$row['T']."	 ";
Print "".$row['SO']."	 ";
Print "".$row['GA']."	 ";
Print "".$row['SA']."	 ";
Print "".$row['PCT']."	 ";
Print "".$row['PIM']."	 ";
Print "".$row['Assists']."	 ";

}
Could you please show me how to fix it, so I can get the correct answer, thanks.
Answer: You are printing the wrong variable:
Print "".$english_format_number."	 ";

PHP Number Format with a calculation


Why composer was designed to work with two files: composer.json and composer.lock, instead of one

Question: I want to create my own package manager, and currently reviewing existing solutions.
I'm playing with PHP's Composer now, and it was quite surprising that it has two files:

composer.json for project configuration, and non-pinned dependencies
composer.lock for exact pinned dependencies

I do understand why one needs to pin dependencies, .lock information by itself seems logical to me.
What I do not understand is why project metadata was split into two files.
Can anyone explain, why it was designed this way? Why deps could not be pinned right in the composer.json?
UPD. Turns out, Rust's Cargo has the same two file configuration in place, and has a nice explanation of the meaning of the .lock file: http://doc.crates.io/guide.html#cargotoml-vs-cargolock
Comment: http://stackoverflow.com/questions/10674641/composer-lock-how-does-it-work
Comment: Still don't understand. So, if I'm using project as a standalone app, I'm using `.lock` and I'm happy with it.
When I'm using project as a third-party app, I'm not using it's own `.lock`, but info that is placed in the `.json` to install library dependencies, right?
Answer: During development, you usually want to be able to upgrade to the latest compatible version of dependencies easily. composer.json has the information on what the dependencies are and which versions are compatible. composer.lock lacks the compatibility information, it may say that the package was built against version 2.2.7 of a dependency but information is missing about rules such as that versions >= 2.1 and < 3 of that dependency are compatible while lower versions aren't and the next major version isn't guaranteed to be so play it safe.
When building for testing or release, on the other hand, it's necessary to make sure you build against the exact same set of dependency versions every time. composer.lock allows that by listing out the exact versions used. Even if new versions of dependencies come out, the dependency pinning insures that the build won't change so you won't have to worry about changes in behavior caused by changes in dependency packages.
Answer: .lock information is absolutely pinned, typically created by a composer update request based on the json information... but developers don't necessarily want to pin everything to an exact version, and without that .json file they have to upgrade the .lock file manually for every version upgrade of their dependencies.
The .lock also holds dependencies of dependencies, and dependencies of dependencies of dependencies, etc... whereas the .json file only holds immediate dependencies.... and as a developer, you should only need to control your immediate dependencies, and allow those libraries to control their own dependencies via their own .json files
Basically, you should build your application against the json but deploy against the .lock


T-SQL BEGIN TRANSACTION and COMMIT within a WHERE Loop fails when deleting records

Question: The following code is designed to loop through and delete transactions by the month. However, it did not perform in the manner that I expected. I was expecting the COMMIT to occur after each DELETE.
The routine failed when it ran out of log space and rolled back ALL of the transactions that it deleted. The COMMIT did not perform in the manner that I was expecting. In an effort to control the log space I assumed the COMMIT within the loop would COMMIT each monthly delete and therefore, prevent the log space from over filling.
DECLARE @MaxPostDate AS DATE = '2021-01-31'
DECLARE @MinPostDate AS DATE = '2019-07-01'

DECLARE @NbrOfMonthsToMaintain As INT = 13

WHILE @NbrOfMonthsToBeDeleted >= 0
BEGIN

    SELECT @NbrOfTransactions = COUNT(*)
    FROM [dbo].[Transaction] f
    WHERE f.[PostDate] BETWEEN @StartingDeleteDate AND EOMONTH(@StartingDeleteDate)

    PRINT 'Delete ' + FORMAT(@NbrOfTransactions,'N0') + ' transactions between '
                    + CAST(@StartingDeleteDate As VARCHAR(20)) + ' AND '
                    + CAST(EOMONTH(@StartingDeleteDate) AS VARCHAR(20))

        BEGIN TRANSACTION

            DELETE f
            FROM [dbo].[Transaction] f
            WHERE f.[PostDate] BETWEEN @StartingDeleteDate AND EOMONTH(@StartingDeleteDate)
            AND f.[PostDate] <= @DeleteToDate

        COMMIT TRANSACTION

        INSERT INTO [app].[DataDeletionHistory](
             [DataType]
            ,[Description]
            ,[DateDeleted]
            ,[MonthDeleted]
            ,[RowsDeleted])
        SELECT 'Transactions'    As DataType
           ,'Delete'             As [Description]
            ,GetDate()           AS DateDeleted
            ,@StartingDeleteDate AS MonthDeleted
            ,@NbrOfTransactions  AS RowsDeleted

    SET @StartingDeleteDate = DATEADD(m,1,@StartingDeleteDate)
    SET @NbrOfMonthsToBeDeleted = @NbrOfMonthsToBeDeleted - 1

END;

Following are the results:
Delete 15,183,513 transactions between 2019-07-01 AND 2019-07-31

(15183513 rows affected)

(1 row affected)
Delete 14,999,308 transactions between 2019-08-01 AND 2019-08-31

(14999308 rows affected)

(1 row affected)
Delete 14,292,165 transactions between 2019-09-01 AND 2019-09-30

(14292165 rows affected)

(1 row affected)
Delete 15,365,025 transactions between 2019-10-01 AND 2019-10-31

(15365025 rows affected)

(1 row affected)
Delete 14,576,586 transactions between 2019-11-01 AND 2019-11-30

(14576586 rows affected)

(1 row affected)
Delete 15,316,013 transactions between 2019-12-01 AND 2019-12-31

(15316013 rows affected)

(1 row affected)
Delete 15,453,046 transactions between 2020-01-01 AND 2020-01-31

(15453046 rows affected)

(1 row affected)
Delete 14,408,066 transactions between 2020-02-01 AND 2020-02-29

Msg 9002, Level 17, State 4, Line 50
The transaction log for database 'MyDatabase' is full due to 'ACTIVE_TRANSACTION'.
Msg 9002, Level 17, State 4, Line 1
The transaction log for database 'MyDatabase' is full due to 'ACTIVE_TRANSACTION'.
Msg 3314, Level 21, State 3, Line 1
Comment: FYI, you don't need an explicit transaction since each delete is automatically committed by default. Add a TRY/CATCH to stop processing after an error. It may be you previously left a transaction open and did not rollback after a previous error. Add SET XACT_ABORT with batches with explicit transactions to ensure a rollback.
Comment: Side note, if you want to know how many rows you have deleted, I would strongly recommend against doing a `COUNT` before hand; you're hitting the table twice which will likely really slow your query down. Why not `PRINT` *after* the `DELETE` and include the value of `@@ROWCOUNT`?
Comment: There is no point in having an explicit transaction around a single statement. Also if it rolled back all of the deletes presumably there is an outer transaction anyway.
Comment: We are configured as a **SIMPLE** database
Comment: Dan, I am not familiar with the approach of SET XACT_ABORT OFF that you are suggesting (I am a rookie SQL coder) How can I see what the current state is of XACT_ABORT prior to setting it to OFF?
Comment: @Elroy, I recommend `SET XACT_ABORT ON` in T-SQL scripts/procs with explicit transactions so that the transaction is rolled back immediately in the event of an error or timeout. You don't need to check if it's already set. Additionally, I suggest a standard catch block of `BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK; THROW; END CATCH;`
Comment: Thanks Dan, that is clear.  I will apply your suggestions.
Answer: Check  it,
DECLARE @MaxPostDate AS DATE = '2021-01-31'
DECLARE @MinPostDate AS DATE = '2019-07-01'

DECLARE @NbrOfMonthsToMaintain As INT = 13
begin try

SET NOCount ON
SET XACT_ABORT ON
WHILE @NbrOfMonthsToBeDeleted >= 0
BEGIN

    --SELECT @NbrOfTransactions = COUNT(*)
    --FROM [dbo].[Transaction] f
    --WHERE f.[PostDate] BETWEEN @StartingDeleteDate AND EOMONTH(@StartingDeleteDate)

    set @StartingDeleteDate=EOMONTH(@StartingDeleteDate)

        --BEGIN TRANSACTION

            DELETE f
            FROM [dbo].[Transaction] f
            WHERE (f.[PostDate]>= @StartingDeleteDate AND f.[PostDate]<= @StartingDeleteDate)
            --AND f.[PostDate] <= @DeleteToDate

        --COMMIT TRANSACTION

        @NbrOfTransactions =@@RowCount

         PRINT 'Delete ' + FORMAT(@NbrOfTransactions,'N0') + ' transactions between '
                    + CAST(@StartingDeleteDate As VARCHAR(20)) + ' AND '
                    + CAST(@StartingDeleteDate AS VARCHAR(20))

        INSERT INTO [app].[DataDeletionHistory](
             [DataType]
            ,[Description]
            ,[DateDeleted]
            ,[MonthDeleted]
            ,[RowsDeleted])
        SELECT 'Transactions'    As DataType
           ,'Delete'             As [Description]
            ,GetDate()           AS DateDeleted
            ,@StartingDeleteDate AS MonthDeleted
            ,@NbrOfTransactions  AS RowsDeleted

    SET @StartingDeleteDate = DATEADD(m,1,@StartingDeleteDate)
    SET @NbrOfMonthsToBeDeleted = @NbrOfMonthsToBeDeleted - 1

END
end try
begin catch
if(@@ROWCOUNT>0)
Rollback;
Throw;
end catch

You can als use Output Deleted to know the count(*)
You can also play with Primary Key of tblTransaction to do bulk delete or batch delete.
Link 1
Link 2
Link 3


HTML Grid with circles in intersections

Question: I'm going to implement the below image in HTML, it is for a Tic-Tac-Toe game.
But I have no idea how to add the circles both for slots and dies.
The board size is dynamic (not always 3x3).
I think it can be done with the ::before or ::after pseudo-elements, but how do I find the intersections?

UPDATE
I made this (check the code at jsfiddle).
Now I need to draw line between circles both horizontal and vertical.
Any ideas here?

Update 2
I did it! (check the code at jsfiddle).
Thanks for your helps. <3
Comment: Since you know the center and the sides, I presume, you could use a relative positioned container with absolute positioned pieces, with CSS [calc](https://developer.mozilla.org/en-US/docs/Web/CSS/calc()).
Comment: because it is isometric, i thinks you can use (`left + n * interval`) to get the value of `margin-left` in px and use `position: absolute`
Comment: @StackSlave I updated my question and did what you said, now how to add the lines?
Answer:

#board {
            display: flex;
            width: 500px;
            height: 500px;
            background: antiquewhite;
            padding: 100px;
            flex-direction: column;
            justify-content: space-between;
        }

        #board > div {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        #board > div > div,
        #board > div > div.white,
        #board > div > div.black {
            height: 10px;
            width: 10px;
            display: block;
            border-radius: 50%;
            background: black;
        }

        #board > div > div.white::after {
            content: "";
            height: 100px;
            width: 100px;
            display: block;
            border-radius: 50%;
            top: -50px;
            position: relative;
            left: -50px;
            background: white;

        }

        #board > div > div.black::after {
            content: "";
            height: 100px;
            width: 100px;
            display: block;
            border-radius: 50%;
            top: -50px;
            position: relative;
            left: -50px;
            background: black;
        }

How about something like this?
Comment: Thank you for the code, it has a problem: the background color must be inside the circles not outside. I updated my question with my solution, but I need help drawing the lines between circles. Thanks again. <3
Answer: My suggestion
using jquery or javescript build div with attributesborder-radius in css to draw the circle
then, set the margin-left to that div by left + n * interval and position: absolute
Comment: Can you please show me with code? I have updated my question and provided my code. Thanks.

HTML Grid with circles in intersections


CouchDB Design Doc...Save Failed: Expression Does Not Eval To a Function

Question: So I'm trying to create a design doc in CouchDB and there's a slight problem. This is for a robotics team scouting system. The design doc is supposed to check if a user has the role "marea". If they do, then they are allowed to input a document into the database. Then the design doc should take the JSON field "points" and average it if the "team" fields match. The averaged value should be merged back into the database. If the user does not have the "marea" role, then they should be restricted from inputting any docs. Please let me know what you think of the below code, and I would also like some advice on the error message I get. I'm able to save the design doc just fine, but its functioning is a little iffy. It prevents the user from creating a new doc with a "points" value even when that user has the role "marea". The exact error message is:
Save failed: Expression does not eval to a function. (function(newDoc, oldDoc, userCtx, secObj) { if ((userCtx.roles.indexOf("2018marea") !==
-1) || (userCtx.name == oldDoc.name)) { if (!doc) { if ("id" in req && req["id"]) { return [{"_id": req["id"]}, "New Doc"] emit(null, "points") var pointsArray = ["points"], thisTotal = 0, thisAverage = 0; for(var i = 0;i < pointsArray.length; i++) { thisTotal+ = pointsArray[i]; } thisAverage = (thisTotal/pointsArray.length); } return [null, "Empty Database."] } doc["New Doc"] = thisAverage; doc["edited_by"] = req["userCtx"]["name"] return [doc, "Edited Data."] } else { return [null, "Cannot Overwrite Data"] } } )

How do I fix this problem so that the design doc carries out its intended function?
{
  "_id": "_design/marea",
  "language": "javascript",
  "validate_doc_update": "function(newDoc, oldDoc, userCtx, secObj) {\r\n\r\n    if ((userCtx.roles.indexOf(\"2018marea\") !== -1) || (userCtx.name == oldDoc.name)) { \r\n    \r\n        if (!doc) {\r\n        \r\n            if (\"id\" in req && req[\"id\"]) {\r\n            \r\n                return [{\"_id\": req[\"id\"]}, \"New Doc\"]  \r\n                emit(null, \"points\")\r\n                var pointsArray = [\"points\"], thisTotal = 0, thisAverage = 0;\r\n                for(var i = 0;i < pointsArray.length; i++)  {\r\n                \r\n                  thisTotal+ = pointsArray[i];\r\n                \r\n                }\r\n                \r\n                thisAverage = (thisTotal/pointsArray.length); \r\n                \r\n            }\r\n            \r\n            return [null, \"Empty Database.\"]\r\n            \r\n        }\r\n        \r\n        doc[\"New Doc\"] = thisAverage;\r\n        doc[\"edited_by\"] = req[\"userCtx\"][\"name\"] \r\n        return [doc, \"Edited Data.\"]  \r\n\r\n    } else {\r\n    \r\n        return [null, \"Cannot Overwrite Data\"]\r\n   \r\n    }\r\n  } "
}

Answer: The error is pretty obvious: You function is not valid

There's a space between + = : { thisTotal+ = pointsArray[i]; }
You forgot some semi colon between few statements:

"New Doc"] ; emit(null, "points"); var pointsArray
This should work better:
function(newDoc, oldDoc, userCtx, secObj) {
  if ((userCtx.roles.indexOf("2018marea") !==  -1) || (userCtx.name == oldDoc.name)) {
    if (!doc) {
      if ("id" in req && req["id"]) {
        return [{
          "_id": req["id"]
        }, "New Doc"];emit(null, "points"); var pointsArray = ["points"],
          thisTotal = 0,
          thisAverage = 0;
        for (var i = 0; i < pointsArray.length; i++) {
          thisTotal += pointsArray[i];
        }
        thisAverage = (thisTotal / pointsArray.length);
      }
      return [null, "Empty Database."]
    }
    doc["New Doc"] = thisAverage;
    doc["edited_by"] = req["userCtx"]["name"]
    return [doc, "Edited Data."]
  } else {
    return [null, "Cannot Overwrite Data"]
  }
}


clarification over the negation for the definition of topological embedding

Question: For the following question:
Let $\text{~}$ be the smallest relation on $\mathbb{R}$ defined by $x\text{~}y$ if $x$ and $y$ are integers.  Then the quotient space $\mathbb{R}/\text{~}$ is not embeddable in $\mathbb{R}^2$
I would like to know how to formulate in mathematical language what it means for one space $X$ to not be embeddable in $Y$.  I know that the definition of embedding from one space to another in terms of homeomorphism and subspace topology are as follows:
Definition: Let $(X,\mathcal{T})$ and $(Y,\mathcal{U})$ be topological spaces.  If $(A,\mathcal{U}_A)$ is a subspace of $(Y,\mathcal{U})$ and $f:(X,\mathcal{T})\rightarrow (A,\mathcal{U}_A)$ is a homeomorphism, then $X$ is said to be embedded in $Y$  and $f$ is called an embedding of $X$ in $Y$.
and also, according to the following proposition on embedding (from K.D.Joshi's Introduction to General Topology Text)
Proposition:  A function $f:X\rightarrow Y$ is an embedding iff it is continuous and one-to-one and for every open set $V$ in $X$, there existss an open subset $A$ of $Y$ such that $f(V)=A\cap Y$
So for a space $X$ to not be embeddable into another space $Y$, does it involve a non exsistence of a homeomorphic mapping $f$ from $X$ to $f(X)$ but also, $f(V)\neq A\cap Y$, for some $V \subset X$ and some $A \subset Y$
Thank you in advance
Comment: It just means that no map $X\to Y$ is an embedding.
Comment: The Proposition is a simple reformulation of the Definition. So what is your question?
Comment: @PaulFrost, i am trying to understand how to express precisely what it means for one space to not be embeddable into another.  The way the definition seems to be a bit complicated involving many quantifiers.
Comment: For some (any) property P, a space Y is called hereditarily P if every subspace of Y (including Y itself) has property P.  A property P is called a topological property if X' has property P whenever X' is the homeomorphic image of a space X that has property P.... Being not-first-countable is a topological property. And $\Bbb R^2$ is hereditarily first-countable.
Comment: An exception to the def'n of hereditarily P is made when P is the property of being disconnected. A space X is hereditarily disconnected if X is disconnected and every subpace of X with at least 2 members is disconnected.
Answer: $X$ is embeddable in $Y$ iff $X$ is homeomorphic to a subspace of $Y$.
So its negation can be formulated as "no subspace of $Y$ is homeomorphic to $X$".
Which in this case is easy to see, as (e.g.) all subspaces of $\Bbb R^2$ are first-countable while $\Bbb R{/}\text{~}$ is not first-countable.
Comment: thank you for your response.  When you say no subspace of $Y$ is homeomorphic to $X$, does it mean the following:  if we assign a topology $T$ to $Y$, and for any $A\subset Y$, with  $T_A = A\cap O$ for some open set $O \in T$, $f(T_A)$ is not homeomorphic to $X$.
Comment: No, @SethMai we don't assign a topology to $Y$, it already *has* a topology $\mathcal{T}_Y$, and then for all $A \subseteq Y$, there is no homeomorphism between $X$ (in its pregiven topology) and $A$ in the subspace topology $\{A \cap O: O \in \mathcal{T}_Y\}$. You statement makes no sense at all.
Comment: I was trying understand and formulate how embedding can fail..  After looking at the proposition,  There seems to be more than one conditions that could make one space not be embedded in another.  I am glad you can clarify it for me.  Thank you again.


Sorting a Rails active record

Question: I have a table A(:name, :address, :country_id). I run this query
ids = [1,2,3]
@result = A.where(country_id: ids)

But, I want to get the results in this order : records containing country_id = 2 first, then 1 and then 3.
How should I write this query?
Edit :
@people = []
@result.each do |r|
  @people.push([r,r.name])
end

I have an array @people of arrays now and want to sort it. What should be the query now?
Another Edit :
@people.sort_by! {|p| preferred_order.index(p.first.country_id)}

This worked.
Comment: More information is needed: why are you doing this? Are there always 3 results?
Comment: There are many results. I want to display results in such an order that the rows containing country_id = 2 are displayed first, then 1 and then 3
Answer: You can use sort_by :
ids = [1,2,3]
preferred_order = [2,1,3]

@result = A.where(country_id: ids)
@result.sort_by! { |u| preferred_order.index(u.country_id) }

Comment: What if I have copied my 'result' into an array 'people'. What should I do now?
Comment: Then try `@people.sort_by! { |u| preferred_order.index(u.country_id) }` and let me know.
Answer: One option would be adding an extra column
 rails g migration add_sortorder_to_A sort_order:integer

Then add a
before_save :update_sort_order

def update_sort_order
  if self.country_id == 1
    self.update_attributes(sort_order:2)
  elsif self.country_id ==2
    self.update_attributes(sort_order:1)
 ........
end

Alternatively, put your sort_order in the countries and sort on that.
Alternatively, create a dynamic field which will give you the sort_order.
There is probably a more elegant way of doing this, but this should work in a quick and dirty way and allow you to use standard activerecord queries and sorting. (i.e. you can just forget about it once you've done it the once)
Comment: Alternatively, do what Sharvy said. Much more elegant... :)

Sorting a Rails active record


How do you enable Big Head mode?

Question: In Batman: Arkham City, there is apparently a secret big head mode. How is that mode enabled on each platform?
Answer: Kotaku describes how to access this easter egg:

It's very easy to do. You have to [have finished the game] on normal or hard, or on New Game+ (Which you can't unlock by completing the game on easy, anyway.) At any point in the game, take out Batman's Cryptographic Sequencer.  While holding down both RT and LT (or, I presume, R2 and L2 on PS3), begin to rotate your left thumbstick clockwise and your right thumbstick counter-clockwise. After doing that for a few seconds, you'll notice that the Dark Knight's chin has gotten a good deal…chinnier.

You can also watch the Rooster Teeth video (great channel for achievements and easter eggs, by they way!):

On the PC, it's a bit different.  You don't seem to need the cryptographic sequencer.  The key combination is:

U,U,U,D,D,D,L,L,R,L,L,U,U,D

or in WASD:

W,W,W,S,S,S,A,A,D,A,A,W,W,S

And here's a video:

How do you enable Big Head mode?


Flash of Unstyled Content (FOUC) for Nextjs using Mantine

Question: I switched to Mantine and followed this approach to solve the FART (Flash of inAccurate coloR Theme), but the webpage runs into a new issue. There is a flash of Unstyled component before the page renders. How to solve this issue?
I looked into Nextjs Github and there were issues few FOUC issues, but the solution was to add , which didn't work for me.
This bug is only in production, in development it works fine.
Example: https://gotrip.vercel.app
If you don't see the flash, copy the link and paste it in the browser.
import Document, { Html, Head, Main, NextScript } from "next/document";
import { createGetInitialProps } from "@mantine/next";

const getInitialProps = createGetInitialProps();

export default class _Document extends Document {
    static async getInitialProps(ctx) {
        const initialProps = await Document.getInitialProps(ctx);
        return { ...getInitialProps, ...initialProps };
    }

    render() {
        const setInitialTheme = `
      function getUserPreference() {
        if(window.localStorage.getItem('theme')) {
          return window.localStorage.getItem('theme')
        }
        return window.matchMedia('(prefers-color-scheme: dark)').matches
          ? 'dark'
          : 'light'
      }
      document.body.dataset.theme = getUserPreference();
    `;
        return (


How do i parse .txt file contents with txt and ids to a dictionary in python?

Question: Below is a text file content with no header or quotes for the text data. How do i parse these in a dictionary.Each record in my file is on a new line Below is my text file content:
B00308CJ12 Bulletproof Salesman (2008)
189138922X Classical Mechanics
B0000CEP9J Fiesta Black 464 7-1/4-inch Salad Plate
B000HRH6IA Baby Blue Aurora Blue Gem Butterfly Belly Ring
B000002ERY Predicciones Leo

Using the code below is giving me an error. I am assuming that's because my sentences are not in quotes. What do i do to rectify and put these values in a dict
 f = open('file_path', 'r')
    answer = {}
    for line in f:
        k, v = line.strip().split(' ')
        answer[k.strip()] = v.strip()

    f.close()

ERROR:

k, v = line.strip().split(' ')
ValueError: too many values to unpack (expected 2)

Edit after changes to code
 f = open('file_path', encoding="utf8")
    answer = {}
    for line in f:
        k, v = line.strip().split(' ')[0],line.strip().split(' ')[1:]
        answer[k] = v

    f.close()

Error :

File "C:\ProgramData\Anaconda3\lib\codecs.py", line 321, in decode
      (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xae in position
  1266: invalid start byte
Comment: Are you intending to get `{'B00308CJ12':'Bulletproof Salesman (2008)',...}`? ie, each key on the left is then the unbroken string on the right?
Comment: Yes but my code is giving me something like this {'B00308CJ12':['Bulletproof', 'Salesman', '(2008)']}... That seems to be the issue
Answer: Replace
k, v = line.strip().split(' ')

with
k, v = line.strip().split(' ')[0],line.strip().split(' ')[1:]

Your sentences have spaces in them, so you are getting more values than you are expecting
Answer: The line line.strip().split(' ') actually splits each line of your text file into a list with the space character ' ' as delimiter producing an output like this one for the first line ['B00308CJ12', 'Bulletproof', 'Salesman', '(2008)']. At this point if you want to create a dictionary, you need to decide what you want as key and value in your dictionary and get those values from the list using their corresponding indexes
Update about encoding
try reading the file with this line
f = open('file_path', encoding="utf8")

And to have 'Bulletproof Salesman (2008)' as value you can use the join function
k, v = line.strip().split(' ')[0], " ".join(line.strip().split(' ')[1:])

Comment: Yeah i did and its throwing a error after half of my file was parsed as a dict  >>> File "C:\ProgramData\Anaconda3\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 4062: character maps to
Comment: What are you using as key? Can you update your original question with the new version of your code. Otherwise it will be hard to help. But this looks to me like a character encoding issue
Comment: i am taking the id as key and the sentence as value. i have updated the original question with the changes made and the error
Comment: as I expected it is a character encoding error. try reading the file specifying an encoding method like utf-8. See my updated answer
Comment: That throws a succeeding error - updated question again
Answer: If you want {'B00308CJ12':'Bulletproof Salesman (2008)',...}
Try this:
di={}
with open(fn) as f_in:
    for line in f_in:
        k,v=line.split(sep=None,maxsplit=1)
        di[k]=v.rstrip()

>>> di
{'B00308CJ12': 'Bulletproof Salesman (2008)',
 '189138922X': 'Classical Mechanics',
 'B0000CEP9J': 'Fiesta Black 464 7-1/4-inch Salad Plate',
 'B000HRH6IA': 'Baby Blue Aurora Blue Gem Butterfly Belly Ring',
 'B000002ERY': 'Predicciones Leo'}

Answer: All answers put together the below code worked like a charm for the intended ie {'B00308CJ12': 'Bulletproof Salesman (2008)','189138922X': 'Classical Mechanics', ......}
Thanks all!!
answer = {}
with open('filepath','rb') as f:
    for line in f:
        k, v = line.strip().split(sep=None,maxsplit=1)[0],line.strip().split(sep=None,maxsplit=1)[1:]
        answer[k] = v
f.close()

Comment: Note: 1) `f.close()` is not necessary when you use `with` to open the file. 2) You are performing a second split unnecessarily with `k, v = line.strip().split(sep=None,maxsplit=1)[0],line.strip().split(sep=None,maxsplit=1)[1:]` You can just use tuple unpacking with `k,v=line.strip().split(maxsplit=1)` and `k` and `v` will get the proper values automatically.
Comment: not doing the second split is giving me an error >>k,v=line.strip().split(maxsplit=1)

ValueError: not enough values to unpack (expected 2, got 1)


How to set text property on keyDownHandler on TextInput in Flex 3

Question: Simple and straight forward.
I extended a mx.controls.TextInput to create a custom component with a different behavior.
I'm trying to set the text property on the keyDownHandler(), and for some reason it doesn't work as I expected. The text on the component just kinda ignore the change.
I'm using Flex 3.6.
Down here is a simple example code that explains what's going on:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:customcomponent="com.test.customcomponent.*">
    <customcomponent:TextTest x="20" y="20"/>
</mx:Application>

And below de AS class:
package com.test.customcomponent
{
    import flash.events.KeyboardEvent;

    import mx.controls.TextInput;

    public class TextTest extends TextInput
    {
        public function TextTest()
        {
            super();
        }

        override protected function keyDownHandler(event:KeyboardEvent):void{
            text = "lol. It doesn't work";
        }
    }
}

Answer: You need to prevent the default key down event.
    override protected function keyDownHandler(event:KeyboardEvent):void{
        text = "lol. It doesn't work";
        event.preventDefault();
        event.stopImmediatePropagation();
        event.stopPropagation()
    }

Comment: Tried that, didn't work..
For some reason, whenever I press CTRL, SHIFT or TAB key it works properly...
Answer: In order to be able to prevent the default handling, you have to have a high enough priority on your handler (which keyDownHandler() does not have). This means you need to register your own method with priority > 0.
You can try like this:
public function MyTextInput() {
    addEventListener(KeyboardEvent.KEY_DOWN, yourHandler,
                     false, EventPriority.BINDING, true);
    ...
}

private function yourHandler(event : KeyboardEvent) : void {
    // stop further handling
    event.preventDefault();
    event.stopImmediatePropagation();
    event.stopPropagation();

    // do your work here
    text = ...;
}


Is there a way to remove an allied Pokémon in a gym?

Question: Near me, there are a couple of gyms at max level and I was wondering if there is a way to remove an allied Pokémon in those gyms and put my pokémon? Of course, without creating another account on another team, reducing prestige and then using my main account to reach the max level again.
Comment: There's no "i" in team.
Comment: ...but there is a "me".
Answer: No you cannot remove another person's Pokemon if they are in your faction.


Retreiving the child projects and updating the parent for the selected projects in Rally using API

Question: In order to clean up Rally I want to change the parent for projects which are marked as "Closed"
--MyWorkspace
  - Project 1
  - Project 2
    - Child 1 (Status = Closed)
    - Child 2 (Status = Closed)
    - Child 3 (Status = Open)
  - Project 3

I want to update the parent of "Child 1" and "Child 2" to "Project 1" (Want to move those child projects under different parent.
import sys
from pyral import Rally, rallyWorkset
options = [arg for arg in sys.argv[1:] if arg.startswith('--')]
args    = [arg for arg in sys.argv[1:] if arg not in options]
server = <server>
apikey = <api_key>
workspace = <workspace>
project = <project_name>
rally = Rally(server,apikey=apikey, workspace=workspace, project=project)
rally.enableLogging('mypyral.log')

I am using below method to check all the projects under the required workspace
projects = rally.getProjects(workspace=workspace)
for proj in projects:
    print ("    %12.12s  %s  %s" % (proj.oid, proj.Name, proj.State))

This gives me parent level projects only
<id> <Name>  <status>

This logic doesn't return all the child projects though.
Also I am looking for post method to update the parents once I get the list of projects I want to close.
Answer: That's correct - projects = rally.getProjects(workspace=workspace) returns all Parents projects.
In order to get all children Projects you need to ask about it parent:
for proj in projects:
children = proj.Children
for child in children:
    print ("    %12.12s  %s  %s" % (child.oid, child.Name, child.State))

The entire task i would solve in the following way:
#get object for 'New Parent':
target_project = rally.getProject('NewParentForClosedProjects')

projects = rally.getProjects(workspace=workspace)
for proj in projects:

    #get children of project
    children = proj.Children

    for child in children:

        #if project closed:
        if child.State == 'Closed':
            #Then update Parent to new one:
            project_fields = {
                "ObjectID": child.oid,
                "Parent": target_project.ref
            }
            try:
                result = rally.update('Project', project_fields)
                print "Project %s has been successfully updated with new %s parent" % (str(child.Name), str(child.Parent))
            except RallyRESTException, ex:
                print "Update failure for Project %s" % (str(child.Name))
                print ex


What is better for REST API? WCF Web API (Preview 4) or OpenRasta or something else?

Question: I see in this question that WCF Web API is still in preview and I've just started looking at OpenRasta.
Though OpenRasta looks more mature than WCF Web API, I'm still a bit confused. Or please suggest if there is any other better framework for building REST API on .NET stack.
Also, I observed that in OpenRasta aspx view containing HTML can also be rendered as a response (in ASP.NET MVC fashion) apart from other JSON/XML representations. So, is it that I can even (or it is recommended that I should) build a web application which will also serve as a service layer to 3rd party client developer using it? Or it is just for use as a service layer?
Answer: OpenRasta is much more mature than WCF Web API.  OpenRasta is an opinionated REST framework.  WCF Web API currently has no opinions on how you should do REST, it only has opinions on how you use HTTP.
If you share OpenRasta's opinions on how to do REST then it will do a great job for you.  WCF Web API is still a preview.  It has great potential but there is still a long way to go.
Comment: Thanks very much Darrel. This is much helpful. What about the other question related to view for rendering HTML?
Comment: How about the rest options in standard WCF 4.0. Would be interested to see peoples opinion. Why not use what comes out of the box? It seems quite straightforward : http://stackoverflow.com/questions/186631/rest-soap-endpoints-for-a-wcf-service
Answer: please read a closed question

OpenRasta vs FubuMVC vs Asp.net MVC just some thoughts

Video with the question and answers, use the PAUSE to hold the scroll and read it.

http://gape.cc/jz822d

--
Err, It's been deleted though I can see deleted questions, let me make a screenshot of it.
Comment: I think question is deleted now.
Answer: OpenRasta works for both services and html sites, it's what it was built for. There's codecs for webforms, razor, sparkview and new ones are easy enough to just plugin.
Comment: Thanks Sebastian for the answer. So if I was to create a website and then expose everything what my website does through an API (obviously securely via oAuth etc.), so is it recommended that I do it using one code base of OpenRasta project? Is it practical? By practical I mean, can I make an intuitive ajax based website restfully and then use the same Get, Post, Put, Delete operations for exposing API to third party developers? I know this much by now that using "accept" header, a client can get response either in XHTML or JSON.
Comment: well yes you certainly could do that, but usually a web page rarely  has the exact same dataset as the json or xml you  may send to clients, so they usually live at different URIs. The point of OpenRasta is that you have the same development model for both :)


How long do title revocation penalties last?

Question: I want to revoke a couple of vassal titles and would like to spread out the penalties over a longer period of time. How long does an individual revocation penalty last for, and does the game track each revocation individually or simply just reset the timer every time you revoke?
Answer: The penalty is -20, last for 5 years, and is applied to all of your direct vassals at the time of revocation. Each revocation is tracked separately. The penalty also only applies to the ruler, so once he dies the penalty doesn't pass on to his successor.


Merge two arrays without sorting using array

Question: I am trying to merge to arrays without sorting (add one then another) using pointer method but its just printing the first array and then garbage values. What i am trying to do is just combine 2 arrays in one big array. No sorting required(at least for now).
void getarray(int*,int);
int merge(int*,int*,int,int,int*);
main()
{
int a[10],b[10],c[20];
int i,j,n,m,size;
clrscr();
printf("Enter no. of elements in FIRST array: ");
scanf("%d",&n);
getarray(a,n);
printf("Enter no. of elements in SECOND array: ");
scanf("%d",&m);
getarray(b,m);
merge(a,b,n,m,c);
printf("\nMerged Array: \n");
for(i=0;i<n+m;i++)
{
    printf("\t%d\t",c[i]);
}
getch();
return 0;
}
void getarray(int *x, int y)
{
int i;
for(i=0;i<y;i++)
{
    scanf("%d",x+i);
}
}

int merge(int *a, int *b,int n,int m,int *c)
{
   int i,j;
for(i=0;i<n;i++)
{
    *(c+i) = *(a+i);
}
   for(j=i;j<i+m;j++)
   {
    *(c+j) = *(b+j);
   }
}

Comment: Hi. Asking people to spot errors in your code is not especially productive. You should use the debugger (or add print statements) to isolate the problem, by tracing the progress of your program, and comparing it to what you expect to happen. As soon as the two diverge, then you've found your problem. (And then if necessary, you should construct a [minimal test-case](http://sscce.org).)
Comment: You are beginning your index to b at n (instead of 0).  That can't be good.
Comment: @OliCharlesworth -- Well now I don't _want_ to post the answer I just found, since Devlin would learn so much more by finding it him/her-self.
Comment: dude i have tried all those stuff. i know the drill. still not getting picture. so please if you wanna help, go ahead.
Comment: And @OliCharlesworth dude i will try my best not to post a question before triple checking it. learned from the mistake.
Answer: Alternatively you can use (assuming c is large enough):
void merge(int *a, int *b,int n,int m,int *c) {
  memcpy(c,   a, sizeof(int)*n);
  memcpy(c+n, b, sizeof(int)*m);
}

You would need to include string.h.
Answer: int merge(int *a, int *b,int n,int m,int *c)
{
   int i,j;
for(i=0;i<n;i++)
{
    *(c+i) = *(a+i);
}
   for(j=0;j<m;j++)
   {
    *(c+n+j) = *(b+j);
   }
}

Comment: @Devlin  Don't worry about it.  Some of the SO people can be crabbykins.  We all have mistakes we miss that others can see clearly.  Happens all the time.
Comment: You were getting your indices confused on the second for loop.
Comment: thanks man. i am still learning. so pardon my rookie mistake.


spring bean creation for java builder pattern objects

Question: I'm using Google Gson(gson) library form reading/writing json files and spring mvc 3 in my web application side.
So In controller, I want to create a singleton instance of Gson with pretty printing. In java the code would be,
Gson gson = new GsonBuilder().setPrettyPrinting().create();

In Controller, I created an autowired entry as below,
@Autowired
private Gson gson;

and the xml bean configuration is as below,
<bean id="gsonBuilder" class="com.google.gson.GsonBuilder">
         <property name="prettyPrinting" value="true"/>
 </bean>
 <bean id="gson" factory-bean="gsonBuilder" factory-method="create"/>

It throws the following exception in catalina logs,
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'prettyPrinting' of bean class [com.google.gson.GsonBuilder]: Bean property 'prettyPrinting' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1024)
    at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:900)
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358)

I knew that the setter signature of setPrettyPrinting() is different than spring expects, that's why spring is throwing the exception.
  public GsonBuilder setPrettyPrinting() {
    prettyPrinting = true;
    return this;
  }

But I'm unable to find a way to wire the builder pattern beans. I'm pretty new to spring. Can any one let me know, whether it is possible to solve this problem in xml bean approach ?
Answer: Simply use a static factory method as described in the documentation and use Java code to create Java objects: it's sooo much easier and safe:
<bean id="gson"
      class="com.foo.bar.MyGsonFactory"
      factory-method="create"/>

and in MyGsonFactory:
public static Gson create() {
    return new GsonBuilder().setPrettyPrinting().create();
}

Answer: The setPrettyPrinting method doesn't take a parameter, so it doesn't look like a java bean property setter. That's why your approach didn't work. You can use the factory method mentioned in the other answer or use a method invoking bean in the config file like so:
 <bean id="myStarter" class="org.springframework.beans.factory.config.MethodInvokingBean">
   <property name="targetObject" ref="gsonBuilder"/>
   <property name="targetMethod" value="setPrettyPrinting"/>
 </bean>

The factory approach seems more straightforward and idiomatic to me, but I include this approach for the sake of completeness.
Comment: 1 Upvote for  suggesting the MethodInvokingBean approach. I never knew of this approach
Comment: Also if any one wants xml configuration only, they can use this approach. I liked it.


apt-get --force-yes: How to suppress further questions

Question: Take the acroread or libpam-ldap packages as examples.
Even when installed with apt-get --force-yes they still ask questions:

acroread wants to know whether acrobat should be the standard PDF reader (how to assume yes?)
libpam-ldap What's your LDAP-Servers URI, version, password, ...? (how to just assume anything, the ldap.conf will be overwritten by puppet anyway)

Is there a "for god's sake assume anything and stop nagging"-switch for apt-get?
Answer: Try:
export DEBIAN_FRONTEND=noninteractive
apt-get -y install package1 package2

Comment: Is `export DEBIAN_FRONTEND=noninteractive` needed or the `y` option in `apt-get` is sufficient?
Answer: Another solution: use yes command to blindly answer yes to all questions.
Apt is smart enough that this solution isn't recommended unless:

you know what you're doing, and
the -y and --force-yes options
don't do what you want

In my case, I want to downgrade Nginx, and I don't care about the dependencies. For some reason force-yes didn't work, nor did the DEBIAN_FRONTEND=noninteractive environment variable.
Here's how to downgrade a package noninteractively:
yes | apt install nginx-common=1.4.6-1ubuntu3.3 nginx-full=1.4.6-1ubuntu3.3


What stops water from stagnating in a gutter drain line that has a pop-up emitter?

Question: I'm planning on burying some rigid PVC pipe to attach guttering on my house to a few pop-up emitters like this:

But the pop-up emitter makes a right angle UP, so doesn't that mean that basically the entire buried pipe will remain filled with stagnating water? It seems like this would be normal but I'm not sure if this causes smell issues or any other adverse effects.
Comment: Are there any holes in the pipe? If not poke a few and any water will drain and not become stagnant.
Answer: I used a post hole digger and made a small leech pit right under the 90 on mine. Filled it with gravel and drilled a 3/8" hole in the bottom of the 90. After it rains the water can drain out and absorb into the dirt.
Comment: Great suggestion, sounds totally reasonable, thanks!
Comment: So.....when I say small I mean small in relative terms. Small for a typical leech line/field. I dug a hole 3' down and that seems to have worked fine over the last 6-7 years. I'm sure it will eventually clog with shingle silt and dirt, but will be relatively easy to dig back and start over with clean gravel.
Comment: The fittings are not watertight anyway, so even without holes the water eventually empties.
Comment: Do those right angle fittings have a knockout to make a hole?
Comment: Not that I've ever seen. Have to drill a hole in it.


makefile hangs when calling shell command head

Question: I want to print the first line of some text file from within my makefile.
Here's what I have, and it doesn't seem to work:
$ cat makefile
BASEDIR = ${HOME}/Downloads
MYDIR = ${BASEDIR}/ddd
all:
    var=${MYDIR}/m.txt
    @echo $(shell head -n 1 ${var})
#   @echo $(shell head -n 1 ${MYDIR}/m.txt)

When I try to use make it simply hangs and I have to kill it.
When I remove the comment and use the head command directly on ${MYDIR}/m.txt everything works fine. What am I doing wrong here? Thanks!
Comment: Tangentially, don't use `@` to silence `make`, especially while debugging. Once you know exactly what's going on, you probably want to use `make -s` if you don't want to see what's happening.
Comment: I prefer this method of dealing with recipe echoing: http://make.mad-scientist.net/managing-recipe-echoing/
Answer: Do not use the shell make function in recipes. Recipes are already shell scripts:
BASEDIR := $(HOME)/Downloads
MYDIR   := $(BASEDIR)/ddd

all:
    @var="$(MYDIR)/m.txt"; head -n 1 "$$var"

Notes:

Recipes are expanded by make before they are passed to the shell. This is where $(MYDIR) will be replaced by something like /home/doe/Downloads/ddd/m.txt. And this is why $var would not work. It would expand as ar, unless there is a make variable named v with a non-empty value FOO, in which case $var would expand as FOOar. $$var is expanded by make as $var, the shell syntax you want.
Each line of a recipe is executed by an independent shell. The following would thus not work:
all:
    @var="$(MYDIR)/m.txt"
    @head -n 1 "$$var"

because the shell variable assignment (var="/home/doe/Downloads/ddd/m.txt") and the shell variable expansion (head -n 1 "$var") would be executed by two different shells. If you want one single shell statement per line, use the line continuation:
all:
    @var="$(MYDIR)/m.txt"; \
    head -n 1 "$$var"

or:
all:
    @var="$(MYDIR)/m.txt" && \
    head -n 1 "$$var"

Comment: @tripleee: agreed. But I suspect the real Makefile will be different, at the end. So, let's show how to properly use shell variables in make recipes, it is always good to know.
Comment: @OrenIshShalom: you can... if you properly escape **all** `$` signs: `x=$$(head -n 1 "$$var"); echo "$$x"`.
Comment: It is of course dubious whether putting the string in a variable and only using it once is any use at all, but I'll just leave this comment here. (^8
Comment: how come I can't extend the solution to: `x=$(head -n 1 "$$var"); echo $$x'
Answer: Don't use variable assignments in recipes. In your command head -n 1 ${var} the expression ${var} expands to nothing and hence head waits on standard input. The following makefile should work:
BASEDIR = ${HOME}/Downloads
MYDIR = ${BASEDIR}/ddd
var=${MYDIR}/m.txt
all:
    @echo $(shell head -n 1 ${var})

Comment: You still want to avoid using `$(shell)` in the recipe. The [`echo` is also useless.](http://www.iki.fi/era/unix/award.html#echo)


Find the number of ways in which the number 30 can be partitioned into three unequal parts.(Please use multinomial theorem)

Question: OfLet $a,b,c$ be the parts such that $a<b<c$
Now, let $a−b=x,     b−c=y,$   implies     $x,y>0$
$⇒a+b+c=30\\
⇒(b+x)+b+c=30\\
⇒x+2(c+y)+c=30\\
⇒x+2y+3c=30$      ,
$c≤27$
Sum =30,Co-eff =$1,2,3$
$(x^1+x^2+.......)×(x^2+x^4+.......)×(x^3+x^6+.......+x^{27})$
Co-efficient of $x^{30}$ in the above product will give us the required answer.=$x×x^2×x^3×(1−x)^{−1}×(1−x^2)^{−1}×(1−x^3)^{−1}\\
 =x^6\times (1−x)^{−1}\times(1−x^2)^{−1}\times(1−x^3)^{−1}$
Please help me to understand the last ,how to find the coefficient of p^24 in those 3 brackes
Comment: Welcome to Math.SE. Please read [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question). [PSQs](https://math.meta.stackexchange.com/questions/33854/what-is-a-psq) (problem statement questions - where you just paste the problem and ask "what is the answer") do not belong on Math.SE. Consider adding context to the question such as what you've tried so far or what you're stuck on. Also, please use $\LaTeX$ to format your questions so they are readable.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: You are pretty much on the right track. The last part is pretty tedious, so it might be better that you just use Wolfram Alpha or possibly some other program. I think you defined your variables a little wrong. For example, if $a<b$, then $a-b<0$. However, you defined $x=a-b$, but you are saying that $x>0$. It looks like you're fine if you instead force $c<b<a$.
As you found before, we want to find the coefficient of $x^{24}$ in
$$\frac{1}{(1-x)(1-x^2)(1-x^3)}$$
Our goal will be to convert this into something of the form
$$\frac{P(x)}{(1-x^a)^b}$$
We can then use the fact that
$$\frac{1}{(1-x^a)^b}=\sum_{n=0}^\infty \binom{n+b-1}{b-1}x^{na}$$
to find the coefficient of $x^{24}$ in the resulting expansion. The most tedious part of this process is determining $P(x)$. We will start with some manipulations of
$$\frac{1}{(1-x)(1-x^2)(1-x^3)}$$
Note that $1-x, 1-x^2,$ and $1-x^3$ are all factors of $1-x^6$ (I think this would be called the LCM). Using this, we get
$$=\frac{(1+x+x^2+x^3+x^4+x^5)(1+x^2+x^4)(1+x^3)}{(1-x)(1+x+x^2+x^3+x^4+x^5)(1-x^2)(1+x^2+x^4)(1-x^3)(1+x^3)}$$
$$=\frac{(1+x+x^2+x^3+x^4+x^5)(1+x^2+x^4)(1+x^3)}{(1-x^6)^3}$$
$$=(1+x+x^2+x^3+x^4+x^5)(1+x^2+x^4)(1+x^3)\sum_{n=0}^\infty \binom{n+2}{2}x^{6n}$$
Well that was simple. However, the hard part is yet to come. We need to find the coefficient of $x^{24}$ in that expansion. Denote the product of the leftmost $3$ polynomials (the ones not in the summation) as $P(x)$. We will be finding the coefficient $x^{24}$ in the expansion of
$$P(x)\sum_{n=0}^\infty \binom{n+2}{2}x^{6n}$$
Since $\sum_{n=0}^\infty \binom{n+2}{2}x^{6n}$ only has terms of powers $0\mod 6$, we only care about the terms with power $0\mod 6$ in the expansion of $P(x)$. Although this doesn't help us too much, it does reduce some of the calculations. Expanding $P(x)$ while only caring about the final terms whose powers are $0\mod 6$ gives
$$P(x)$$
$$=(1+x+x^2+x^3+x^4+x^5)(1+x^2+x^4)(1+x^3)$$
$$=(1+x+x^2+x^3+x^4+x^5)(1+x^2+x^3+x^4+x^5+x^7)$$
$$\sim 1+x^6+x^6+x^6+x^6+x^{12}$$
$$=1+4x^6+x^{12}$$
So we only need to find the coefficient of $x^{24}$ in
$$(1+4x^6+x^{12})\sum_{n=0}^\infty \binom{n+2}{2}x^{6n}$$
$$\binom{4+2}{2}+4\cdot \binom{3+2}{2}+\binom{2+2}{2}$$
$$=15+40+6$$
$$=61$$
Indeed this matches what Wolfram Alpha gives (just click more terms on the taylor series expansion until you get to $x^{24}$)
Answer: Since, I'm learning a bit of residue theory, I want to try this solution out as well. We want to find the coefficient of $x^{-1}$ in the expansion of
$$f(x)=\frac{1}{x^{25}(1-x)(1-x^2)(1-x^3)}$$
$$f(x)=\frac{1}{x^{25}(1-x)^3(1+x)(1+x+x^2)}$$
This is just the residue at $0$. $f(x)$ also has residues at $1,-1,\omega,\omega^2,\infty$. Where $\omega$ is the third root of unity. We have
$$f(x)=\frac{-1}{x^{25}(x-1)^3(x-(-1))(x-\omega)(x-\omega^2)}$$
The residues at $-1,\omega,\omega^2$ are respectively
$$-\frac{1}{2^3}$$
$$-\frac{1}{9}$$
$$-\frac{1}{9}$$
The residue at $\infty$ is $0$. The residue at $1$ is
$$-\frac{1}{2}\lim_{x\to 1} \frac{d^2}{dx^2}\frac{1}{x^{25}(1+x)(1+x+x^2)}$$
$$=-\frac{1}{2}\lim_{x\to 1} \frac{d}{dx}-\frac{25(1+x)(1+x+x^2)+x(1+x+x^2)+x(1+x)(1+2x)}{x^{26}(1+x)^2(1+x+x^2)^2}$$
$$=\frac{1}{2}\lim_{x\to 1} \frac{d}{dx}\frac{25}{x^{26}(1+x)(1+x+x^2)}+\frac{1}{x^{25}(1+x)^2(1+x+x^2)}+\frac{1+2x}{x^{25}(1+x)(1+x+x^2)^2}$$
$$=\frac{1}{2}\lim_{x\to 1} -\frac{25(26(1+x)(1+x+x^2)+x(1+x+x^2)+x(1+x)(1+2x))}{x^{27}(1+x)^2(1+x+x^2)^2}-\frac{25(1+x)(1+x+x^2)+2x(1+x+x^2)+x(1+x)(1+2x)}{x^{26}(1+x)^3(1+x+x^2)^2}+\frac{2x(1+x)(1+x+x^2)-(1+2x)(25(1+x)(1+x+x^2)+x(1+x+x^2)+2x(1+x)(1+2x))}{x^{26}(1+x)^2(1+x+x^2)^3}$$
$$=\frac{1}{2}\left(-\frac{25(156+3+6)}{36}-\frac{150+6+6}{72}+\frac{12-3(150+3+12)}{108}\right)$$
$$=\frac{1}{2}\left(-\frac{1375}{12}-\frac{9}{4}-\frac{161}{36}\right)$$
$$=-\frac{4367}{72}$$
Since the sum of all the residues must be $0$, we have that the residue at $0$ is
$$\frac{1}{8}+\frac{1}{9}+\frac{1}{9}+\frac{4367}{72}$$
$$=\boxed{61}$$
Yeah, this was not the best method in retrospect. Computing the second derivative was very tedious and error prone (had to check with Wolfram several times), but the method does work. In my opinion, I think the other method I posted of just manipulating the generating function would be a lot more effective in these types of problems.
Comment: So i found a easier method to this problem instead of  finding  coefficient of x^24 ,just find the number of non-negative integer solution of 3x+2y+z=24,that comes from the series expansion of all the three  terms.and its a hell lot easier to find the numbers of non-negative integer solution.
Comment: @TECHNOHACK could you elaborate? Is this not the same approach as what I did in the first solution?
Comment: Yaa but finding the integer solutions in this is much easy as we can easily club 24 and 3x then just count the number of solutions using multiples of 2
Comment: @TECHNOHACK Yes, that is true for small numbers such as $24$. Both methods I gave readily generalize for larger numbers, which would not be as easy to brute force.
Comment: Yaa ur method is more generalized and can be applied to any number,for smaller numbers integer solution approach is fine.thanks for the help by the way i was searching for the method to find coefficient and u just gave an amazing method.thanks for ur time .


Check if object created: good style?

Question: I recently did some functions like the following one:
-(BOOL)registerSomethingWithParameter:(Parameter*) param
{
    Something* some = nil;

    if ([self checkParameter:param])
    {
        some = [[Something alloc] myInitCallWithParameter:param];
    }
    return (some ? YES : NO);
}

There are many discussions about using the ? in code. What do you think? Is this a proper way to tell the calling function, that everything worked well without returning an object?
I also thought about: isn't it better to check for valid parameter in myInitCallWithParameter: within the Something-Definition, but mostly these Classes are very small and store only a few values. So everything that could result in creating a nil is checked when entering the if.
Comment: A common Cocoa alternative is to add another argument of type `NSError**` that will contains an error if something went wrong. Though, if you look at many of Apple's methods they return a BOOL as well (for example `- (BOOL)setInputGain:(float)gain error:(NSError **)outError`)
Comment: Don't really understand why you are creating a Something object?
Comment: @CW0007007 forgot to mention something like `[self doSomethingWith:some];`
Comment: Are you not going to return `some` in this case?
Answer: I don't think there's any problem in using ? instead of if/else. I see a lot of programmers using it and I use it myself. Your code style is fine.
Answer: Why not just do:
-(BOOL)registerSomethingWithParameter:(Parameter*) param
{
    return [self checkParameter:param];
}

I'm assuming checkParamter returns a bool. In which case you don't even need this registerSomethingWithParameter function as it just creates a local variable that isn't used anywhere anyway ? Unless you've just written this as an example. :-)
Answer: While your approach is perfectly viable, a better option might be to simply return the created object itself; like so:
-(id)registerSomethingWithParameter:(Parameter*) param
{
  Something* some = nil;

  if ([self checkParameter:param]) {
    some = [[Something alloc] myInitCallWithParameter:param];
    [self registerSomething:some];
  }

  return some;
}

Check if object created: good style?


Gradle Could not find method "() for arguments

Question: I have just install android studio and import a project. but when i run it could not find method error will come. I am new in android studio please any one help.
I have android studio version is 2.2.3
my gradle file which has error is
buildscript {
  repositories {
    jcenter()
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'
  }
}
allprojects {
  repositories {
     jcenter()
  }
}
android {
  compileSdkVersion 21
  buildToolsVersion '21.1.2'
}
dependencies {
}

Answer: You can't use the android block in the top level file.
You have to add it in the root/app/build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.1'
}

dependencies {
    //.....
}

Answer: This question is answered many times but anyway...
What is Gradle?
Gradle is software for building software, otherwise known as "build automation
software" or "build systems". But build system does not compile, link, package, etc. applications
directly, but instead directs separate compilers, linkers, and packagers to do that
work.
Android studio usually has two gradle files:
The Project-Level File which controls the Gradle configuration for
all modules in your project.
The Module-Level Gradle File which contains unique settings
for this module, independent of any other module that your project may have in the
future.
For more information you can refer to the The Busy Coder's Guide to Android Development book or any other relevant book about android development in Android Studio
Probably your android declaration is in Project-level build gradle but instead it should be in module-level gradle.

Gradle Could not find method “() for arguments


How to prove that $\lim_{n\to\infty}\int_k^n\frac{\log_xn}{n\log x}\, dx=0$ for every $k\ge 2$

Question:
Prove that $$\lim_{n\to\infty}\int_k^n\frac{\log_xn}{n\log x}\, dx=0$$ for every $k\ge 2$.

The integral can be written as $$\int_k^n\frac{\log n}{n\log^2x}\, dx=\frac{\log n}n\int_k^n\frac1{\log^2x}\, dx$$ Now since $e^n>n$ for $n>1$, $\dfrac{\log n}n\to 0$ as $n\to\infty$.
Also, $\dfrac1{\log^2x}$ is monotonically decreasing, so we need only consider the case when $k=2$ - the equality would hold for larger values of $k$.
However, by WolframAlpha (http://www.wolframalpha.com/input/?i=%5Cint_2%5E%5Cinfty%5Cfrac1%7B%5Clog%5E2x%7D+dx), $$\int_2^n\frac1{\log^2x}\, dx\to +\infty$$ as $n\to\infty$. The limit thus cannot be evaluated using this method because we would have $0\cdot\infty$.
How should I begin the proof?
Answer: Write your expression in the form
$$\frac{\displaystyle\int_k^n\dfrac{dx}{\log^2(x)}}{\dfrac n{\log(n)}}$$
Since this is defined for real $n>1$ you can apply L'Hôpital's rule to obtain:
$$\frac{\dfrac 1{\log^2(n)}}{\dfrac{\log(n)-1}{\log^2(n)}}=\frac 1{\log(n)-1}\sim\frac 1{\log(n)}\longrightarrow 0$$
as $n\to +\infty$.