Q:

How to limit file modifications to a single branch in Git

I'm starting to learn Git, reading the ProGit book from time to time. I've heard that the most powerful feature of Git is the branches, so I tried to use them. I'm hacking on the KDE project, so there is a remote server and a local copy.
So here's my situation. I've coded a bugfix, but the developer responsible for that code area has gone offline without having given me a shipit, so I decided to do a different fix in the meantime. I've heard that branches can (and more importantly, should) be used for such situations. OK, I created a local branch
git branch bugfix

then switched to that branch
git checkout bugfix

ad then discovered that the files I had modified for the original fix were still modified. (Of course, I needed a clean directory to be able to push only the second bugfix without the first one.) Well, no problem, I thought, let's reset if that's what git status tells me to do. I did a reset and indeed got a clean dir. But hey, after I switched back to master
git checkout master

the modified files  were no longer modified there! It was a clean dir.
Now what's the point of branches? Can't have two versions of a file, modified in one branch and unmodified in another one? I know about git stash, but if I do that, unstashing the changes will kill the second bugfix, because IIRC stash simply replaces one file with another one, no merging is done.
What am I doing wrong here? Why is it impossible to have the file modifed in one branch and unmodified in another?

A:

So, here's what happened.  You started off with a commit A from the original developer.  You fixed some bugs and now you're in B.  There's a remote branch pointing to A called origin/original-branch, and there's a local branch pointing to B called my-changes.  I don't know what they're actually called (use git branch -a to list them).

....->  A  ->  B
        ^      ^
        |      +-- my-changes
        |
        +-- origin/original-branch

If you're on B and you make a branch and start making changes, you'll get this:

....->  A  ->  B  ->  C
        ^      ^      ^
        |      |      +-- bugfix
        |      |
        |      +-- my-changes
        |
        +-- origin/original-branch

This is not what you want.  You want this:

               +-- my-changes
               v
....->  A  ->  B
         \
           ->  C
        ^      ^
        |      +-- bugfix
        |
        +-- origin/original-branch

So you have to make your new branch start where the other developer's branch is.
git branch bugfix origin/original-branch
git checkout bugfix

That specifies that the new branch starts from the other developer's work.  If you do this instead:
git branch bugfix # not what you want

This will cause the bugfix branch to start from wherever you are right now.


Q:

What exactly happens in this javascript sequence?

I would like to get a deeper understanding of the nuances of javascript.
Take the function below:
str.replace(/(\b[^:]+):'([^']+)'/g, function ($0, param, value) {
    ret[param] = value;
});

Why is there a need for /g?
What
exactly gets passed into the
function?
Where do these values come
from?

Thanks!

A:

Why is there a need for /g?

Because presumably you will have multiple pairs on the matching string, e.g. a:'b' c:'d'

What exactly gets passed into the function?

The callback function gets the whole match as the first argument, the two later arguments are the capturing groups specified on your regexp.
For example:
"a:'b' c:'d'".replace(/(\b[^:]+):'([^']+)'/g, function ($0, param, value) {
    console.log($0, param, value);
});

The callback will be executed twice, and it will show you "a:'b'" for $0, "a" for param and "b" for value on the first execution.
In the second execution -for the second match-, will show you "c:'d'" for $0, "c" for param and "d" for value.


Q:

Doxygen - How to generate a textual call relationship result without generating the graph

I am using Doxygen to get the whole function call graph for the c/c++ project. I set HAVE_DOT = YES and CALL_GRAPH = YES. It can help get the right results but for a big project, it will cost much time to generate the PNG using dot. I want to get a textual result without PNG to avoid time consuming. But I do not know how to config. It will be perfect to get .DOT files without generating PNG.

A:

For the graphical representation doxygen has the CALL_GRAPH, CALLER_GRAPH together with the HAVE_DOT configuration settings.
For a textual representation there are the settings: REFERENCED_BY_RELATION and REFERENCES_RELATION, these setting result in a per function result.
From the comment by the OP:

But it just helps me to know what entities are called in a function. I
  can not get the whole call graph for the project.

and

What I want is to get the functions call graph in textual graph like .DOT without generating PNG.

this is not directly supported by doxygen. There is a mean trick to accomplish something:

set HAVE_DOT to YES
set CALL_GRAPH to NO
add to the function of which you want the relations: \callgraph
the mean trick:

set DOT_CLEANUP to NO
set DOT_PATH to a path where the dot executable does not reside
set DOT_GRAPH_MAX_NODES to an appropriate value
set MAX_DOT_GRAPH_DEPTH to an appropriate value

this will result in a dot file (in e.g. the html directory) with the relations as requested.


Q:

nginx serving page code instead of page content

I am setting up an instance of the official nginx docker image to serve a static web page. The Dockerfile contains the following:
FROM nginx
COPY ./html /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf

As for the configuration file:
http {
    server {
        root         /usr/share/nginx/html;
        index        index.htm;
    }
}

events {
    worker_connections        1024;
}

The image is compiling successfully, and is put up on port 8090:
docker run --name hello-world -d -p 8090:80 hello-world-nginx

When I access the port from a web browser, I get this:

What am I doing wrong?

A:

You just need to add the mime types file to nginx config:
http {
include       /etc/nginx/mime.types;
    server {
        root         /usr/share/nginx/html;
        index        index.htm;
    }
}

events {
    worker_connections        1024;
}


Q:

Voice call recording Application in android

I like to make an application for recording voice call.Is it possible? I expecting some proper guiding from well experienced people in android.
i have seen android.media.MediaRecorder class in android. Is that class i need to use for this?
Thanks and Regards
Parvathi Kamalone.

A:

Developers do not have access to the in-call audio stream, sorry. The only way this sort of works is if the device is in speakerphone mode.


Q:

How to draw a plane equivalent to a given btStaticPlaneShape using OpenGL

With all other shapes in bullet, you can easily get the transform from the MotionState which holds the origin, the scale, and the rotation. There seems to be no way to get the same information about a btStaticPlaneShape. How can I get this information, so that I can build a rectangle with 4 vertices that will act as a representation in OpenGL?

A:

Looks like btStaticPlaneShape is an infinite plane, so you could pick an arbitrary point and just draw a really big plane centered on that that point using the normal stored in btStaticPlaneshape


Q:

Trying to select link in other element with JQuery

So i'm working on a plugin for a specific site, i'm trying to select a certain link but only if the image next to it has a certain title.
The only problem here is that the image and the link aren't in the same element, and i'm not quite sure how to target the link.
JSFiddle example
$('div.column.first img[title="True"]').css({
    "background-color": "red"
});

$("div.column a").parent().css({"background-color": "red"});

This is all the code I have ( I know its not much but i'm completely stuck )
Could anyone please give a hint on how I should approach this, thanks in advance

A:

Try this:
$('div.column.first img[title="True"]').parent().siblings().find('a').css({
    "background-color": "red"
});

You can also use the .next() method instead of the .siblings(). Based on your markup an alternative is using the .has() method:
$('li.even').has('img[title="True"]').find('a').css({
    "background-color": "red"
});

Or :has selector:
$('li.even:has(img[title="True"]) a').css("background-color", "red");


Q:

Set attribute before include jsp

consider this situation:
<!-- main.jsp -->
<% for (int i = 0; i < 10; i++) { %>
    <% request.setAttribute("i", new Integer(i)); %>
    <jsp:include page="template.jsp" />
    <% request.removeAttribute("i"); %>
<% } %>

<!-- template.jsp -->
<jsp:useBean id="i" scope="request" type="java.lang.Integer" />
<%=i%>

If I execute main.jsp I get this result:
0 1 2 3 4 5 6 7 8 9

that's what I want.
But the question is:
The display order will always be this?
Should I put a synchronization for the request?
Thanks

A:

Yes Display order will always be the same,
You are putting it to request which is new instance per request so no need of synchronization


Q:

Python display text with font & color?

Is there a way I can display text on a pygame window using python?
I need to display a bunch of live information that updates and would rather not make an image for each character I need.
Can I blit text to the screen?

A:

Yes. It is possible to draw text in pygame:
# initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error
myfont = pygame.font.SysFont("monospace", 15)

# render text
label = myfont.render("Some text!", 1, (255,255,0))
screen.blit(label, (100, 100))

A:

You can use your own custom fonts by setting the font path using pygame.font.Font
pygame.font.Font(filename, size): return Font

example:
pygame.font.init()
font_path = "./fonts/newfont.ttf"
font_size = 32
fontObj = pygame.font.Font(font_path, font_size)

Then render the font using fontObj.render and blit to a surface as in veiset's answer above. :)

A:

I have some code in my game that displays live score. It is in a function for quick access.
def texts(score):
   font=pygame.font.Font(None,30)
   scoretext=font.render("Score:"+str(score), 1,(255,255,255))
   screen.blit(scoretext, (500, 457))

and I call it using this in my while loop:
texts(score)


Q:

How many distinct subgroups does the symmetric group $S_3$ have?

How many distinct subgroups does the symmetric group $S_3$ have?
So when I do this question, is there a general technique to use?
I know that the order of a subgroup divides that of the group.
But the because $S_3$ is not cyclic, there may not be bijection between divisors of $6$ and
the subgroups of it. (Or there is?)
So is the only way by trial and error?
For $S_3$ it may help to know that it is equal to the group of symmetries of a regular triangle.
But for $S_4$ and higher, is there any simpler method?
Anyway, is the answer $6$?

A:

I think that for small groups like $S_3$ this not very difficult to do by hand.
$S_3=\{id,(12),(13),(23),(123),(132)\}$
Clearly, $\{id\}$ and $S_3$ are subgroups of $S_3$
Now let us have a look at subgroups generated by one elements (cyclic subgroups). (We only have 6 elements to try, and we have already considered $[id]=\{id\}$.)
$[(12)]=\{id,(12)\}$
$[(13)]=\{id,(13)\}$
$[(23)]=\{id,(23)\}$
$[(123)]=[(132)]=\{id,(123),(132)\}$
Is this list of all subgroups? Yes, it is.
We can do this by trial and error -- trying adding one element to subgroup from our list and checking whether they generate the whole group $S_3$. (Which seems tedious, but in fact we only have to check whether any subgroup containing at least one 2-cycle and at least one 3-cycle is the whole $S_3$; and also observe that two different 2-cycles give us a 3-cycle.)
But quicker way is to notice that any proper subgroup of $S_3$ must have 1, 2 or 3 elements. (Order of subgroup must divide order of the group.) And any group of prime order is cyclic. So by enumerating cyclic subgroups we have obtain list
of all proper subgroups of $S_3$.
We can check our result at groupprops wiki (or elsewhere): Subgroup structure of symmetric group:S3.
You also asked about $S_4$. As I have mentioned in my comment, there is another question on this site about subgroups of $S_4$: How to enumerate subgroups of each order of $S_4$ by hand

A:

An important theorem to use is that the order of any subgroup must divide the order of $S_3$. Now, the order of $S_3$ is just 3! = 6. Hence, any candidate subgroup must have order 6, 3, 2, or 1. Note that the group of order 1 is just the trivial subgroup { e }, the group containing the identity element of $S_3$. Now, this is the only subgroup of order 1. The subgroup of order 6 must be $S_3$ itself, the only possible subgroup of order 6. Hence, we are left with subgroups of order 2 or order 3.
Subgroups of order 2: Note any subgroup must contain the identity element e.
Hence, we are interested in sets of the form K = { e $\in $ K and |K| = 2 and s $\in$ S$_3$, such that s$\circ$s=e }. This is because we want closure and we need an identity and inverse for any subgroup. It is not difficult to check that the only elements in $S_3$ satisfying the conditions on K are the transpositions on $S_3$.
Subgroups of order 3: For subgroups of order three we are interested in sets of the form F = { e $\in$ F and |F| = 3, and $s_1$,$s_2$ $\in$ S$_3$ such that $s_1$$\circ$$s_2$=$s_2$$\circ$$s_1$= e }. This is because we want to make sure our set is closed, and contains inverses and the identity. It is not difficult to check that there are only two elements in $S_3$ with unique inverses (inverses that are not the element itself) that satisfy all of the conditions imposed on F.
So you are done, and the number of unique subgroups of $S_3$ is 6.


Q:

Backbone.js: rendering collections in real world apps

Frustratingly, most ‘tutorial’ examples of backbone.js apps assume a clean model slate.  I-.e. that the model collections are empty initially, until a user adds an item.  Of course this is not the case in a real world app, where you usually have an existing collection to start with from the back end store.
I would like to know how people deal with existing collections in backbone.  Specifically:

How do you render a collection after it has been fetched? Is is just a case of iterating through the collection? Should this be trigger by some event?
The backbone docs talk about ‘bootstrapping’, which I understand means using data that is available on the initial load (this also makes sense from an SEO point of view). But how does this work in practice? The data is dumped into JS on the server side? Or the JS examines the DOM?

I feel like this is a poor question, but I expect to expand it based on the answers.
EDIT
So it seems that the consensus is to add the data as party of the JS and process that on page load.
One big disadvantage I see with this technique is that the information is not available for  search engine spiders.  From that perspective it might be better to extract it from the DOM (although I haven't seen anyone do it that way).  Or maybe add the HTML server side and stick the data in the JS?

A:

I came across the same situation as you, I don't always want my data bootstrapped initially (especially if its from a third-party api call).  I haven't come across any tutorials that do this but looking through the documentation its actually pretty easy.  You just need to bind the 'reset' event (this is fired when the entire collection is repopulated) on your collection and render.  Heres a quick example:
my_application.js
window.MyApplication = {
  Models: {},
  Collections: {},
  Views: {},
  Routers: {},
  init: function() {
    // Start the data loading
    this.someItems = new MyApplication.Collections.Items();
    this.someItems.fetch();

    // Start rendering the UI before the data is ready
    new MyApplication.Routers.Items(this.someItems);
    Backbone.history.start();
  }
};

routers/items_router.js
MyApplication.Routers.Items = Backbone.Router.extend({
  routes: {
    "" : "index"
  },

  initialize: function(collection) {
    this.collection = collection;
  },

  index: function() {
    var view = new MyApplication.Views.ItemsIndex({ collection: this.collection });
    $('.items').html(view.render().el);
  }
});

views/items/items_index.js
MyApplication.Views.ItemsIndex = Backbone.View.extend({
  initialize: function() {
    _.bindAll(this, "render");

    // Once the collection is fetched re-render the view
    this.collection.bind("reset", this.render);
  },

  render: function() {
    console.log(this.collection.length);
    // Render content
    return this;
  }
});

A:

As far as rendering collections, yes I normally iterate over a collection and create a child view for each of the models.   Here is a link that might be helpful on that  http://liquidmedia.ca/blog/2011/02/backbone-js-part-3/
When should you render it?  Well that's a tough one to answer but I wouldn't say it's in response to any particular event.  One thing that I like is that we have one main view that renders sub views which render other sub views.  As a convention we don't render directly to the DOM but once all the sub views are rendered, we append the main view to the DOM and the whole page shows up immediately.  This avoids the 'flash of unstyled content'
Regarding bootstrapping I see from the contents that you read the FAQ, and that's just what I've done in practice.  I use ASP.Net MVC 3 so my server side rendered view would have something like (though I wouldn't put 'books' on the global namespace normally):
<script type="text/javascript">
    books = new BooksCollection();
    books.reset(@Html.ToJson(Model));
</script>

Hope that's helpful.


Q:

sql server cannot access inserted table in a trigger

I am trying to create a simple to insert trigger that gets the count from a table and adds it to another like this
CREATE TABLE [poll-count](
id VARCHAR(100),
altid BIGINT,
option_order BIGINT,
uip VARCHAR(50),
[uid] VARCHAR(100),
[order] BIGINT
PRIMARY KEY NONCLUSTERED([order]),
FOREIGN KEY ([order]) references ord ([order]
)
GO

CREATE TRIGGER [get-poll-count]
ON [poll-count]
FOR INSERT
AS
    BEGIN
        DECLARE @count INT
        SET @count = (SELECT COUNT (*) FROM [poll-count] WHERE option_order = i.option_order)
        UPDATE [poll-options] SET [total] = @count WHERE [order] = i.option_order
    END
GO

when i ever i try to run this i get this error:

The multi-part identifier "i.option_order" could not be bound

what is the problem?
thanks

A:

Your trigger currently assumes that there will always be one-row inserts. Have you tried your trigger with anything like this?
INSERT dbo.[poll-options](option_order --, ...)
  VALUES(1 --, ...),
        (2 --, ...);

Also, you say that SQL Server "cannot access inserted table" - yet your statement says this. Where do you reference inserted (even if this were a valid subquery structure)?
SET @count = (SELECT COUNT (*) FROM [poll-count]
  WHERE option_order = i.option_order)
-----------------------^ "i" <> "inserted"

Here is a trigger that properly references inserted and also properly handles multi-row inserts:
CREATE TRIGGER dbo.pollupdate
ON dbo.[poll-options]
FOR INSERT
AS
BEGIN
    SET NOCOUNT ON;

    ;WITH x AS
    (
      SELECT option_order, c = COUNT(*)
       FROM dbo.[poll-options] AS p
       WHERE EXISTS
       (
        SELECT 1 FROM inserted
        WHERE option_order = p.option_order
       )
       GROUP BY option_order
    )
    UPDATE p SET total = x.c
      FROM dbo.[poll-options] AS p
      INNER JOIN x
      ON p.option_order = x.option_order;
END
GO

However, why do you want to store this data on every row? You can always derive the count at runtime, know that it is perfectly up to date, and avoid the need for a trigger altogether. If it's about the performance aspect of deriving the count at runtime, a much easier way to implement this write-ahead optimization for about the same maintenance cost during DML is to create an indexed view:
CREATE VIEW dbo.[poll-options-count]
WITH SCHEMABINDING
AS
  SELECT option_order, c = COUNT_BIG(*)
    FROM dbo.[poll-options]
    GROUP BY option_order;
GO
CREATE UNIQUE CLUSTERED INDEX oo ON dbo.[poll-options-count](option_order);
GO

Now the index is maintained for you and you can derive very quick counts for any given (or all) option_order values. You'll have test, of course, whether the improvement in query time is worth the increased maintenance (though you are already paying that price with the trigger, except that it can affect many more rows in any given insert, so...).
As a final suggestion, don't use special characters like - in object names. It just forces you to always wrap it in [square brackets] and that's no fun for anyone.


Q:

Java Generics: Class that takes a class that takes another class

I have a class BatchConfigurable
public class BatchConfigurable<T extends BatchContext>() {}

I am trying to write a wrapper for it. This will be another class that takes this class or any class that extends BatchConfigurable as parameter. For the declaration, I'm trying:
public class WrappedBatchConfigurable<E extends BatchConfigurable <T extends BatchContext>>() {}

This is invalid but as should be clear from the code, I want to preserve the property that the subtype of BatchConfigurable that WrappedBatchConfigurable takes should take a type that extends BatchContext as parameter. What would the syntax for this be?

A:

You need to declare your type parameter T before you use it.
class WrappedBatchConfigurable<T extends BatchContext, E extends BatchConfigurable<T>> {}


Q:

python selenium xpath grabbing elements

I'm trying to grab some elements using selenium and python, but I'm having a hard time referencing the sub elements.
If you take a look at image 1  and at image 2, I am trying to grab the dt and dd elements. My current code that I am playing around with is:
status = driver.find_elements_by_xpath("//div[@class='listview-info']")
for x in status:
    print(x.text)

I am using xpath and a for loop because there are 10 of these elements per page that I'm trying to grab. I'm unsure of how to grab the dt and dd tags. I've tried "//div[@dt]" with no luck.

A:

You are trying to grab parent element (//div[@class='listview-info']). Instead grab divs under it, and access dd and dt for each of them:
list = driver.find_elements_by_xpath("//div[@class='listview-info']/div")
for item in list:
    print(item.find_element_by_xpath("./dd").text)
    print(item.find_element_by_xpath("./dt").text)


Q:

spring-data: Not an managed type: class java.lang.Object

I started using spring-data project yesterday and was trying to add a test to repository I have created.
The project structure looks like
persistence/pom.xml
           src/main/java/
                        ApplicationConfig
                        BaseRepository
                        Network
           src/main/test/BaseRepositoryTest

The ApplicationConfig looks like
@Configuration
@ComponentScan
@EnableJpaRepositories
public class ApplicationConfig {
    @Bean
    public DataSource dataSource() {
        final EmbeddedDatabaseBuilder embeddedDatabaseBuilder = new EmbeddedDatabaseBuilder();
        embeddedDatabaseBuilder.setType(EmbeddedDatabaseType.H2);
        return embeddedDatabaseBuilder.build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        final HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setDatabase(Database.H2);
        jpaVendorAdapter.setGenerateDdl(true);

        final LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        localContainerEntityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        localContainerEntityManagerFactoryBean.setPackagesToScan(getClass().getPackage().getName());
        localContainerEntityManagerFactoryBean.setDataSource(dataSource());

        return localContainerEntityManagerFactoryBean;
    }
}

The BaseRepository looks like
import org.springframework.data.repository.Repository;

public interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
    List<T> findAll();
}

The Network is an Entity class looks like
@Entity
public class Network extends com.org.comma.persistence.Entity {
    private final long networkId;

    private final String name;

    private final boolean active;

    private final DateTime createdAt;

    private String createdBy;

    private DateTime updatedAt;

    private String updatedBy;
...
}

and BaseRepositoryTest looks like
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ApplicationConfig.class, BaseRepository.class})
public class BaseRepositoryTest {

    @Autowired
    BaseRepository<Network, Long> baseRepository;

    @Test
    public void testAllNetworks() {
        final List<Network> networks = baseRepository.findAll();
        assertTrue(networks.isEmpty());
    }
}

My pom.xml looks like
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.0-api</artifactId>
        <version>1.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.3.5.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.6.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
    </dependency>
    <dependency>
        <groupId>com.google.code.findbugs</groupId>
        <artifactId>jsr305</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
</dependencies>

When I run mvn clean install, I see error as
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:319)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:212)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class java.lang.Object

Please help me identify what am I doing wrong here, I am new to this project

A:

The type the repository manages has to be known at bootstrap time, which means that you need to actually create a concrete repository like this:
interface NetworkRepository extends BaseRepository<Network, Long> { … }

There are a few other glitches in the code you showed:

The Network class doesn't have any property annotated with @Id
BaseRepository should carry an @NoRepositoryBean annotation to indicate it's not supposed to be instantiated at all. See the reference documentation for details.

A:

This also happens if you have one repository interface that extends another and you forgot the @NoRepositoryBean on the super-interface.

A:

I have faced the same issue, and resolved by adding @NoRepositoryBean
@NoRepositoryBean
public interface BaseRespository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> {}


Q:

Stretch ComboBox Content in Silverlight

This is driving me nuts.  I can't seem to get the data template within my ComboBox to stretch the width of the pulldown.  What gives?
<Grid x:Name="LayoutRoot" Background="White">
    <Grid.RowDefinitions>
        <RowDefinition Height="30" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <ComboBox x:Name="SearchesComboBox" HorizontalContentAlignment="Stretch" Width="150">
        <ComboBox.ItemContainerStyle>
            <Style TargetType="ComboBoxItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            </Style>
        </ComboBox.ItemContainerStyle>
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Black" BorderThickness="1">
                    <TextBlock Text="{Binding}" Margin="2" />
                </Border>
            </DataTemplate>
        </ComboBox.ItemTemplate>
        <sys:String>Two</sys:String>
        <sys:String>Four</sys:String>
        <sys:String>Six</sys:String>
    </ComboBox>
</Grid>

A:

<ComboBox.ItemContainerStyle>
    <Style TargetType="ComboBoxItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
    </Style>
</ComboBox.ItemContainerStyle>

A:

Ok, after about a day of fiddling with it, I have a solution.  I HATE it, but it works.  Basically, I reflected into the System.Windows.dll for Silverlight, and I ripped out the default template for ListBoxItem (which ComboBoxItem uses).
It turns out that in that template, there is a ContentPresenter with the HorizontalAlignment hard-coded to Left.  So, I ripped off the template, and added a TemplateBinding for HorizontalAlignment, so it can use whatever the HorizontalAlignment of ComboBoxItem is.
That being said, what follows is the working code.  If ANYONE has a better way to do this, please tell me.  I haven't checked yet if this is fixed in 3.0.  I hope it is.  It should really bind all the way from ComboBox.HorizontalContentAlignment.
<UserControl.Resources>
    <Style x:Key="FixedComboBoxItem" TargetType="ComboBoxItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ComboBoxItem">
                    <Grid Background="{TemplateBinding Background}">
                        <vsm:VisualStateManager.VisualStateGroups>
                            <vsm:VisualStateGroup x:Name="CommonStates">
                                <vsm:VisualState x:Name="Normal" />
                                <vsm:VisualState x:Name="MouseOver">
                                    <Storyboard>
                                        <DoubleAnimation Storyboard.TargetName="fillColor" Storyboard.TargetProperty="Opacity" Duration="0" To=".35"/>
                                    </Storyboard>
                                </vsm:VisualState>
                                <vsm:VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <DoubleAnimation Storyboard.TargetName="contentPresenter" Storyboard.TargetProperty="Opacity" Duration="0" To=".55" />
                                    </Storyboard>
                                </vsm:VisualState>
                            </vsm:VisualStateGroup>
                            <vsm:VisualStateGroup x:Name="SelectionStates">
                                <vsm:VisualState x:Name="Unselected" />
                                <vsm:VisualState x:Name="Selected">
                                    <Storyboard>
                                        <DoubleAnimation Storyboard.TargetName="fillColor2" Storyboard.TargetProperty="Opacity" Duration="0" To=".75"/>
                                    </Storyboard>
                                </vsm:VisualState>
                            </vsm:VisualStateGroup>
                            <vsm:VisualStateGroup x:Name="FocusStates">
                                <vsm:VisualState x:Name="Focused">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Visibility" Duration="0">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <Visibility>Visible</Visibility>
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </vsm:VisualState>
                                <vsm:VisualState x:Name="Unfocused"/>
                            </vsm:VisualStateGroup>
                        </vsm:VisualStateManager.VisualStateGroups>
                        <Rectangle x:Name="fillColor" Opacity="0" Fill="#FFBADDE9" IsHitTestVisible="False" RadiusX="1" RadiusY="1"/>
                        <Rectangle x:Name="fillColor2" Opacity="0" Fill="#FFBADDE9" IsHitTestVisible="False" RadiusX="1" RadiusY="1"/>
                        <ContentPresenter
                            x:Name="contentPresenter"
                            Content="{TemplateBinding Content}"
                            ContentTemplate="{TemplateBinding ContentTemplate}"
                            HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
                            Margin="{TemplateBinding Padding}"/>
                        <Rectangle x:Name="FocusVisualElement" Stroke="#FF6DBDD1" StrokeThickness="1" Visibility="Collapsed" RadiusX="1" RadiusY="1" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</UserControl.Resources>

<Grid x:Name="LayoutRoot" Background="White">
    <Grid.RowDefinitions>
        <RowDefinition Height="30" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <ComboBox x:Name="SearchesComboBox" Width="150" ItemContainerStyle="{StaticResource FixedComboBoxItem}"  HorizontalContentAlignment="Stretch">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Black" BorderThickness="1" >
                    <TextBlock Text="{Binding}" Margin="2" />
                </Border>
            </DataTemplate>
        </ComboBox.ItemTemplate>
        <sys:String>Two</sys:String>
        <sys:String>Four</sys:String>
        <sys:String>Six</sys:String>
    </ComboBox>
</Grid>


Q:

LXC container starts with readonly root filesystem

I am running LXC on Debain Wheezy using BTRFS, and have created a container using lxc-create using the "debian" template (yesterday).
When starting the container, the root filesystem in the container is read only. I expected the rootfs in the container would be read-write, not read-only. This seems to disrupt the started services and prevents the lxc-shutdown and other host tools from interacting with the container.
I have been using mount -o remount,rw / to make the rootfs read-write, but it's much too late in the boot process for the container. I have only installed a few extra packages and haven't done any significant configuration yet.
What do I need to do to get the container to boot with a read-write rootfs?
[EDIT]: it appears that the host's filesystem was marked as readonly. Making it read-write then starting the container means that the container has a read-write rootfs. However, when the container is shutdown, the filesystem is readonly again. Appears the container shutdown marks the FS as readonly. Is there something to do to stop it from doing that?

A:

The template "debian" in LXC on Debain Wheezy currently (early March 2014) doesn't disable services that may cause problems.
The key service causing problems in this case was 'umountroot', fix by running
chroot /path/to/containername/rootfs /usr/sbin/update-rc.d -f umountroot remove

Other services to remove include

hwclock.sh
hwclockfirst.sh

There a probably other ways of solving this issue, such as dropping capabilities. Another way to solve it is to change the template, such as suggested by http://cblog.burkionline.net/lxc-linux-container/, but note that it doesn't include umountroot as one of the services disabled and will need tweaks.


Q:

About the set of density points of given sets, for the Lebesgue measure on the line and on the plane

Please help me prove the following:

1) Let $A \subseteq \{(x,y)|0< x^2+y^2 < 1 \}$ be a lebesgue measurable set such that every point in $\{(x,y)|0< x^2+y^2 < 1 \}$ is a density point of $A$,
  then (0,0) is a density point of A as well.
2) Find a set $A$ such that for every n:
  $\frac{m \bigl(\bigl[0,\frac{1}{2^n}\bigl] \cap A \bigl)}{m\bigl(\bigl[0,\frac{1}{2^n}\bigl]\bigl)}=\frac{1}{2}$.

Couldn't prove the 1st question. Any help?
And anyone have an example for the second question?
Thanks!

A:

For the first problem, define $B= \{0<x^2+y^2<1\}\setminus A.$ Suppose $m(B)>0.$ Then by Lebesgue's differentiation theorem, a.e. $(x,y) \in B$ is a point of density of $B.$ Let $z_0=(x_0,y_0)$ be one of these. Then it is easy to see
$$ \lim_{r\to 0^+} \frac{m(A\cap D(z_0,r))}{m(D(z_0,r))} = 0.$$
Thus $z_0$ is not a point of density of $A,$ contradiction. This shows a.e. point of $\{0<x^2+y^2<1\}$ is in $A.$ The desired conclusion is immediate from this.


Q:

Network between host and guest operating system (VMware virtual machines)

On my computer (OS: Windows 7) I have installed VMware and created one virtual machine(OS: Windows XP), can I create a network between my host OS (windows 7) and guest OS (windows XP) ?

A:

VMware already creates a network between your actual machines and the virtual machines. The virtual machines each, by default, can get their own IP address to access network resource and the Internet.


Q:

Why does this simple code yield 'Undefined variable: bar'

class A {
    protected $bar = 'bar';
    public function foo() {
        echo $this->$bar;
    }
}

$a = new A();
$a->foo();

It's boggling my mind that this isn't working. I come from C++ and C# so it's likely something I don't understand about PHP.

A:

Why does this simple code yield 'Undefined variable: bar'

Because PHP tries to evaluate the variable $bar before evaluating $this->. Since there is not a $bar variable, it yields a notice.
Remove the $ in front of $bar:
echo $this->bar;

I would encourage you to read the Variable Variables section of the docs as well as OOP Basics.

A:

When you access a member, you only need the dollar-sign before this; i.e. access it like this instead:
echo $this->bar;


Q:

Is synchronization needed when manipulating different array(object array) indices

In the context if Java, I have a code like this,
MyObject[] array;

and in different threads i have a code like this
array[i] = new MyObject(val);

If I ensure that each of my threads use different values of "i" then would I need to synchronize the above statement to take care of race conditions?

A:

Race conditions are only an issue if two threads may read and modify the same variable concurrently.
As long as you are sure that each thread uses a different range of indices, and the underlying array is not redefined, then it should be safe to think of each cell as a different variable. Therefore, each thread works on a separate set of variables and you would not get a race condition.
That being said, make sure you are indeed not overlapping in your use of indices - this is often trickier than it would appear.
In addition, you have to make sure that no two cells map into the object - if you modify the same object (rather than just the reference to it) from two threads, you could get a race condition.

A:

Maybe. If every task wrote to a different location in the array, they wouldn't overwrite each other's output. So that works.
You might face an issue when finally processing the array, though, since Java doesn't make guarantees when the values are written to memory. The optimizer could decide to write the values really late (or too late for you). Therefore, you should make the array volatile which means that no caching must happen when accessing the values in it.


Q:

Login failed for user 'someone'

I work on Microsoft SQL Server 2008 R1 and visual studio 2010.
My target is to clone a server to a new machine. However, after setting the application up and entering  "local/storytelling" in the browser's URL, the error msg appears. After google the possible mistake, I have set the authentication mode form  "Windows Authentication mode" to "SQL Server and Windows Authentication mode".
But the error remains... And I have no more idea now.
Here is the error msg:

[SqlException (0x80131904): Login failed for user 'storytelling'.]
     System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4846887
     System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
     System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392
     System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +35
     System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +144
     System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +342
     System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +221
     System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189
     System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +185
     System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31
     System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +433
     System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66
     System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499
     System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65
     System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117
     System.Data.SqlClient.SqlConnection.Open() +122
     _Default.Page_Load(Object sender, EventArgs e) in D:\storytelling\Default.aspx.vb:21
     System.Web.UI.Control.OnLoad(EventArgs e) +99
     System.Web.UI.Control.LoadRecursive() +50
     System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627

I don't know what's the problem to the code:(Source file: "Default.aspx.vb")
Partial Class _Default
    Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)                      Handles Me.Load
    Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("StoryTelling2ConnectionString").ConnectionString)
Dim cmmd As New SqlCommand
Dim strSQL As String
conn.Open()

The error log highlight conn.Open() in red color. I guess it's probably I lost some steps as I cloned the server. But I have no idea what steps I ignored.
Please provide some suggestion.
                                                             Thanks.

A:

I finally know what happened. Sorry for the poor representation of my problem. I take reference to this and this, finding out that the windows server 2008 has installed an SQL Express edition for me. Nevertheless, I don't know at all, so I install another SQL Server. In this condition. I have two SQL server edition, and according to the thread MSDN FORUM, the log in to the different server is quite different in the "Server Name" input.
In short, my connection string is always incompatible with the "Server Name" input, and thus the log in process always failed.


Q:

Replace line breaks

I am using visual studio code for several things. Everything is working fine, but I cannot get one specific thing to work.
I need the ability to remove line breaks from the text.
Example:
first line
second line

Should become:
first linesecondline

Since a recent update it is possible to search for line breaks with using ^$.
It is described here: https://github.com/Microsoft/vscode/pull/314
The problem I have is that when I use this for replacing, it does actually "add" to the line break and does not "replace" it.

A:

The latest version of VS Code has a shortcut to remove breaks from selection (CTRL + J).

A:

I found that (at least on Windows) the solution was to use search and replace with a regular expression. Search for $\n and replace with nothing to get rid of the newlines. Note that the newline character that we want to replace is placed after the end of line matcher ($).

A:

@tripleonard hint did not work for me (no shortcut key assigned), so what I did was  first ctrl+shift+p to list all commands and then just type Join lines


Q:

Time incorrect after add format date in gson builder

I have json string which is returned from mongodb.
[{"_id":"578bb51aa51d15940688809e","name":"aaa","date":"2016-07-20T11:47:39.302Z"}]

I used gson to convert the Java Object. I got Unparseable date: "2016-07-20T11:47:39.302Z". So I added date format to gson builder.
Gson gson=  new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();

The date result is Wed Jul 20 11:47:39 MMT 2016. The time is incorrect.
What is the better date format pattern for date string?
How can I choose the suitable date format pattern by the given date string?

A:

If I am not mistaken, you are having an issue with timezone information. Both the JavaScript Date object and the Java Date object represent a point in universal coordinated time (UTC). Neither the JavaScript Date object nor the Java Date object contain timezone information.

Side note: The Java Date object does actually contain timezone information, which is why you see the timezone (MMT in your case) when you call date.toString(). Though, this timezone should be ignored, as the timezone irregularities highlight some of the many issues with the Java 7- date/time classes.

The GsonBuilder().setDateFormat() method sets the string format that a Java Date object should be serialized to and deserialized from. This format does not contain any timezone information either because the Date object does not contain that information.
In order to display the UTC time your Date object represents in the correct timezone, you must provide that timezone. This is not done during deserialization with Gson, but when you actually display the date/time:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getDefault());

String zonedDateTime = simpleDateFormat.format(date);

Android also comes with a handy DateUtils class to use instead of SimpleDateFormat that will handle the timezone information for you, as well as Locale information.
DateUtils.formatDateTime(getContext(), date.getTime(),
                        DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_ABBREV_ALL);


Q:

How to set a timeout on a SOAP call in MS .Net 4.5 using C#

I need to account for extremely slow responses from a SOAP server. I have added the service in C# language using Visual Studio 2012 and I really would like to be able to easily set a timeout value on the service object and handle a suitably named exception when a response is not received within that time frame.
How can I implement this?

A:

It's in the documentation: http://msdn.microsoft.com/en-us/library/microsoft.web.services2.soapwebrequest.timeout.aspx .
In short, use the SoapWebRequest's Timeout property.


Q:

How does this TypeScript function parameter work

I found this code online and trying to understand it.
public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]> {

    //Create a function that considers the specified $index parameter value
    let getCities = (text$: Observable<string>) =>
        text$
            .debounceTime(300)
            .distinctUntilChanged()
            .switchMap( query => {

                //some logic involving $index here
                //...

                //query.length < 2 ? [] : this.apiService.getCities(query).catch(() => {
                //return Observable.of([]);
            });

    //Return that "custom" function, which will in turn be called by the ngbTypescript component
    return getCities;
}

My question revolves around the method signature.
public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]>

I understand
$index: any is an input parameter of type Any.
The function returns Observable an observable of any.
But what is
: (text: Observable<string>)
Is it a second parameter?
If its a second parameter shouldn't it be
public searchFunctionFactory($index: any ,text: Observable<string>) => Observable<any[]>

A:

That indicates that the return value of the searchFunctionFactory function is a function which takes a parameter of text, whose type is Observable<string>, and calling that function returns an Observable<any[]>. It's a higher-order function.
public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]> {
                        /*   ^^^^^^^^^^^   searchFunctionFactory parameter */
public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]> {
  /* searchFunctionFactory return value     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */

As comment notes, this is not Javascript syntax, but Typescript syntax.
So, if you call
const result = searchFunctionFactory(someVar);

result will be of the type
(text: Observable<string>) => Observable<any[]>

and you could then call it with
const resultTwo = result(someOtherVar)

to get a value whose type is Observable<any[]>.


Q:

jQuery: .load() getting no response

I have a simple HTML page with these jQuery statements:
$(document).ready(function() {
    $('#myDiv').load('mypage.html');
});

For some reason this doesn't load any HTML to the div. I used this method to make sure the source file exists - everything checks out fine. I tried using the error callback on .load() and the status is "error", but the response is empty. Looking at the console I see the following GET request:
[12:18:20.770] GET http://localhost/ [HTTP/1.1 200 OK 0ms]

Finally, when I do a simple $('#myDiv').html('test'); it loads fine, so I know the div is set up properly.
Can anyone think of what's going wrong here? I'm running WAMP on Windows, if that's any help.

A:

try
$('#myDiv').load('/root/folder/mypage.html');

also try.
$('#myDiv').html('Did i disappear?');
$('#myDiv').load('/root/folder/mypage.html');
///// Is myDiv empty when the page loads?


Q:

What is the true nature of weightlessness?

Suppose you are in an elevator and you and the elevator free-fall under the influence of gravity, you feel weightlessness. This weightlessness is because the Normal Force due to the elevator is $0$ N.
Now, suppose it's you without the elevator. The force due the air molecules [Normal Force] is $0$ N, if the fall is truly free-fall. But, in a general fall of an object when you drop it from the top of a building:

Will you feel weightless?

A:

Atmospheric drag will decelerate you, so you won't feel weightless.


Q:

Flat file data mapping to sibling nodes

I have a flat file coming in where each record is a customer and it has a shipto and billto address in that record.  The output schema has a customer record with an address child node.  I don't know how to map the 2 addresses from the incoming record to sibiling child nodes of the customer record.
I have an input file that is defined like:
<customer>
    <customernum/>
    <shipaddrcity/>
    <shipaddrstate/>
    <shipaddrzip/>
    <billaddrcity/>
    <billaddrstate/>
    <billaddrzip/>
</customer>

The output needs to end up looking like:
<customer>
    <customernum/>
    <addr>
        <type/>
        <city/>
        <state/>
        <zip/>
    </addr>
    <addr>
        <type/>
        <city/>
        <state/>
        <zip/>
    </addr>
</customer>

I'm quite new to biztalk and have been unable to find any decent examples of how to complete this using the Biztalk Mapper.  I'm also willing to listen to how to do this with xslt.

A:

You probably want something specific to BizTalk, and I don't know anything about BizTalk, but this might be helpful to you any way.
Given an input document of ...
<customers>
<customer>
    <customernum>1</customernum>
    <shipaddrcity>Cairns</shipaddrcity>
    <shipaddrstate>QLD</shipaddrstate>
    <shipaddrzip>b</shipaddrzip>
    <billaddrcity>Sydney</billaddrcity>
    <billaddrstate>NSW</billaddrstate>
    <billaddrzip>c</billaddrzip>
</customer>
<customer>
    <customernum>2</customernum>
    <shipaddrcity>d</shipaddrcity>
    <shipaddrstate>WA</shipaddrstate>
    <shipaddrzip>e</shipaddrzip>
    <billaddrcity>Melbourne</billaddrcity>
    <billaddrstate>Vic</billaddrstate>
    <billaddrzip>f</billaddrzip>
</customer>
</customers>

... this XSLT 1.0 stylesheet ...
<xsl:transform
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

<xsl:output omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<xsl:strip-space elements="*" />

<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="customer">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()[not(
      self::shipaddrstate|
      self::shipaddrzip  |
      self::billaddrstate|
      self::billaddrzip   )]"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="shipaddrcity">
  <addr>
    <type>ship</type>
    <city><xsl:value-of select="." /></city>
    <xsl:apply-templates select="../(shipaddrstate|shipaddrzip)" />
  </addr>
</xsl:template>

<xsl:template match="billaddrcity">
  <addr>
    <type>bill</type>
    <city><xsl:value-of select="." /></city>
    <xsl:apply-templates select="../(billaddrstate|billaddrzip)" />
  </addr>
</xsl:template>

<xsl:template match="shipaddrstate|billaddrstate">
  <state><xsl:value-of select="." /></state>
</xsl:template>

<xsl:template match="shipaddrzip|billaddrzip">
  <zip><xsl:value-of select="." /></zip>
</xsl:template>

</xsl:transform>

... when applied to the input document, will yield ...
<customers>
   <customer>
      <customernum>1</customernum>
      <addr>
         <type>ship</type>
         <city>Cairns</city>
         <state>QLD</state>
         <zip>b</zip>
      </addr>
      <addr>
         <type>bill</type>
         <city>Sydney</city>
         <state>NSW</state>
         <zip>c</zip>
      </addr>
   </customer>
   <customer>
      <customernum>2</customernum>
      <addr>
         <type>ship</type>
         <city>d</city>
         <state>WA</state>
         <zip>e</zip>
      </addr>
      <addr>
         <type>bill</type>
         <city>Melbourne</city>
         <state>Vic</state>
         <zip>f</zip>
      </addr>
   </customer>
</customers>


Q:

Dockerfile ENV variable substitution into another ENV variable

I am learning Docker and facing issue in substituting the value of one env variable into another env variable.
This is my Dockerfile
FROM ubuntu

ENV var_env=Tarun

ENV command="echo Hello $var_env"

CMD ["sh","-c","echo Hello $var_env"]

Now, after building it with tag name "exp", then
sudo docker run -e  "var_env=New Env Value" exp

It gives me correct output as
Hello New Env Value

But, if I see the environment variables associated by executing
sudo docker run -e  "var_env=New Env Value" exp env

It gives me this output:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=138aa8852d8d
var_env=New Env Value
command=echo Hello Tarun
HOME=/root

In it, the value of var_env environment variable is changed and value of command environment variable remains same.
I need to find a way so that if I change the value of var_env environment variable by the above command, it will update the value of var_env environment variable inside command environment variable also.
For reference: https://docs.docker.com/engine/reference/builder/#environment-replacement

A:

Option 1: at container start
You can use a wrapper script to create your environment variables with the inheritance that you wish. Here is a simple wrapper script
wrapper.sh
#!/bin/bash

# prep your environement variables
export command="echo Hello $var_env"

# run your actual command
echo "Hello $command"

Your dockerfile needs to be adapted to use it
FROM ubuntu
COPY ./wrapper.sh .
ENV var_env=Tarun
ENV command="echo Hello $var_env"
CMD ["sh","-c","./wrapper.sh"]

Option 2: during build
You can archive this by rebuilding your image with different build args.
Lets keep your dockerfile almost the same:
FROM ubuntu
ARG var_env=Tarun
ENV command="echo Hello $var_env"
CMD ["sh","-c","echo Hello $var_env"]

and run
docker build -t test .

this gives you your default image as defined in your dockerfile, but your var_env is no longer an environment variable.
next we run
docker build -t test --build-arg var_env="New Env Value" .

this will invalidate the docker cache only from the line in which you have defined your build arg. So keep your definition of your ARG close to where it is used in order to maximize the caching functionality of docker build.
You can find more about build args here: https://docs.docker.com/engine/reference/commandline/build/


Q:

Does A Program that is written with the Microsoft .NET framework compile/execute native code?

Newb question:
Does a Program that is written with the Microsoft .NET framework compile/execute native code?
I don't mean if there is a way not to have to install the .net framework on a machine.  Simply put: does a .net application run on another layer like Java (i.e. bytecode).

A:

A .NET application must run over the Common Language Runtime (CLR).
The CLR is Microsoft's implementation of the CLI standard. (And there are other implementations of the CLR beside the Microsoft .NET Framework i.e.: Mono, Portable.NET).
The CLR executes a type of bytecode known as the Common Intermediate Language (CIL).

A:

Sort of. The .NET compiler compiles your source code into IL (an intermediate language) and packages it in an assembly (usually one .DLL or .EXE file) which you deploy. At run-time, it is hosted by a CLR (common language runtime) which is responsible for executing the code, enforcing security rules, and so on. The main desktop CLR for Windows (there are others like Mono and Silverlight) doesn't interpret the IL, but rather "JIT"s (just in-time compiles) the IL code into native code before executing methods (functions).
Note there are actually some performance advantages to just in-time compilation. For example, the CLR can optimize the native code it generates based on performance characteristics of the machine it is running on like type of CPU, CPU cache size, number of CPUs, RAM size, etc. Traditional compilers can't do this as they don't know what machine the code they generate will ultimately be executed on.
Also, assemblies can be "pre-JITted" using a tool called ngen. In this process the native code is compiled from the IL before the assembly is executed and cached on disk. That way, no JITting overhead is incurred at run-time.


Q:

Parameterized dynamic sql returns no results

From a C# application I create the following parameterized dynamic sql statement as captured by SQL profiler:
Executing this statement returns no results:
exec sp_executesql N'SELECT IDWebFormAnswer FROM WebFormAnswers WHERE IDWebform = 55 AND IDWebFormQuestion = 478 AND (ANSWER = ''@answer0'')', N'@answer0 nvarchar(2)', @answer0=N'XL'

However, if I simply replace @answer0 with XL in the following, I get 4 rows returned.
exec sp_executesql N'SELECT IDWebFormAnswer FROM WebFormAnswers WHERE IDWebform = 55 AND IDWebFormQuestion = 478 AND (ANSWER = ''XL'')', N'@answer0 nvarchar(2)', @answer0=N'XL'

I do not understand why this happens? Am I building the query wrong?

A:

When you use a parameter you should not enclose it in quotes. If you do that then the parameter name becomes a literal string. With your code the query search for an ANSWER that contains the value '@Answer0' and there is none.
 exec sp_executesql N'SELECT IDWebFormAnswer FROM WebFormAnswers
      WHERE IDWebform = 55 AND IDWebFormQuestion = 478 AND
      (ANSWER = @answer0)', N'@answer0 nvarchar(2)', @answer0=N'XL'


Q:

Jquery failed to change Div border colour

I am trying to implement "changing Div border color" when clicking on one of the radio buttons. It works well for scenario 1 but won't work on scenario 2.

$(":radio:checked").closest(".discount").addClass("checked");
$(":radio").on("change", e => {
  const $div = $(e.target).closest(".discount");
  console.log($div);
  $(".discount").removeClass("checked");
  $div.addClass("checked");
});

$(":radio:checked").closest(".discount2").addClass("checked");
$(":radio").on("change", e => {
  const $div = $(e.target).closest(".discount2");
  console.log($div);
  $(".discount2").removeClass("checked");
  $div.addClass("checked");
});
.discount {
  border: 2px solid #cccccc;
  padding: 2px;
  padding: 10px;
  width: 100%;
  text-align: center;
  border-radius: 5px;
}
.discount.checked {
  border-color: red;
}
.discount2 {
  border: 2px solid #cccccc;
  padding: 2px;
  padding: 10px;
  width: 100%;
  text-align: center;
  border-radius: 5px;
}
.discount2.checked {
  border-color: red;
}

    <input type="radio" name="fruits" checked>Apple

    <input type="radio" name="fruits">Banana

    <input type="radio" name="drinks" checked>Milk

    <input type="radio" name="drinks">Zzz

    <input type="radio" name="drinks">Bbb

In scenario 2, when clicking on 'Zzz', the Div border "Red" is gone! Anyone know whats wrong ?

A:

There is no need to use multiple clases and such:
(I added another version of the example, where no
s were used (and changed the coloring a bit)

$('input[type=radio]:checked').parent().addClass('checked');
$('input[type=radio]').on('change',function(e) {
  var thisGroup = $(this).attr('name');
  if ($(this).is(':checked')) {
    $('input[name='+thisGroup+']').parent().removeClass('checked');
    $(this).parent().addClass('checked');
    }
 });
.discount, .discount-label{
    border: 2px solid #cccccc;
    padding:2px;
    padding:10px;
    width:10%;
    text-align:center;
    border-radius: 5px;
}

.discount.checked,.discount-label.checked {
    border-color: red;
}
.discount-label input[type=radio] {
  display: none;
  }
.discount-label.checked {
  background: red;
  color: #FFF;
  }

<input type="radio" name="fruits" checked>Apple

<input type="radio" name="fruits">Banana

<input type="radio" name="drinks" checked>Milk

<input type="radio" name="drinks">Zzz

<input type="radio" name="drinks">Bbb

example two

<input type="radio" name="fruits2" checked>Apple
<input type="radio" name="fruits2">Banana

<input type="radio" name="drinks2" checked>Milk
<input type="radio" name="drinks2">Zzz
<input type="radio" name="drinks2">Bbb


Q:

Find the order of the views in RelativeLayout

I have a RelativeLayout that includes a set of buttons. During app execution the order of buttons is changed.
How to find the order of the buttons in onDestroy()?

A:

for(int i = 0; i < parentLayout.getChildCount(); i++){
    View child = parentLayout.getChildAt(i);
    // other logic here
}


Q:

What happens half life (second) which Decay constant is $9 \times 10^{-8} s^{-1 }$

I've which decay constant is $9\times10^{-8}$ s$^{-1}$ so how to find half life (second) of this element? I asked my teacher but he doesn't have enough time to solve this. If anyone helps it would be great.
$\ln2 = 0,693$

A:

This is the formula for radioactive decay.
(decay constant)=ln2/(half life)
So
$9\cdot 10^{-8}=\frac{0.693}{\left( half\; life \right)}$
$\left( half\; life \right)=\frac{0.693}{9\cdot 10^{-8}}$


Q:

Composite of an immersion with the inverse map of another immersion is a diffeomorphism

Let $U\subset \mathbb{R}^k$ be an open set, $n>k$ and $\varphi_1,\varphi_2 : U\to \mathbb{R}^n$ be immersions, meaning continuously differentiable such that the differential taken in any point of $U$ is injective. Also, let $\varphi_1(U)=\varphi_2(U)=:U'$ and $\varphi_1$ and $\varphi_2$ be injective (and homeomorphisms $U\to U'$).
Then $\varphi_1^{-1} \circ \varphi_2 : U\to U$ is a diffeomorphism.
My problem is that $\varphi_1^{-1}$ need not be differentiable in the usual analysis sense, because $U'$ is not an open subset of $\mathbb{R}^n$. I am guessing that $d (\varphi_1^{-1}\circ \varphi_2)(x)$ should be $d(\varphi_1)(\varphi_1^{-1}(\varphi_2(x)))^{-1}\cdot d(\varphi_2)(x)$, because this is what happens if $k=n$ and it is still defined for $k<n$. However, I would need a way to apply the theorem on inverse functions to $\varphi_1$.

A:

I managed to solve this after all now (which is in part thanks to Sam's post, but I use a different idea).
Let $x\in U$ and $a:=\varphi_1(x)\in U'$. Choose $y\in U$ with $\varphi_2(y)=a$. It is enough to show that there is an open neighbourhood $V$ of $a$ in $U'$ such that $\varphi_1^{-1} \circ \varphi_2 : \varphi_2^{-1}(V)\to U$ is differentiable (by symmetry and because differentiability is a local property).
Without loss of generality, let the first $k$ rows of $d\varphi_1(x)$ be independent.
I want to use the fact that for suitably small $V$ as above, $V=W\cap U'$ with $W$ open in $\mathbb{R}^n$, there is a diffeomorphism $\Phi:W\to W'\subseteq \mathbb{R}^n$ such that $\Phi (V) = W'\cap \{ (x_1,..,x_n)\in W'\, |\, x_{k+1},..,x_n = 0 \}$.
In fact, one can be chosen as $\Phi: (x_1,..,x_k,x_{k+1},..,x_n)\mapsto (x_1,..,x_k,x_{k+1}-\varphi_{1,k+1}(\psi(x_1,..,x_k)),..,x_{n}-\varphi_{1,n}(\psi(x_1,..,x_k)))$
where, using the inverse function theorem, $\psi$ is the locally defined inverse function of $(\varphi_{1,1},..,\varphi_{1,k})$. (The differential of $\Phi$ is everywhere lower triangular with determinant 1.)
Let $p:\mathbb{R}^n\to\mathbb{R}^k$ be the projection to the first $k$ coordinates. The map $f:=p\circ \Phi \circ \varphi_1$ (defined on a suitable open set in $U$ containing $x$ and mapping to $\mathbb{R}^k$) is differentiable and injective.
For any $x'$ close to $x$, $df(x') = dp(\Phi(\varphi_1 (x'))) \cdot d\Phi (\varphi_1 (x')) \cdot d\varphi_1 (x')$. Now the first $k$ rows of $d\varphi_1(x')$ are independent (since $x'$ is close to $x$ and this is the case for $d\varphi_1(x)$) and  for $1\leq i\leq k$, the $i$th row of $d \Phi$ taken at any point is simply a $1$ at the $i$th coordinate and zeroes otherwise. The same goes for $dp$. So this composition of three matrices still has its first $k$ rows independent, so it is an invertible $k\times k$ matrix. It follows that $f$ is a diffeomorphism onto its image.
$\varphi_1^{-1}\circ \varphi_2$ equals the composition $f^{-1} \circ p \circ \Phi \circ \varphi_2$ on a suitably small neighbourhood of $y$ and all these maps are differentiable.


Q:

Using 'stack ghc', How do you compile a Haskell program with -fglasgow-exts?

I'm following Write Yourself Scheme in 48 Hours and I'm at the point in which the flag -fglasgow-exts must be used to compile to the program. I'm using a MacBook and Stack however when I try to run it with stack ghc scheme.hs -fglasgow-exts or stack ghc -fglasgow-exts scheme.hs I cannot get it to run. I tried using the command they used ghc -package parsec -o scheme, I get nothing as well.

A:

You are using GHC through Stack, so if you want to pass command line flags such as -fglasgow-exts to GHC, you need to do it after a --, so that Stack doesn'r gobble up the flags:
stack ghc -- -fglasgow-exts scheme.hs


Q:

Radius of Convergence of power series, with n! and $n^n$

During revision, I came across this problem:
The set of real numbers $x$ for which the series $$\sum_{n=1}^{\infty}{\frac{n!x^{2n}}{n^n(1+x^{2n})}}$$ converges is __.
I tried using the ratio test, but got stuck in the process of simplification.
(The answer is the series converges for $\mathbb{R}$.)
Sincere thanks for any help.

A:

For every $x \in \mathbb{R}$ and $n \in \mathbb{N}$ we have
$$
\frac{n!x^{2n}}{n^n(1+x^{2n})} \le a_n:=\frac{n!}{n^n},
$$
and
$$
\frac{a_{n+1}}{a_n}=\left(\frac{n}{n+1}\right)^n=\left(1+\frac{1}{n}\right)^{-n} \to 1/e.
$$
Therefore the series converges for every $x \in \mathbb{R}$.

A:

Hint: The terms in $x$ are not a problem. For note that $\frac{x^{2n}}{1+x^{2n}} \lt 1$. So compare with $\sum \frac{n!}{n^n}$.  If you can show this converges you will be able to conclude that your original series converges for all $x$.


Q:

NSJSONSerialization running on iOS 4

What am I missing here:
+ (id) JSONObjectWithData:(NSData *)data {
#if __IPHONE_OS_VERSION_MAX_ALLOWED < 50000
    //iOS < 5 didn't have the JSON serialization class
    return [data objectFromJSONData]; //JSONKit
#else
    NSError *jsonParsingError = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0   error:&jsonParsingError];
    return jsonObject;
#endif
}

I'm compiling on base SDK 5.0, deployment version is 4.0. When I run it on an iPhone 3G with 4.2.1 I get .....
dyld: Symbol not found: _OBJC_CLASS_$_NSJSONSerialization
Crash on startup....

A:

#if __IPHONE_OS_VERSION_MAX_ALLOWED < 50000 is evaluated on compile time. If you compile your code with the iOS 5 SDK the condition will be false. And the NSJSONSerialization code will be used anyway.
You should check if the NSJSONSerialization class exists. Like this:
+ (id) JSONObjectWithData:(NSData *)data {
    Class jsonSerializationClass = NSClassFromString(@"NSJSONSerialization");
    if (!jsonSerializationClass) {
        //iOS < 5 didn't have the JSON serialization class
        return [data objectFromJSONData]; //JSONKit
    }
    else {
        NSError *jsonParsingError = nil;
        id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0   error:&jsonParsingError];
        return jsonObject;
    }
    return nil;
}


Q:

validates uniqueness: { scope: [:foobar] } not working

I have a model that has a uniqueness validation on it something like:
class CurriculumRequirement < ActiveRecord::Base

  belongs_to :student

  belongs_to :curriculum_sequence

  validates :student_id,
    uniqueness: { scope: [:curriculum_sequence_id] }
end

The problem is that somehow duplicate records are being inserted into my database despite this validation. The place in which adding these records happens in a sidekiq background worker:
student.curriculum_requirements.where(curriculum_sequence: sequence).first_or_create
I think that what is happening is that 2 or more workers are executing the same code, and saving the record. Is there a way to put a lock or something on this record so that I don't get duplicates?

A:

Rails cannot guarantee uniqueness.  You need to create a unique index on the table on [curriculum_sequence_id, student_id] in the database.


Q:

Algorithm to vary coloring in plot series

I'm trying to get a multi-series plot to display with an even variance of color per plot.  I'm currently thinking something like
Plot |  R  |  G  |  B
----------------------
   0 |   0 |   0 |   0
   1 | 255 |   0 |   0
   2 |   0 | 255 |   0
   3 |   0 |   0 | 255
   4 | 128 | 128 |   0
   5 | 128 |   0 | 128
   6 |   0 | 128 | 128
   7 | 170 |  85 |   0
   8 |  85 | 170 |   0
   9 | 170 |   0 |  85

Is there already a well-established method for this?

A:

This is a well studied problem that unfortunately doesn't have a good answer.  Presenting data is as much an artform as a science.  Your approach, while yielding decent variance, falls short in two areas:

Equally weighting colors and series - your algorithm will produce both bold and muted colors.  The series receiving the bold colors will stand out and dominant the muted series.  They will appear more visually important even if they are not.
Aesthetics, aesthetics, aesthetics - many of your colors will end up unpleasant to the eye.  Here's your first 9 for instance:

So, how do we pick distinctive visually appealing colors?  The first question to ask is how many colors do you really need.  If you only really need nine, I would instead work with a tool like ColorBrewer or iWantHue and hardcode one of their palettes.  If you need forty distinct colors, the task is probably impossible.
From the master of data visualization Edward Tufte:

The often scant benefits derived from  coloring data indicate that
  even putting a  good color in a good place is a complex  matter.
  Indeed, so difficult and subtle  that avoiding catastrophe becomes the
  first principle in bringing color to  information: Above all, do no
  harm.


Q:

How can I add windows controls to a C++ desktop application in Visual Studio 2017?

I've started a new Visual C++ desktop application in Visual Studio 2017 and I'm having trouble getting started with the UI / View.  I normally do Windows development in C# with WPF, but I've had to go with C++ for various reasons on this one.
This seems like a rookie question, but I can't see any obvious way to add basic controls, like a TextBox, Label, Button, or Canvas.  Several hours of searching online hasn't yielded any concrete results either - only added confusion.
There's definitely a blank form there when I compile and run.  It even has a Menu -> Exit.
Is there a specific framework I should be using, like Windows Forms or MFC?  Are those even still supported?  Do all the UI elements have to be added in C++ code?  Did I choose the wrong type of Visual Studio solution?
More Info, by Request:
What I'm working on is a 3D modeling program, similar to something like Blender, but greatly simplified.  I'll need to use the FBX SDK, which Autodesk publishes, but it only supports C++.
I've already started one version which uses C# / WPF for the front-end. The goal is to incorporate the SDK later with either some sort of multi-project solution or a dll that I've compiled separately.  I haven't attempted something like this before.
The all-C++ version is my idea of trying to simplify everything by consolidating into one language, one project, and one solution.  I think if I do a really basic alpha version each way, it will help me choose the best answer and be doubly-educational.

A:

1)Is there a specific framework I should be using, like Windows Forms or MFC?
Using MFC in VC++ 2017, one can quickly using drag-n-drop, insert a number of window controls including ActiveX/COM components directly over dialog box. Thereafter a suitable class, interface events can be generated through in-built wizard. A variety of application choices SDI(Single-Document-interface)/MDI/Dialog based are available to start with.
2)Are those even still supported ?
MFC still works very well on VS 2017 and very user friendly, requires minimal coding IMHO.
3)Do all the UI elements have to be added in C++ code?
No. Let say you added some static text, accelerators, buttons on a dialog and generate a class with a single line of coding. You just insert the appropriate control events and invoke window messages suitably.
4) Did I choose the wrong type of Visual Studio solution?
Don't arise. Worked with MFC in 2010,2012,2015 and 2017, most of the MFC codes remains same. But some conversions are required when one have to switch from multibyte to unicode style.
Hope it helps a bit to clear your doubt. The window controls can be skinned pretty easily.


Q:

How to initialize one field using another in case class?

Suppose I have a case class like
case class Person(fname:String, lname:String, nickName:Option[String] = None)

On creating an instance like Person("John", "Doe"), I want nickName to be automatically assigned to fname, if one is not given. Eg:
val p1 = Person("John", "Doe")
p1.nickName.get == "John"

val p2 = Person("Jane", "Doe", "Joe")
p2.nickName.get == "Joe"

How can auto assignment of one field from another field be achieved?
Trying the solutions below in repl. I think this is something to do with repl
scala> case class Person(fname: String, lname:String, nickName:Option[String])
defined class Person

scala> object Person { def apply(fname:String, lname:String):Person = {Person(fname, lname, Some(fname))}}
  console:9: error: too many arguments for method apply: (fname: String, lname: String)Person in object Person
   object Person { def apply(fname:String, lname:String):Person = {Person(fname, lname, Some(fname))}}

A:

You can overload the constructor of the case class
case class Foo(bar: Int, baz: Int) {
     def this(bar: Int) = this(bar, 0)
}
new Foo(1, 2)
new Foo(1)

So you can check the case if nickName is none.
You can also overload it's apply method in the same way. In that way, then you can use
Foo(1,2)
Foo(1)

A:

Technical Solution (don't)
On the current definition of case classes, you can override the constructor of the case class and the apply method of its companion object, as described in the answer of Facundo Fabre.
You will get something like this:
object Person {
  def apply(fname:String, lname:String): Person = Person(fname, lname, fname)
}

case class Person(fname:String, lname:String, nickName: String) {
  def this(fname:String, lname:String) = this(fname, lname, fname)
}

This is technical correct and quite clever coding. But for my taste its a little bit too clever, because it breaks an important property:
CaseClass.unapply(CaseClass.apply(x1,x2,x3)) == (x1,x2,x3)

In other words: When I construct a case class using apply with some tuple of parameter and then deconstruct it using unapply I expect to get the original tuple I put into apply (ignoring currying and option type).
But in this case, this property is not true any  more:
Person.unapply(Person("John", "Smith"))
// result: Option[(String, String, String)] = Some((John,Smith,John))

Deconstruction using unapply is used for pattern matching (match{ case ... => ...). And this is a common use case for case classes.
So while the code is quite clever, it might confuse other people and break properties their code relies on.
Rephrase the problem (my suggestion)
When overly clever code is needed, it is often a good idea to rethink, what problem one tries to solve. In this case, I would suggest to distinguish between the nick name the user has chosen and a nick the system assigns to the user. In this case I would then just build a case class like this:
case class NickedPerson(fname : String, lname : String, chosenNick : Option[String] = None) {
  val nick = chosenNick.getOrElse(fname)
}

You can then just use the field nick to access the computed nick name, or use chosenNick if you want to know if the user has provided that nick name:
NickedPerson("John", "Smith").nick
// result: String = "John"
NickedPerson("John", "Smith", Some("Agent")).nick
// result: String = "Agent"

The basic properties about case classes are not changed by this code.


Q:

Is there any point to raise social stats to rank 5?

I've reached rank 4 on all 5 of my social stats which lets me start (and finish, as far as I can tell) any Social Link. Is there a reason to try and raise them to rank 5?
I know that Knowledge affects the results of the exams and that Proficiency allows to craft more items in one go (which I don't really need any more since I've already crafted the Unbreakable Lockpick, and the rest can be handled by the maid). Is there any use in raising Kindness, Charm and Guts to rank 5?

A:

Yes, there is a usage for increasing Kindness, Charm, and Guts to Rank 5. These social stats will be used to maximize different confidants.

Sojiro requires max kindness at rank 7
Munehisa requires max guts at rank 7.5
Makoto requires max charm  at rank 6
Haru requires max proficiency at rank 2
Hifumi requires max knowledge at rank 8


Q:

Create new file - exception options?

My assignment is to write a program that copies an existing file into a new file. The program prompts the user for the name of the existing file and then asks for the name of the new file (to create a copy of existing).
If the file already exists, 3 options should be presented:
1. Exit the program
2. Overwrite the existing file
3. Enter a new name for the file
In my project folder, I have two files old.txt and new.txt. When I enter them, it does not state the file already exists, it simply just overwrites the existing new.txt. Here is my code:
   existingFile = JOptionPane.showInputDialog("Enter the name of the "
        + "existing file: ");

    try
    {
        file = new File(existingFile);
        inputFile1 = new Scanner(file);
    }
    catch (FileNotFoundException e)
    {
        JOptionPane.showMessageDialog(null, existingFile +
                " does not exist. Exiting program.");
        System.exit(0);
    }

    newFile = JOptionPane.showInputDialog("Enter the name of the "
            + "new file: ");
    try
    {
        file2 = new File(newFile);
        createFile = file2.createNewFile();
        JOptionPane.showMessageDialog(null, "Copying " + existingFile +
                " into " + newFile);
    }
    catch (FileAlreadyExistsException e)
    {
        JOptionPane.showMessageDialog(null, newFile + " already exists.");
        System.out.println("Choose from the following choices:");
        System.out.println("1. Exit the program");
        System.out.println("2. Overwrite the existing file");
        System.out.println("3. Enter a new name for the file");
    }
    catch (IOException e){
        JOptionPane.showMessageDialog(null, "Something");
    }

Can you tell me why I am not getting an exception? Thanks.

A:

According to JavaDoc, File#createNewFile does not throw an exception but just returns false.
If you are on a recent Java version, you should use Files#createFile instead (which will throw the exception). The new Files/Path API is a cleaned-up version for doing file I/O (the legacy one has to be kept for compatibility).


Q:

Knockout attr binding with attributes like 'readonly' and 'disabled'

What's the suggested "best practice" way to use Knockout's "attr" data binding with standalone attributes like "readonly" and "disabled"?
These attributes are special in that they are generally enabled by setting the attribute value to the attribute name (although many browsers work fine if you simply include the attribute names without any values in the HTML):
<input type="text" readonly="readonly" disabled="disabled" value="foo" />

However, if you don't want these attributes to be applied, the general practice is to simply omit them altogether from the HTML (as opposed to doing something like readonly="false"):
<input type="text" value="foo" />

Knockout's "attr" data binding doesn't support this scenario. As soon as I provide an attribute name, I need to provide a value as well:
<input type="text" data-bind="attr: { 'disabled': getDisabledState() }" />

Is there a cross-browser way turn off 'disabled' or 'readonly'? Or is there a trick with a custom binding that I can use to not render anything if I don't want the item disabled or made read-only?

A:

Knockout's "attr" data binding does support this scenario just return null or undefined from your getDisabledState() function then it won't emit the attribute.
Demo Fiddle.

A:

You can also create a binding for readonly like this:
ko.bindingHandlers['readonly'] = {
'update': function (element, valueAccessor) {
    var value = ko.utils.unwrapObservable(valueAccessor());
    if (!value && element.readOnly)
        element.readOnly = false;
    else if (value && !element.readOnly)
        element.readOnly = true;
}
};

Source: https://github.com/knockout/knockout/issues/1100

A:

Knockout has an enable binding as well as a disable binding.
I'm not sure if these were available when the question was asked, but anyone referring back to this issue should be aware.


Q:

Chef just ignores return block

Chef noob alert!!!!
So, I have this code
ohai 'reload' do
  action :reload
end

if node['packages'].keys.include?('ffmpeg')
  return
end

I want the recipe to return control if 'ffmpeg' is installed
I didn't do any installation or config for Ohai. Chef zero run says the plugin path /etc/chef/ohai/plugins does not exist but it also says :
"- re-run ohai and merge results into node attributes" .. So I guess that works
But Chef just ignores the if block. Chef doesn't even mention it when I run chef zero with "info" level enabled.
I have tried another variation of it too
return if node['packages'].keys.include?('ffmpeg')

But the same results. Why is Chef so weird? Or does it seems so to be because I didn't bother learning ruby? Why do all Chef resources assume that everybody knows all the basics.

A:

You should familiarize yourself with the Chef Client Overview. Especially the order of the Reset node attributes phase, Compile the resource collection phase, and Converge the node phase.
Ohai information is reloaded every time before resources are compiled, during the reset phase. If the goal is to reload Ohai for your if statement then the Ohai resource you have here isn't need. That Ohai resource will run during the converge phase. The if block runs before that Ohai resource, during the compile phase. This also means that if statement will return during the compile phase and not during the chef client run.
As a general rule; resources run during convergence but any ruby code that's not in a ruby_block resource runs during compilation. This means any if statement is completed during compilation with the state of the node before the current client run.
Hopefully this helps clear up some confusion.


Q:

PhpStorm, about ftp sync

Just trying out this IDE but it already looks better than NetBeans in terms of speed and usability.. However, the main reason I chose it was the ftp sync feature, which.. doesn't seem to be working? When I create new project from existing files -> from remote server, ftp, it downloads the files and that's it. If I open it with open directory it doesn't upload changes to the server. So what am I doing wrong?

A:

With your project loaded, go to settings by either going to File > Settings or by pressing
CTRL + ALT + S.
From here go to Deployment > Options and then tick the "Uploaded changed files automatically to the default server".
It's also worth ticking the "Upload external changes" setting below; this will keep your local copy and the ftp copy synchronized by removing/renaming etc any file changes you make.

A:

Please refer to the corresponding help section. For the synchronization feature see Comparing Deployed Files and Folders with Their Local Versions.
File | Synchronize is not related to remote hosts at all, it synchronizes the files with the file system in case external changes were not detected automatically for some reason or you've disabled automatic files synchronization on frame activation.


Q:

Angular and JSON syntax getting confused with {}

I am new to angular and trying to integrate it within my application. I am attempting to use a simple ng-repeat (which works perfectly in an example project i setup). However, in the current project, i am using the Swig templating language, which fetches data from a .JSON file using {{ }} e.g:
person.html file:

 {{ myFirstName }}

 {{ mySurName }}

person.json file:
{
    "myFirstName"   : "Joe",
    "mySurName" : "Bloggs",
}

I think the problem i am facing, is that Swig uses {{ }} to get data from .JSON files, and Angular uses {{ }} too.
Here is my simple ng-repeat:

       {{country.name}} has population of {{country.population}}

Here is my simple controller:
require(['app'], function(app) {
'use strict';

   app.controller("MyCtrl", function($scope) {

      $scope.countries = [
          {name: 'France', population: 63.1},
          {name: 'United Kingdom', population: 61.8}
      ];

   });
});

When opening my HTML page, all that is displayed is:
 has population of
 has population of

Any ideas of how i can get around this?
Thanks
UPDATE
I would like angular to retrieve the data from the .JSON file
UPDATE Folloiw David Beech's recommendation
Application Tree:
- application
     - resources
           - CSS
           - img
           - JS
           - data
                - countries-data.json
     - pages
           - countries.html

In the example solution below my $http.get was
$scope.countries  = [];
  $http.get('/resources/data/countries-data.json', function(data){

Error shown in Firebug: "NetworkError: 404 Not Found - http: // localhost:8000/resources/data/countries-data.json"

A:

To answer part 2 of your question and get angular to retrieve the json file use the $http service. http://docs.angularjs.org/api/ng/service/$http
app.controller("MyCtrl", function($scope, $http) {
  $scope.countries = [];
  $http.get('/path/to/data.json', function(data){
      $scope.countries = data;
  }, function(error) {
     //handle error here
  });
});

And to answer part 1:
I'm not familiar with swig and after a quick google I notice this is available server-side on node or client side and you don't specify how you are using it.
If you are using it server-side I would recommend you check it's documentation about escaping certain bindings to ensure pages are being delivered with the bindings in the html (you can check this by 'view page source' option in chrome).
UPDATE: http://paularmstrong.github.io/swig/docs/api/#SwigOpts
I notice here you can set the varControls binding to something other then '{{' and '}}'.
If you are using it client side then I would ask why you need it at all.. angular works best when you give it as close to complete and exclusive control over the DOM as possible. I'm sure anything that is possible in most templating engines is possible in angular with a little more learning and training and there are plenty of resources for that if you just do a little googling.
Hope this helps.


Q:

Monte Carlo simulation for the log-normal distribution

Consider $X$ that follows a log-normal distribution with parameters $\mu=1$ and $\sigma=1$. The moments are known: $m_n=E[X^n]=e^{n+n^2/2}$. For example, $m_{10}=e^{60}$ (of the order of $10^{26}$). I simulate samples of $X^{10}$ in Mathematica of length $1,000,000$, and I notice that the mean values of such samples are always less than $e^{60}$:
Mean[RandomVariate[LogNormalDistribution[1, 1], 1000000]^10] < Exp[60]
(* Comment: The output seems always to be True. *)

Why is Monte Carlo simulation not working with the log-normal distribution? The tails of the distribution (the extreme values) should be the problem, I think. Is there a modification of the Monte Carlo simulation to tackle this problem?

A:

From your expression above for $m_n$, you can derive the following:
$$P[X^n > m_n] = 1 - \Phi(n/2)$$
For $n=10$, that's less than 0.3 per million, so the vast majority of samples will be smaller than $m_n$ (and it's not unusual to not have a single sample out of 1 million turn out to be larger than $m_n$). It's the rare but very large values that pull up the moment, as you mention, and it gets more evident for larger moments.
One relatively simple method for improving a Monte Carlo method that depends critically on rare events is to use importance sampling and "tweak" the distribution to make those events more likely, and then weigh our samples to get back to the distribution we're actually trying to sample from. One such approach is called exponential twisting (or tilting). For example, for a normal distribution $Y\sim \mathcal{N}(\mu,\sigma^2)$, consider the twisted random variable:
$$Y_\theta \sim \mathcal{N}(\mu + \theta\sigma^2,\sigma^2)$$
For some function $f$ of interest, you can show that:
$$E(f(Y)) = E_{\theta}\left[f(Y)p(Y)/p_{\theta}(Y)\right]=E_{\theta}\left[f(Y)e^{(\mu-Y)\theta+\sigma^2\theta^2/2}\right]$$
The expectation $E$ is taken with respect to the distribution of $Y$, while $E_{\theta}$ is with respect to that of $Y_{\theta}$. The parameter $\theta$ can be tuned depending on the problem at hand (e.g. which events we need to make more likely), and $\theta = 0$ corresponds to the regular MC method.
The above identity means that you can then estimate the expectation of interest on the left by Monte Carlo like this:

Draw $Y_i \sim \mathcal{N}(\mu + \theta\sigma^2,\sigma^2)$
Compute the weighted sample average $\frac{1}{M}\sum_{i=1}^M f(Y_i) e^{(\mu-Y_i)\theta+\sigma^2\theta^2/2}$

For your specific problem, you would take $\mu = 10$, $\sigma^2 = 100$ and $f(x) = e^x$.
For a range of values of $\theta$, sampling only 1000 $Y_i$'s for each value, I obtain the following estimates (the horizontal line is the exact value):

We see that the regular MC method ($\theta=0$) performs poorly, and that values near $\theta=1$ produce a result much closer to the true value.
Obviously, this is a somewhat contrived example: if I simply take $\theta = 1$, then $Y_i = e^{\mu+\sigma^2/2}$ for all $i$, and I get the exact result with no sampling variation, which we already knew from the beginning. The method can still be used in other situations where a closed-form solution or other efficient numerical approximation does not exist.


Q:

Cómo validar campo select con JQuery

¿Cómo puedo validar en un campo select que al seleccionar una opción haga x función? Intenté hacerlo pero no funcionó. ¿Alguna forma de hacerlo?
registerGenderCheck = false;
$(function() {
    $('#registergender').on('click', function() {
        var x = $('#registergender');
        var bt = $('.button');

        if(x.val()){
            registerGenderCheck = true;
            x.css('border', '1px solid #40de49');
        }
        // else {}
    });
});

<select id="registergender">
    <option value="">Selecciona tu género</option>
    <option value="">Masculino</option>
    <option value="">Femenino</option>
</select>

A:

Para lograr lo que quieres debes cambiar la forma en la que intentas capturar el cambio de valor del elemento select, debes utilizar el evento change y no click, de la siguiente forma:

$(function() {
  $('#registergender').on('change', function() {
    if($(this).val() == 'masculino'){
      $(this).css('border', '1px solid #40de49');
    }else{
      $(this).css('border', '1px solid red');
    }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="registergender">
  <option value="">Selecciona tu género</option>
  <option value="masculino">Masculino</option>
  <option value="femenino">Femenino</option>
</select>

En el código HTML de tu select, te faltaba asignar los value de cada option.