What group-policies have you applied?

Question: I have set about 10 group-policies, and it works OK.
Although, it would be interesting to see what kind of things IT-administrators enforce.
If you have a ton of policies, just show some, that you feel really changes something.
I guess you could avoid "default permit" -> block everything you can, and only keep things unlocked, that is directly needed.
This question refers to Windows Servers :) Although I won't shun Mac nor Linux administrators.
Comment: You should make this a community wiki.
Comment: You're right. Good point.
Answer: I love Group Policy. It makes me able to do my job and to allow my company to leverage the collective talents of 3 people over more than 1,000 PCs and server computers in multiple Customer sites.
Nearly every one of my Customers has the majority of the following uses of Group Policy:

Install software with Software Installation policy
Install software with startup scripts
"Work over" machines' factory Windows installations after their initial domain membership with a one-time startup script (Add/Remove Windows components, clean up the start menu, reomve unwanted vendor-provided software, etc)
Setup the "user environment" (Folder Redirection, Group Policy preferences to put out registry preferences, desktop shortcuts, etc)
When appropriate, "locking down" the user environment (for kiosks, special-purpose PCs, etc)
Directing computers to WSUS servers and setting update policies
Setting IPSEC policy settings
Deploying wireless Ethernet settings (the corporate SSID and security configuration, etc)
Logon scripts to "map" "drives"
Logon scripts to clean out per-user "temp" directories, and startup scripts to clean out per-machine "temp" directories
Restricted group policy to populate local groups with domain groups
Control third-party applications that use registry settings to influence their behaviour through creation of custom Administrative Templates
Doing ANY type of misc. maintenance, either per-machine or per-user, that I need to do via startup or logon scripts

That's my "off the top of my head" list. I'll come back and revise if I think of more.
Answer: We use group policy to:

Point workstations to our WSUS server
Run a program that checks if the antivirus software is installed and if not, install it
Disable registry editing
Set Office security level
Set ODBC connections
Redirect a user's Desktop and My Documents to a file server
Map network drives
Set power saving settings (out monitors, hard drives and computer to sleep after xx minutes)
Check versions of in-house applications
Disable iTunes, Windows Media Player, VLC, etc.
Set disk space quotas

[EDIT] Added the following:

Enforce password policy
Standardize desktop wallpaper and screen savers

And a few others I can't remember off the top of my head.
Answer: Quite a few; they tend to ping-pong between low numbers and high numbers.  Right now the numbers are high on account of a number of WSUS policies that need to be consolidated.  I don't think GPOs are the kind of thing that are ever really "finished", but instead get constant fine-tuning and refinement as time goes by.
Primary uses include:

Desktop lockdown
Software installation
Logon (and logoff) scripts
Startup (and shutdown) scripts
WSUS config
Passwords/security/etc
Folder redirection

One - maybe - novel use is a logon script that (1) checks if the computer is a server, (2) checks if the user is a "sensitive" one that we want to track, and (3) sends an email to our admins giving computer name, user name and time if either condition is met.  We call it "proactive paranoia" and while it's not exactly security, it is an extra layer of comfort in that we know a little bit more about what's going on.
We also maintain some dummy OUs in our live AD that we occasionally drop some users and/or computers into for testing out new stuff, and have a small army of scripts that we can add anywhere for certain one off jobs (e.g if we feel like defragging all PCs any time we can just drop in a shutdown script for it).
Future plans include moving a lot of the vile registry hacks and maybe some other stuff from our main logon script over to Preferences.

What group-policies have you applied?


Kalman filter Welch and Bishop

Question: I am trying to understand Kalman filter from a highly recommended pdf by Welch and Bishop https://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf. I am highly confused with one terminilogy x_k. There are three of such kinds x_k, x_cap_k and x_cap_minus_k. He says x_cap_minus_k is the a priori estimated state at time step k given knowledge of the process prior to step k. x_cap_k is the posteriori state estimate at step k given measurement z_k.
I am not able to understand what is x_k and how do I interpret it?
Answer: Let us make this concrete with an example. Let us say that we want to invest money into a company. We start to observe the value of the stock of that company on a daily basis: we start at day $t=0$ at 1 pm and then we receive (every day at 1 pm) real values $z_0, z_1, z_2, ...$. Let us assume that we want to invest money into the company if its stock value is above 7 dollars (I have no experience in finance, so please forgive me if this example is nonsense but lets stick to it in order to explain what the Kalman filter does).
The approach of the kalman filter is that this time series actually originates from a different time series $x_0, x_1, x_2, ...$ (the so-called 'true' state). The idea behind that is that there exists an actual value of the stock $x_t$ and some disturbed variant $z_t$ of it. If we want to base decisions on whether or not we should do some investment we should know what the 'actual' value of the stock is (and not whether or not the 'current' value is high that migh easily change and might only be currently high due to some weird non-measurable short term effects of the market).
In the most simple setup the model assumes that the 'true' state $x_t$ (that we can never observe) proceeds over the time as
  $$x_{t+1} = ax_t + \text{error}$$
i.e. the next state is a linear map of the current state (plus error). Notice that this looks as if this is a quite stupid model as
  $$x_t \approx a^t x_0 + \text{error}$$
so the value should either diverge to infinity (if $a > 1$) or converge towards $0$ quickly (if $a < 1$) but due to the fact that the error is added at each step, this is not the case. One sample that was produced like this looks as follows: For $a=0.7$ and each error being $N(0,1)$-distributed,

I.e. these very simple models can already model quite wiggly (and senseful) functions. So this would be the true stock value that is always hidden from us. What we can see is the observed value $z_t$. This is produced from the true state as
  $$z_t = bx_t + \text{error}$$
Let us assume that $b=1.2$ and the errors are $N(0,1)$-distributed here as well, then we will see a picture like this:

I.e. we can only see the red line but the black line is hidden from us. Let us say that every day around 10am in the morning your boss approaches you and asks you: "Well, how is the state of that company? Should we invest money?". So now you need to make a prediction of the true state $x_t$. You look at the graph but as it is only 10am in the morning, you do not have the most recent observed value, i.e. you only have the observed value until yesterday [red line] and your estimations [grey line]:

So, based on the recent past (nah, the observed value was low, my past estimations were low, I think the value goes down a little) you make some first prediction of the true state:

This is $\hat{x}_t^{-}$. The hat means: its an estimation. The $x_t$ means: it it an estimation of $x_t$, the true state for today. The minus means: you did this prediction before you observed the observeable value $z_t$ for today (this might give you some important information, see below!). You predicted around 6.7 dollars, so the answer would be: no, do not invest money, the value is too low. However, at 1 pm the new observeable value $z_t$ comes in. It is really high. And since you know that $b=1.2$ (which means that the market tends to overestimate the trus value slightly but not by too much) you correct the prediction upwards a little bit:

This is the $\hat{x}_t$, the 'a poszteriori', i.e. 'after you got access to the recent observeable value $z_t$'. All of a sudden your prediction changes and you tell your boss that he should invest money into that company.
The task of the Kalman filter is to give you these predictions of the true state $\hat{x}_t$ and $\hat{x}^{-}_t$. I.e. it aims to reconstruct the black curve from the red one. The important fact one can prove about it is that with respect to some conditions (i.e. among the linear filters if I recall correctly) it does that as good as it is only possible, i.e. there is no better linear filter than the Kalman filter.

Kalman filter Welch and Bishop


Significantly different in categorical variables

Question: I am working with a categorical variable with 4 mutually exclusive classifications (CC, CD, DC and DD). I had counted how many times each classification is repeated. (for example, 33 CC, 40 CD, 50 DC and 100 DD). I would like to know if there are a significant difference between them, and between which of them.
I am doing this with Matlab
Comment: Significantly different what? Total count / frequency / proportion?
Comment: It sounds like you are interested in testing against a null hypothesis that the counts across categories are equal.  But there's not enough information in the question to be sure. In this case, you might look at chi-square goodness-of-fit test, standardized residuals from a chi-square goodness-of-fit test, and Sison and Glaz multinomial confidence intervals.
Comment: Exactly, my idea is to compare if the total count of one category is significantly different from another.
Comment: I am not sure why Chi-square goodness-of-fit test could be use in this situation. I haven't got a model to fit. Or am I confused?
Answer: It looks like you want to test if "there are equal counts". That must be reformulated to "equal expected counts" to be a valid hypothesis. That is a model, namely, an equal probability model on 4 different levels of a categorical variable (in R a categorical variable is named a factor,) I do not know about matlab.
There is not enough information in your post for a full answer, I will assume independent sampling, otherwise we cannot advance ... So in R I will do, it should be possible in matlab:
 (tab  <-  as.table(c("CC"=33, "CD"=40, "DC"=50, "DD"=100))  )
 CC  CD  DC  DD
 33  40  50 100
  chisq.test(tab)

    Chi-squared test for given probabilities

data:  tab
X-squared = 49.448, df = 3, p-value = 1.047e-10

The test above assumes by default equal probabilities, otherwise null probabilities can be given via an argument p=c(0.2, 0.2, 0.2, 0.4), say.


How to make "See all category" link button to display rest of the text with jquery 1.11 and above

Question: I have an issue on the dropdown text.
Below snippet using jquery 1.11.1

$(".more").toggle(function(){
    $(this).text("Less category").siblings(".complete").show();
}, function(){
    $(this).text(" All category").siblings(".complete").hide();
});
.complete{
    display:none;
}

.more{
    background:black;
    color:red;
    font-size:13px;
    padding:3px;
    cursor:pointer;
}

li{
    list-style:none;
}

kategori 1

kategori 2

kategori 3

kategori 4

kategori 5

See all category

Below snippet using jquery 1.8.3

$(".more").toggle(function(){
    $(this).text("Less category").siblings(".complete").show();
}, function(){
    $(this).text(" All category").siblings(".complete").hide();
});
.complete{
    display:none;
}

.more{
    background:black;
    color:red;
    font-size:13px;
    padding:3px;
    cursor:pointer;
}

li{
    list-style:none;
}

kategori 1

kategori 2

kategori 3

kategori 4

kategori 5

See all category

Problem is, "See all category" text will disappear if I use jquery 1.9.1 and above.
If I use jquery 1.8.3 and lower "See all category will appear and work just fine.
Can anyone help, thanks anyway :)
Comment: This variant of the `toggle` function was removed in jQuery 1.9
Answer: You need to use the click handler as this variant of toggle is removed in jQuery 1.9

$(".more").click(function() {
  $(this).text(function(i, text) {
    return text == 'Less category' ? 'All category' : 'Less category';
  }).siblings(".complete").toggle();
});
.complete {
  display: none;
}
.more {
  background: black;
  color: red;
  font-size: 13px;
  padding: 3px;
  cursor: pointer;
}
li {
  list-style: none;
}

kategori 1

kategori 2

kategori 3

kategori 4

kategori 5

See all category

How to make “See all category” link button to display rest of the text with jquery 1.11 and above


How can vector algebra have applications in analytic geometry?

Question: Well, I was reading Apostol and in it's historical introduction section of Vector Algebra chapter he said that best features of quaternion analysis and Cartesian geometry were united and a new subject called vector algebra sprang into being. And after two lines, he said that there are applications of vector algebra in analytic geometry which are discussed in next chapter.
So, my question is how can vectors have applications into analytic geometry when the former one was created through the elements of the later one?
I've tried to have a glance on the next chapter but I couldn't get to understand how did Cartesian geometry gave birth to vector algebra since it isn't mentioned in the book.
Answer: I will not give here a general point of view. Instead, I give an example of the vector approach, here with the "dot-product tool" (in other cases, it will be the cross-product or the determinant that play a central role):
Let us look for the (common) angle $A_iOA_j$ $i \neq j$ in a regular tetrahedron $A_1A_2A_3A_4$  with centroid $O$ (an angle that every chemist knows because it is linked to methane molecule $CH_4$ (https://en.wikipedia.org/wiki/Methane)).
Instead of rather complicated considerations, it suffices to proceed like this:
$$\tag{1}\vec{OA_1}+\vec{OA_2}+\vec{OA_3}+\vec{OA_4}=0 \ \ \ \ \text{(by symmetry.)}$$
Let us assume that $\|\vec{OA_k}\|=1$ (WLOG because a scale change does not modify angles).
Then, taking the dot product of (1) with itself:
$$\sum_{k=1}^4 \vec{OA_1}^2+\sum_{i \neq j} \vec{OA_i}.\vec{OA_j}=0$$
$$4+\sum_{i \neq j} \cos(\theta)=0 \ \ \ \iff \ \ \ 4+12 \cos(\theta)=0,$$
giving $\theta=acos(-1/3) \approx 1.91$ radians $= 109.5°.$


Shortest path in weighted digraph, constrained to include a minimum number of nodes

Question: Say you have a weighted digraph with n nodes.
And you want to find the shortest path to all n nodes from a source node.
But you are constrained by the fact that the shortest path must go through a minimum number of other nodes, but can only touch any given node once in a given path.
Are there any algorithms which could be useful in this case?
Answer: There are two constraints in this problem:

The shortest path from the source to a node should not go through any node more than once.  The only case in which going through a node more than once may reduce the cost of a path is when it contains a cycle of negative cost.  However, under the constraint that the number of nodes must be minimum, there can be no negative cycles.  Hence this constraint has no effect.
The shortest path must go through a minimum number of other nodes.  Said otherwise, the shortest path must be chosen among those with minimum number of edges.  This is accommodated by adopting an edge cost with two components.  The first component is $1$ for every edge and the second component is the length of the edge.  Given costs $c_1 = (n_1,l_1)$ and $c_2 = (n_2,l_2)$, we have $c_1 < c_2$ if and only if $n_1 < n_2$ or $n_1 = n_2$ and $l_1 < l_2$.  Costs are added component-wise.

Since all edge costs are effectively positive, Dijkstra's algorithm works.


Hibernate not creating table despite correct configurations and no error messages in logs

Question: I'm creating a new database table in my Spring Boot application but the problem is that the table is not being created in the database despite the correct configurations and no log error messages. Here is my model class:
@Entity
@Table(name="user_avatar")
public class UserAvatar {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="user_avatar_id")
    private String userAvatarId;

    @OneToOne
    @JoinColumn(name="user_id")
    private User user;
    @Column(name="random_string")
    private String randomString;
    @Column(name="style_options")
    private String styleOptions;
    @Column(name="avatar_type")
    private String avatarType;
    ...

Here is my application.properties file:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://${DB_HOST}/${DB_NAME}?createDatabaseIfNotExist=true&autoReconnect=true&allowPublicKeyRetrieval=true&useSSL=false&useUnicode=yes&characterEncoding=UTF-8&characterSetResults=UTF-8
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true

spring.jpa.hibernate.ddl-auto=create
server.tomcat.uri-encoding=UTF-8
spring.data.jpa.repositories.bootstrap-mode = default

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.properties.hibernate.connection.characterEncoding=utf-8
spring.jpa.properties.hibernate.connection.CharSet=utf-8
spring.jpa.properties.hibernate.connection.useUnicode=true

And my console logs, shorten to show the Hibernate create queries:
Hibernate: create table student_storybook (student_storybook_id integer not null auto_increment, is_quiz_completed tinyint(1) default 0, is_story_completed tinyint(1) default 0, by_student_id integer, for_storybook_id integer, in_progress_quiz_session integer, in_progress_story_session integer, primary key (student_storybook_id)) engine=InnoDB
2021-09-11 09:43:20.561 DEBUG 5684 --- [           main] org.hibernate.SQL                        : create table teacher (teacher_id integer not null auto_increment, name varchar(255), user_id integer, primary key (teacher_id)) engine=InnoDB
Hibernate: create table teacher (teacher_id integer not null auto_increment, name varchar(255), user_id integer, primary key (teacher_id)) engine=InnoDB
2021-09-11 09:43:20.575 DEBUG 5684 --- [           main] org.hibernate.SQL                        : create table user (id integer not null auto_increment, avatar_data TEXT, avatar_type integer, email varchar(255), gender varchar(255), password varchar(255), reset_password_token varchar(255), role varchar(255), username varchar(255), user_avatar_id integer, primary key (id)) engine=InnoDB
Hibernate: create table user (id integer not null auto_increment, avatar_data TEXT, avatar_type integer, email varchar(255), gender varchar(255), password varchar(255), reset_password_token varchar(255), role varchar(255), username varchar(255), user_avatar_id integer, primary key (id)) engine=InnoDB
2021-09-11 09:43:20.595 DEBUG 5684 --- [           main] org.hibernate.SQL                        : create table user_avatar (user_avatar_id varchar(255) not null auto_increment, avatar_type varchar(255), random_string varchar(255), style_options varchar(255), user_id integer, primary key (user_avatar_id)) engine=InnoDB
Hibernate: create table user_avatar (user_avatar_id varchar(255) not null auto_increment, avatar_type varchar(255), random_string varchar(255), style_options varchar(255), user_id integer, primary key (user_avatar_id)) engine=InnoDB

As you see here, despite the Hibernate create query being executed the required user_avatar table is not being created in the database:

Why is this and how I can resolve this issue?
Answer: Turns out it was because of a very trivial mistake: I had the primary key for the UserAvatar class as a String when it should have been an int type:
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="user_avatar_id")
private int userAvatarId;

After this change, the table was created successfully.
On a different note: Hibernate console logs were not showing the error message that detailed why the table was not being created despite having the following settings in the application.properties file:
 DEBUG = true
 logging.level.org.springframework.web= DEBUG
 logging.level.org.hibernate= ERROR

But that's a question for another post :)


WebView in AsyncTask doInBackground method?

Question: I'm using a WebView that injects some JS code on a page. This webview has a "domino effect", like:
webView.setWebViewClient(new WebViewClient{
  ...
@Override
public void onPageFinished(WebView view, String url) {
    if(url.contains("http://A")){
        view.loadUrl("javascript: window.location.assign('http://B');")
    } else if(url.contains("http://B"){
        //do another stuff
    }
  ...
});

And it takes about 10~15 seconds. I'm currently doing this directly on Activity, but i'm not satisfied with it's performance. And more, if user minimizes the application during the process, it stops from working.
Now i'm trying to doInBackground(), but i can't neither instantiate a WebView on a non UI thread or call loadUrl() on a received WebView (from AsyncTask<> parameter). What can i do ?
Should I do all this work with a IntentService ?
EDIT:  I'm injecting JS to return an ArrayList. I'm using webview only to parse the webpage and get what i want.
Thanks !
Comment: A View component is supposed to be drawn on UI thread only
Comment: Are you saying you're not satisfied with the speed at which the WebView opens after you create the client and pass it to the WebView?
Comment: No.. I wasnt clear.. I'm injecting JS to return an ArrayList. I'm using webview only to parse the webpage and get what i want ^^
Answer: You cannot update your UI from background thread.
 Use
 runOnUiThread(new Runnable() {
                public void run() {

                // Update your UI

            }
        });

If it takes delay, use ProgressDialog and alert the user that page is being loaded.
Comment: How to send variable from doInBackground  to webview from inside runOnUithread ?i tried following but didn't work! mWebView.loadUrl("javascript:MyFunction(" + sb.toString() + ")");


Macro matching a single expr after [expr*], path[tt*] and ident[tt*] branches

Question: I'm trying to make a macro that I can call in the following manner:
mactest!(some::Path[1, 2, AnotherName[3, 4]])

Which would be equivalent to the following:
make_result(
    "some::Path",
    1.convert(),
    2.convert(),
    make_result(
        "AnotherName",
        3.convert(),
        4.convert()
    )
)

where convert is some trait that will be implemented for a bunch of types. (convert and make_result has the same result type).
This is as far as I've come:
// Note: u32 is used as an example result type.
// The real code attempts to create a more complicated object.

trait Foo {
    fn convert(&self) -> u32;
}

fn make_result(name: &str, data: Vec<u32>) -> u32 {
    // This example ignores name and makes a meaningless result
    data.iter().fold(0,|a, &b| a + b)
}

#[macro_export]
macro_rules! mactest {
    ( [ $($inner:expr),* ] ) => {{
        let mut result = Vec::new();
        $(
            // Process each element.
            result.push(mactest!($inner));
        )*
        result
    }};
    ($name:path [ $($inner:tt),* ] ) => {
        make_result(stringify!($name), mactest!([$($inner),*]))
    };
    ($name:ident [ $($inner:tt),* ] ) => {
        make_result(stringify!($name), mactest!([$($inner),*]))
    };
    // Process single value. This is never matched?
    ($x:expr) => {
        $x.convert()
    };
}

The first matching branch of the macro is supposed to match each element of a list to either the path/ident[items] or the single item .convert branch at the end. But the final branch is never reached, with rust complaining error: expected ident, found '1' when single items enter the macro, i.e. mactest!(1).
My reasoning as a beginner rust user is that the macro has four patterns: [expr*], path[tt*], ident[tt*] and expr. When I pass something like 1 into the macro, I don't see why any of the above patterns should match/interfere.
Can someone explain why this doesn't work? Is there a workaround to get the intended result?
Comment: your macro doesn't work in the regular case: https://play.rust-lang.org/?gist=6ce29f2366951025ad4b&version=stable . It complains with "expected one of `.`, `]`, or an operator, found `,`"
Answer: macro rules are tried by starting with the first one and going down from there. So if you want to prevent your other rules from triggering in special cases, you need to put the special case rule first.
Try it out in the playground
Comment: @porgarmingduod Bed time for me, but this (among other things) is explained in [TLBoRM](https://danielkeep.github.io/tlborm/).  Short version: the `macro_rules!` parser is *really* dumb, and the fact that `1` isn't an ident *is* the problem.  That specific formulation is *impossible* to get working; see section 2.3.1.
Comment: Aside from that, the problem is that the outer invocation matches as `:expr`, which prevents the "special case" rules from *ever* matching.  This can't be done except by incremental parsing.
Comment: What confuses me is that, in the case of `mactest(1)`, I don't see how any of the first three rules matches `1`. Those are the special cases, which is why they are at the top. `1` is not an `ident` nor a `path`. To narrow it down, [this](https://play.rust-lang.org/?gist=dc58b6e911d75f546cb3&version=stable) error message really confuses me. @DK. What does incremental parsing mean in this context?
Comment: @DK. Thanks, that is just the kind of resource I needed to shore up my shortcomings about rust macros. Can't believe it never showed up when I was googling various macro stuff.


How can i fix ActiveAdmin 'Edit' action route that doesn't seem to work

Question: I've just created the active admin dashboard and everything seemed to work but when creating a new admin user I've received an URLGeneration error, though the user is created on going back to the dashboard. The same error occurs when I try to 'View' the user I've just created or any user including the default admin user. The same goes as I click to the 'Id' of the admin users.
(The Error)
     ActionController::UrlGenerationError in Admin::AdminUsers#show

showing .../bundler/gems/activeadmin-b9f189ff671a/app/views/active_admin/resource/show.html.arb where line #2 raised:

 No route matches {:action=>"edit", :controller=>"admin/admin_users", :id=>#<User id: nil, email: "", created_at: nil, updated_at: nil, name: nil, provider: nil, uid: nil, image: nil>}, possible unmatched constraints: [:id]

(config/routes.rb)
Rails.application.routes.draw do
 devise_for :admin_users, ActiveAdmin::Devise.config
 ActiveAdmin.routes(self)

(models/admin_user.rb)
class AdminUser < ApplicationRecord
 devise :database_authenticatable,
     :recoverable, :rememberable, :validatable
end

Admin file:
(admin/admin_users.rb)
ActiveAdmin.register AdminUser do
  permit_params :email, :password, :password_confirmation

  index do
    selectable_column
    id_column
    column :email
    column :current_sign_in_at
    column :sign_in_count
    column :created_at
    actions
  end

  filter :email
  filter :current_sign_in_at
  filter :sign_in_count
  filter :created_at

  form do |f|
    f.inputs do
      f.input :email
      f.input :password
      f.input :password_confirmation
    end
    f.actions
  end

end

(admin/dashboard.rb)
ActiveAdmin.register_page "Dashboard" do

  menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") }

  content title: proc{ I18n.t("active_admin.dashboard") } do
    div class: "blank_slate_container", id: "dashboard_default_message" do
      span class: "blank_slate" do
        span I18n.t("active_admin.dashboard_welcome.welcome")
        small I18n.t("active_admin.dashboard_welcome.call_to_action")
      end
    end

  end # content
end

Answer: No route matches {
 :action=>"edit",
 :controller=>"admin/admin_users",
 :id=>#<User id: nil, email: "", created_at: nil, updated_at: nil, name: nil, provider: nil, uid: nil, image: nil>
}, possible unmatched constraints: [:id]

My read on the above is that the edit route is expecting an ID but is instead getting a bad value. Combining that with this
ActionController::UrlGenerationError in Admin::AdminUsers#show
and with your description of what you did leads me to believe that there's a problem with the way edit links are being generated within the show view.
Can you update your question to include the ActiveAdmin 'show' view? It would also be helpful to include your ActiveAdmin resource file (should be in app/admin).
Comment: Hi Matt, I believe that Active Admin auto-generates the views for such functionality, or am I wrong? I'm just getting started with Ruby, any clarification would be great
Comment: Sorry, I phrased that poorly. Yes, the view itself is generated (using the resource file). What I meant to ask was if you could share the rendered HTML produced by the view; my thought was to look at the HTML for the link to see if anything was malformed.
Comment: I checked it out, it's the same as the one ActiveAdmin has on github


Erro ao tentar usar usar MediaPlayer

Question: tentei elaborar um Botão que quando pressionado execute um som, mas sei como importar esse som e nao sei como localizar a pasta Raw, quando tento usar essa linha:
mpSongButtons = MediaPlayer.create(MainActivity.this, R.raw.);

Da erro, ou seja, essa Raw nao existe, alguem poderia me ajudar?
Answer: public class ExecutaSomExemplo {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Conecta o button do xml
        Button button = (Button)findViewById(R.id.myButton);

        //Método de ação do clique
        button.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {

                      //Cria o objeto MediaPlayer que irá receber o arquivo de som
                      MediaPlayer mPlayer = MediaPlayer.create(MainActivity.this, R.raw.nomedoarquivo);

                       //Toca a música
                       mPlayer.start();
                    }
                }
        );
    }
}

No seu caso específico em que você está usando o Eclipse a pasta raw não vem criada como padrão, você tem que criá-la: clique com o botão direito sobre a pasta res, selecione Novo... depois Pasta e digite o nome da pasta, como na imagem:

Então, você pode criar novos arquivos lá, seja arrastando-e-soltando o arquivo dentro dela, ou clique novamente com o botão direito na pasta raw e selecione Novo... e depois Arquivo.
Comment: mas nao consigo usar esse metodo pois nao existe o endereço R.raw.nomedoarquivo, da erro quando tento usar "raw cannot be resolved or is not a field"
Comment: Certifique se o arquivo é do tipo `.mp3` exemplo: nomedoarquivo.mp3, também certifique que o arquivo está no diretório `res/raw` do seu projeto. Caso tudo esteja certo dê um `Clean/Build` e tente rodar novamente.
Comment: Mas nao existe a pasta Raw, essa é minha duvida, nao existe essa pasta no meu projeto, estou usando a ultima versao do ADT Plugin
Comment: Qual IDE você está usando @Jeiferson? Eclipse, Netbeans, Android Studio?
Comment: IDE Eclipse @iTSangar
Comment: Adicionei uma breve solução pro seu caso na resposta que eu eu criei @Jeiferson, caso precise de algo mais é só falar =)
Comment: Vlw cara, era isso...

Erro ao tentar usar usar MediaPlayer


Prolog: Can't see the file

Question: I am learning how to program in prolog. I'm currently learning I/O and encountered the following problem.
I want to read the file dane.txt using this program:
czytajPlik :-
    open('dane.txt',read,X),
    current_input(CI),
    set_input(X),
    kodOdczytujacy,
    close(X),
    set_input(CI).

kodOdczytujacy :- read(Term), obsluz(Term).

obsluz(end_of_file):-!.
obsluz(Term) :-
         write(Term),nl,kodOdczytujacy.

However when in Prolog, when I try to use czytajPlik., I get the following error:
ERROR: open/3: source_sink `'dane.txt'' does not exist (No such file or directory)

The file exists and has the proper name.
Comment: Do you run the program with as active directory, the directory that contains `dane.txt`?
Comment: You should give the absolute path of 'dane.txt'.
Answer: The error means that the Prolog interpreter (I'm guessing SWIPl) cannot open the file, because it cannot find the file.
The interpreter looks in the directory it was started in, by default. You should either qualify the file with the path, or cd into the correct directory.
So let's say that you've started Prolog from a directory ~/prologstuff while the file is in ~/misc.
czytajPlik :-
    cd('../misc'),
    open('dane.txt',read,X),
    ...

or
czytajPlik :-
    open('../misc/dane.txt',read,X),
    ...

should solve your problem.

Prolog: Can't see the file


Showing that a complex function is continuous

Question:
Find out, and give reason, whether $f(z)$ is continuous at $z = 0$ if $f(0) = 0$ and for $z\neq 0$ the function $f$ is equal to $(\operatorname{Re}z^2)/|z|$.
Answer: If $z=x+iy$, then $|Re (z^2)|=|x^2-y^2| \le x^2+y^2=|z|^2$, hence, for $z \ne 0$:
$|f(z)| \le |z|$.
This gives $f(z) \to 0=f(0)$ for $z \to 0$.


Path for learning cuica

Question: Really hard to find anything for this lovely crazy little thingy. Can anyone give me hints for a learning path?
What are the first skills I need to acquire? Even sounding up and downstrokes I guess? And after that?
Should I start with 2-pitch rhythms or directly work on 3-pitch rhythms, treating 2-pitch as a simplification? Or is 3 pitch stuff for more advanced learners and it´s better to focus on 2 pitch and keeping the sounds even?
Google yields extraordinary few authorative materials. E.g. I could not find a single book about the cuica.
The cuica is a friction drum. You rub a bamboo stick which is fastened in the center of a drumhead. The stick is rubbed to produce a sound. The pitch can be changed by pressing fingers on the drumhead.
The sound is described to be like a dog's bark, or like monkeys, the latter description probably being more accurate.
Here is a video showing a cuica:

A cuica in a pop song can be heard e.g. in Red Hot Chili peppers Walkabout (starting from 1.45,

)
Answer: I think you are over thinking it.  When I was an undergad, I lived with a percussion major and had a grand old time messing with his cuica.
As you know it is a percussion instrument, but more specifically, it is going to add a specific sound, rather that to keep time, such as a drumset or clave would.
The music surrounding the cuica is basically Brazilian folk music, most specifiacally Samba, but I expect that the instrument appears in other non-samba Brasillian styles. Anyway, this music probably not written down, and performed anyone that was in the corner band.  No specific skills needed.
Just wet your rag, and go to town.  Practice.  Experiment with different amounts of moisture, start with slightly damp.  Experiment with pressure and speed.  You can also use a finger tip  or the side of your hand to press on the drum head, thus changing its tension and pitch.
Have fun.

Path for learning cuica


How to create view of referenced nodes with fields?

Question: I have node reference field which can take multiple values in it and I want to create a view of fields of these referenced nodes.
How do I achieve this?
Answer: Adding node reference field to contextual filter and select "Provide a default argument" in it and select "Content ID from URL". This will do the needful.


How to implement a java equivalent for WaitForMultipleObjects windows API?

Question: We need to have a cleanup thread that will do cleanup repeatedly. The cleanup will be triggered

after a specified time period or
after a specified event

In Windows we have:
DWORD WINAPI WaitForMultipleObjects(
  _In_       DWORD  nCount,
  _In_ const HANDLE *lpHandles,
  _In_       BOOL   bWaitAll,
  _In_       DWORD  dwMilliseconds
);

...which will wait for specific events for specified time. The wait will be released when any of the specified event occurs or when the time-out occurs.
Do we have a similar implementation in Java? I tried the CountDownLatch and CyclicBarrier. CountDownLatch cannot be reset again, so couldn't use that and CyclicBarrier has some dependency on the number of threads. Looking for something better than CyclicBarrier. Will Timer and TimerTask help?
Comment: If you were able to use WaitForMultipleObjects, would you be passing true or false for `bWaitAll`?
Comment: We will be waiting for one of the event to occur. So we will be passing false for bWaitAll.
Answer: One option would be to use a BlockingQueue. Multiple implementations are provided in the java.util.concurrent package.
Your event producers could put events into the queue.
Your cleanup thread could poll for an event, with a timeout, with the method BlockingQueue.poll( long timeout, TimeUnit unit ).
Comment: Thank you. Will try this solution now.
Comment: Thank you @Andy Thomas. BlockingQueue works fine for this requirement. We are also trying with TimerTask and Timer. TimerTask and Timer seems to be cleaner. The task is simple that we don't have to use ScheduledThreadPoolExecutor. Our only concern is that it should not hold the system resources. Which one would you prefer? BlockingQueue or the TimerTask and Timer. Thanks again.


Montar notícia agrupando resultados por classe de usuário

Question: Estou desenvolvendo um sistema de notícias onde uma certa classe de usuário vai poder postar uma ou mais notícias para todos verem ele funciona perfeito, mais para uma melhor visualização gostaria que essas mensagens fossem agrupadas pela classe do usuário que postou. vou dar o exemplo de como está abaixo:
aqui eu faço um select normal:
SELECT a.id_salapostagem, a.titulo, a.mensagem, a.data_lancamento,
b.descricao
FROM salapostagem a
INNER JOIN usuariotipo b on a.usuariotipo_id = b.id_usuariotipo
WHERE a.cursograde_id = 0;

aqui é a resposta que tenho:
id_salapostagem  |        titulo            |                                   mensagem                                             |     descricao
      6          |   teste de mensagem 01   |   teste de mensagem 01 esta mensagem vai aparecer para todo mundo 2015-12-09 16:15:21  |     Webmaster
      7          |   teste de mensagem 02   |   teste de mensagem 02 esta mensagem tbm vai aparecer para todos  2015-12-09 16:19:13  |     Webmaster
      12         |   teste de mensagem 03   |   teste de mensagem 03 esta mensagem vai aparecer para todo mundo 2015-12-09 16:15:21  |     administrador

Este é o laço que faço para notícia aparecer
<?php
mysql_data_seek($sqlNot, '0');
while($not = mysql_fetch_array($sqlNot) ){
    if($_SESSION["usuariotipoid"] != 4 || $_SESSION["usuariotipoid"] != 5 || $_SESSION["usuariotipoid"] != 9){
    $Botao = "Seção: ".$not["descricao"]."";

}
    ?>

ADMINISTRAÇÃO
<?php echo $Botao; ?>

<?php echo $not["titulo"]; ?>
<?php echo $not["data_lancamento"]; ?>

            <?php echo $not["mensagem"]; ?>

        <?php
}

As notícias aparecem na sequência em que foram postadas dessa forma:
| ADMINISTRAÇÃO                                Seção: Webmaster   |
| teste de mensagem 01                       2015-12-09 16:15:21  |
| teste de mensagem 01 esta mensagem vai aparecer para todo mundo |

| ADMINISTRAÇÃO                                Seção: Webmaster   |
| teste de mensagem 02                       2015-12-09 16:19:13  |
| teste de mensagem 02 esta mensagem vai aparecer para todo mundo |

| ADMINISTRAÇÃO                              Seção: administrador |
| teste de mensagem 03                       2015-12-09 16:15:21  |
| teste de mensagem 03 esta mensagem vai aparecer para todo mundo |

E eu gostaria que aparecessem assim:
| ADMINISTRAÇÃO                                Seção: Webmaster   |
| teste de mensagem 01                       2015-12-09 16:15:21  |
| teste de mensagem 01 esta mensagem vai aparecer para todo mundo |
|                                                                 |
| teste de mensagem 02                       2015-12-09 16:19:13  |
| teste de mensagem 02 esta mensagem vai aparecer para todo mundo |

| ADMINISTRAÇÃO                              Seção: administrador |
| teste de mensagem 03                       2015-12-09 16:15:21  |
| teste de mensagem 03 esta mensagem vai aparecer para todo mundo |

Desde já agradeço qualquer ajuda, pois está difícil de resolver isso.
Answer: Uma das coisas é acrescentar o campo que você quer ordenar no ORDER BY:
SELECT   a.id_salapostagem, a.titulo, a.mensagem, a.data_lancamento, b.descricao
FROM     salapostagem a
INNER    JOIN usuariotipo b on a.usuariotipo_id = b.id_usuariotipo
WHERE    a.cursograde_id = 0
ORDER BY descricao

A outra é criar uma situação para mostrar o título uma vez só. Por exemplo algo assim:
$titulo= '';

...

while($not = mysql_fetch_array($sqlNot) ){
   if( $titulo!= $not['descricao'] ) {
      echo 'ADMINISTRACAO            Secao: ' . $not['descricao'];
      $titulo=$not['descricao'];
   }

Esse é só um exemplo, teria que adequar para o campo correto.


Serve 404 from HAProxy when no acls match

Question: I'm currently re-configuring HAProxy using 1.5dev-17. What I'd like to do is return a 404 error when there is no backend to use for a particular request.
Our current configuration uses the default_backend to route to our django app servers, but when there are a whole lot of probing requests (like a pen-test) that match none of the other configured backends, our django servers grind to a halt as they try to serve these invalid requests, eventually returning a 404.
I'd like to serve the 404 from HAProxy rather than delegating to the django backends. I'm currently achieving this with a hack:
frontend www
    ...
    default_backend nomatch

backend nomatch
    errorfile 503 /var/www/http/404.http

And within the 404.http file I set the 404 status code in the headers. This works, but feels very wrong. Is there a better way of achieving this with HAProxy? Or should I use a regular backend and just let that handle responding with a 404?
Comment: @JasonFloyd `HTTP/1.0 404 Not Found` followed by some other headers, then a blank line, then the `` content.
Comment: What's the contents of the 404.http file?
Answer: If you would be okay with any of the following response codes: 200, 400, 403, 405, 408, 429, 500, 502, 503, or 504.
Then you could do something like this:
frontend www
  ...
  default_backend no-match

backend no-match
  mode http
  http-request deny deny_status 400

http-request: http://cbonte.github.io/haproxy-dconv/1.7/configuration.html#4-http-request
Accepted response codes described in errorfile: http://cbonte.github.io/haproxy-dconv/1.7/configuration.html#errorfile

edit: newer versions off HAProxy also support 404 as return code: https://docs.haproxy.org/2.4/configuration.html#3.8-errorfile
Answer: After wanting something similar this is the same thing I came up with. It felt wrong but it works very well in practice and is much cleaner than trying to blacklist particular urls. Just be sure to leave a comment so no one comes across it thinking it's incorrect.
Answer: This is not what the OP asked for, but in case you the reader stumbled across here while using TCP mode (like I did), the corresponding directive you want to use is tcp-request content. So you would have:
frontend my-tcp
  ...
  default_backend no-match

backend no-match
  tcp-request content reject

Of course in TCP mode there's no HTTP response code. You can also use silent-drop instead of reject if you so wish.

Note that you CANNOT use tcp-request connection because it cannot be used in a backend section. If you try to put it in a frontend section instead, haproxy will warn you:

a 'tcp-request' rule placed after a 'use_backend' rule will still be processed before

... which means it's overriding all your use_backend and default_backend directives.
While you technically CAN use tcp-response content, there's no good reason to do so in this use case (as compared to using tcp-request content.


SQL update with multiple criteria

Question: I know this is quite simple but I've been looking at this for awhile and can't seem to identify what the issue is. I want to update a row in a table using two criteria. When I use either criteria, the table updates fine but when I combine them, it doesn't work.
This is the query
$updatequery = "UPDATE query SET audio='$finalpath' WHERE content='$title' AND WHERE userid LIKE '%$regID%'";

An example of the reg id:
APA91bGHS59rrpM0sbX9PIYT3SzXs-W1yEtGa2xGMGJXi8O1vW2SrgN7koHDj2o6ZwKvkd3TxtzhktsiVtQNSYQRa4uNDF7Yy0VOf0BJfQOnJWMtN2WBQjmVDsuU-0GxmceNLd8SWqOM
An example of content :
Where can I find a car
Answer: You only need to use the where keyword once:
$updatequery =
"UPDATE query SET audio='$finalpath' WHERE content='$title' AND userid LIKE '%$regID%'";
# "WHERE" removed here ------------------------------------^

Mandatory comment:
Using string manipulation like this leaves your code vulnerable to SQL-injection attacks. You should really consider using prepared statements instead.
Answer: Your query is wrong.
Try this:
 $updatequery = "UPDATE query SET audio='$finalpath' WHERE content='$title' AND userid LIKE '%$regID%'";

EDIT:
Where is needed only once.
Answer: You can have only one WHERE clause, so this is a syntax error:
WHERE content='$title' AND WHERE userid LIKE '%$regID%'

Combine the logic in a single clause:
WHERE content='$title' AND userid LIKE '%$regID%'

The WHERE clause essentially works like conditionals in any other language.  You can build up as complex a tree of boolean conditions as you like, as long as the whole thing resolves down to a boolean then it's fine.
Answer: WHERE content='$title' AND userid LIKE '%$regID%'

Where is needed only once

SQL update with multiple criteria


rpm -ivh, failed dependency already installed

Question: I'm having trouble installing a set of custom build rpms.  The spec file produces 7 binary rpms.  I installed 5 of them using rpm -ivh and then decided that I also needed the remaining two.  When I try to install those, rpm complains:
# sudo rpm -ivh foo-lib-cpp-devel-0.7.0-1.x86_64.rpm
error: Failed dependencies:
    foo = 0.7.0-1 is needed by foo-lib-cpp-devel-1:0.7.0-1.x86_64

Yet that exact dependency is already installed:
# rpm -q foo
foo-0.7.0-1.x86_64

I discovered 'rpm -R', which provides more details on the package:
# rpm -qvRp foo-lib-cpp-devel-0.7.0-1.x86_64.rpm
auto: /usr/bin/pkg-config
manual: boost-devel
manual: libevent-devel >= 1.2
auto: libfoo.so.0()(64bit)
auto: libfootnb.so.0()(64bit)
auto: libfooz.so.0()(64bit)
auto: pkgconfig(foo) = 0.7.0
rpmlib: rpmlib(CompressedFileNames) <= 3.0.4-1
rpmlib: rpmlib(FileDigests) <= 4.6.0-1
rpmlib: rpmlib(PayloadFilesHavePrefix) <= 4.0-1
rpmlib: rpmlib(VersionedDependencies) <= 3.0.3-1
manual: foo = 0.7.0-1
manual: zlib-devel
rpmlib: rpmlib(PayloadIsXz) <= 5.2-1

The only suspicious thing I see is the '-1:' token in the lib-cpp-devel package, which I can't explain.
What is the '-1:' and could that be related to this issue?  How can I debug this further or workaround it?  FWIW this is all occuring on a relatively fresh install of CentOS 6.
Thanks!
Comment: -1 refers to the rpm release. For example, foo is version 0.7.0, rpm release 1. In the spec file, you'll commonly see it defined like: Release: 1%{?dist}
Comment: It's not the '-1' but the '-1:' (note the colon).  The colon isn't present in the package filename.
Answer: If you are absolutely sure that the two packages are compatible, you could do one of the following:

Remove the current foo-lib-cpp-devel package using the --nodeps switch on rpm.

1a. Install the new foo-lib-cpp-devel package using rpm (may have to use --nodeps or --force switches)
OR

Install the new foo-lib-cpp-devel package using the --force --nodeps switches on rpm.
Answer: The -1: token is the Epoch tag, so it looks like your RPM may have been built with an Epoch equaling 1. If that's the case, foo-lib-cpp-devel's dependency on foo must include the Epoch, like so:
Requires: foo = 1:0.7.0-1

Or, using macros:
Requires: foo = %{epoch}:%{version}-%{release}


Alguém consegue me explicar como esse código funciona?

Question: Não consigo entender o uso do prototype.allReplace e nem o uso do RegExp.
O que são esses parâmetros?
String.prototype.allReplace = function(obj) {
    var retStr = this;
    for (var x in obj) {
        retStr = retStr.replace(new RegExp(x, 'g'), obj[x]);
    }
    return retStr;
};

console.log('T35t3 d3 35t4g1o'.allReplace({4: 'a', 3: 'e', 1: 'i', 5: 's'}));

Não tem uma forma mais simples de fazer essa troca de números por letras?
Answer: Colocas duas perguntas:

como funciona o código
se não há forma mais simples

A segunda pergunta gera respostas baseadas em opiniões, depende do caso, da aplicação e dos dados disponíveis... por isso não vou responder.
Em relação à primeira pergunta o código funciona assim:
Quando defines uma função no protótipo de um objeto nativo como "String", o this dentro dessa função será a String.
Quando tens um objeto tens pares de chaves e valores. Por exemplo {foo: 123} tem a chave "foo" e o valor "123". Assim quando usas var x in obj vais percorrer todas as chaves de um dado objeto, cujo valor fica guardado dentro da variável x.
Assim, dentro desse ciclo/loop, com o replace o código troca todas as ocorrências da chave pelo "valor" dessa chave. O segundo argumento "g" da RegExp quer dizer exatamente "todas as ocorrências".
No final, depois do loop retorna a frase com as trocas feitas.
Dá uma olhada a este exemplo para ver em detalhe  que se passa dentro do loop:

String.prototype.allReplace = function(obj) {
  let retStr = this.toString();
  for (const x in obj) {
    console.log(
      retStr,
      new RegExp(x, 'g'),
      obj[x],
      retStr.replace(new RegExp(x, 'g'), obj[x])
    );

    retStr = retStr.replace(new RegExp(x, 'g'), obj[x]);
  }
  return retStr;
};

console.log('T35t3 d3 35t4g1o'.allReplace({
  4: 'a',
  3: 'e',
  1: 'i',
  5: 's'
}));
Answer: A outra resposta já explica como o código funciona, então vou focar na sua outra pergunta:

Não tem uma forma mais simples de fazer essa troca de números por letras?

Tem outras maneiras de fazer, mas se elas são mais simples ou não, é uma questão de opinião. De qualquer forma, vamos à elas.

Opção 1: criar uma única regex em vez de várias
Uma característica do seu código é que ele cria várias expressões regulares, uma para cada chave do objeto passado (no caso, uma regex para cada dígito). Talvez alguém ache que é "mais simples" criar uma única regex (pode ser um pouco "melhor" por criar menos coisas e fazer tudo de uma vez, por exemplo, mas novamente, é questão de opinião).
Podemos juntar todas as chaves da regex em uma única expressão e fazer um único replace:

String.prototype.allReplace = function(obj) {
    let r = new RegExp(Object.keys(obj).join('|'), 'g');
    return this.replace(r, function(match) {
        return obj[match];
    });
};

console.log('T35t3 d3 35t4g1o'.allReplace({4: 'a', 3: 'e', 1: 'i', 5: 's'}));

No caso, eu pego todas as chaves de obj (que no caso são os dígitos 4, 3, 1 e 5) e junto tudo em uma única expressão: 4|3|1|5. Essa regex usa alternância (o caractere |, que significa ou), o que quer dizer que ela pega qualquer um destes dígitos.
Em seguida, eu uso uma função no segundo parâmetro do replace, que por sua vez recebe como parâmetro o match (ou seja, o trecho que foi encontrado pela regex). Eu sei que este trecho pode ser qualquer um dos dígitos (4, 3, 1 ou 5), então eu retorno o valor correspondente (as letras a, e, i ou s, obtidas do próprio obj), que será o valor usado na substituição.
No final, todos os dígitos são substituídos pelas respectivas letras.
Obs: se todas as opções só possuem um caractere (no caso, todas são apenas um dígito), a regex também poderia ser [4315]. Mas eu usei alternância para deixar o código mais "genérico", assim ele pode receber strings de vários tamanhos. Por exemplo, se eu quiser trocar abc por xyz:

String.prototype.allReplace = function(obj) {
    let r = new RegExp(Object.keys(obj).join('|'), 'g');
    return this.replace(r, function(match) {
        return obj[match];
    });
};

console.log('abc 123 abc'.allReplace({'abc': 'xyz'}));

Opção 2: não usar regex
Talvez seja mais simples percorrer a string e ir substituindo seus caracteres um a um, usando o obj para substituir os caracteres desejados, e mantendo os demais:

String.prototype.allReplace = function(obj) {
    let s = '';
    for (let i = 0; i < this.length; i++) {
        let c = this.charAt(i);
        if (obj.hasOwnProperty(c)) {
            s += obj[c];
        } else {
            s += c;
        }
    }
    return s;
};

console.log('T35t3 d3 35t4g1o'.allReplace({4: 'a', 3: 'e', 1: 'i', 5: 's'}));

Para cada caractere da string, eu uso hasOwnProperty para verificar se obj contém uma chave com aquele caractere. Caso tenha, eu uso o respectivo valor na substituição, e caso não tenha, eu mantenho o mesmo caractere da string original.
A diferença para a primeira opção é que, como estou percorrendo os caracteres um a um, não é mais possível trocar trechos maiores (como o exemplo anterior que troca abc por xyz).

Enfim, estas são algumas alternativas ao seu código. Se é mais simples ou não, vai da opinião de cada um...


Site Republica Virtual fora do ar

Question: Já a alguns dias o site Republica Virtual que servia como base para muita gente realizar consulta de CEP e receber os dados com facilidade, esta fora do ar, não sei se alguém sabe o motivo de estar fora mas o meu questionamento é se existe outra fonte confiável por onde podemos extrair tais dados.
Comment: Relacionado: [Como buscar um endereço por CEP nos Correios?](http://pt.stackoverflow.com/q/400/4337)
Answer: O próprio site dos correios tem um serviço:
https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente?wsdl
Comment: Consigo ver o WSDL mas dá erro no parse dizendo que `The namespace '' already contains a definition for 'cliente'`
Comment: Faça um teste com um projeto novo e verifique se o problema ocorre.
Comment: Fiz direto no `WcfTestClient`, sem projeto nem nada e ocorreu o erro. Tentando consumir como `ServiceReference` num projeto novo também deu problema.

Site Republica Virtual fora do ar


python docx changing text when outputting table cells

Question: I am using the python docx package basic example for reading table cell text.
The document is 40MB. However even when split I find this is happening too.
`
from docx import Document
import re
<code>wordDoc = Document('./mydoc.docx')
for table in wordDoc.tables:
    for row in table.rows:
        for cell in row.cells:
            print(cell.text)
</code>
`
The document has the below text "(3.4.2:2) WCS allows an..."
However when output from the example code it converts it to this for some reason
"(:) WCS allows an..."
Does anyone know how I can stop this? Is it a bug or something potentially in the document?
There are other similar cells that don't have this issue, but no pattern to what is causing it.
Tried cutting document down in case it was size related, however still happens.
Answer: Found that there was a hidden link in these as part of the index.  I did ctrl + A to select the whole document. Then CTRL+6 to remove all links.
Then processing of the document looked correct.


How to include large set of data with my iOS app at install?

Question: I have a big database of data I want my app to install with, too big for NSDefaults, essentially it's too big for me to type in (it's computer generated).
I can easily serialize it into a hierarchial NSDictionary format and a pList, but I'm stumped on how to get that pList from my running app into a file that Xcode will include in app builds, and where to install it, etc.
I've tried dumping my pLists out with .description to try to just copy and paste them into an Xcode .plist file. But pList.description outputs in the format
Problem8 = {
Term1 = 3;
};

While the Plist files in Xcode require a format like
<key>Problem8</key>
<string>3</string>
<key>Term1</key>

Feeling pretty dumb here, I'm obviously missing something easy to get to the correct format, or to save them serialized to disc in a manner that Xcode will include in future builds.
Comment: One problem with the generated data is that I can't regenerate it for the user, as it's got some random values that would make it different if regenerated. I want this data set identical for every user (the data describes the introductory levels for a game), so I need to include this data as file or pList/etc at installation.
Answer: If you have a dictionary, use writeToFile:atomically: to save it to a file and initWithContentsOfFile: to load it back in.
That said, if it's a lot of data, and particularly if you don't need all of it loaded all the time, consider saving a Core Data store and deploying that.
Comment: I understand how to do that. But how to I make that file part of my installation package for my app in Xcode so it's included in my app submission/TestFlight distributions/etc?
Comment: Add the file to a copy files build phase (like images are added into the build).
Comment: So if I understand this correctly, I run the app on my device/simulator, generate the file to it's local sandbox, and use the organizer to download a copy to my mac's file system, and copy the data file from there into my project? Thanks for your comments, greatly appreciate you taking time to help me through this.
Comment: Yes. Or you can have a desktop app which generates the file instead. If the app can generate it then why deploy with a big file?


Permutation testing

Question: So let's say I did an experiment comparing mutated samples vs non mutated where I have an unequal number of samples (100s (non mutated) vs 5-10 (mutated)). I think the groups might have different variances so I could do a welch t-test to address that issue. But a colleague thinks doing permutation testing and drawing sample size equal to the smallest group would be better. While I think in some cases permutations are great but in this case I'm not so sure. Also looking at his R code I'm not sure it's correct.. shouldn't you be sampling from each group independently rather than pooling them
# groupA is mutated samples and groupB is non mutated samples
groupA <- which(samples[,i] == "mutated")
groupB <- which(samples[,i] == "non_mutated")
sample.size <- length(groupA)
groupAB <- c(groupA,groupB)

for(j in seq(1:length(colnames(results))))
{
    actual.med.diff <- median(na.omit(results[groupA,j])) - median(na.omit(results[groupB,j]))

    for(k in 1:1000)
    {
        index <- sample(1:length(groupAB), size=sample.size, replace=FALSE)
        perm.groupA <- groupAB[index]
        perm.groupB <- groupAB[-index]
        perm.med.diffs[k] <- median(na.omit(results[perm.groupA,j])) median(na.omit(results[perm.groupB,j]))
    }
    median.perm.pval <- length(which(perm.med.diffs <= actual.med.diff)) / 1000
}

Answer: Permutation testing is a good way to go with a group with few observations; however, you are not quite doing it right. You don't choose the sample size of the permutation draw, rather you permute the labels for your drawn sample. for instance if you observe:
outcome <- rnorm(100)
group <- sample(c("a","b"), 100, prob=c(.1,.9),replace=TRUE)
medianDifference <- abs(diff(tapply(outcome,group,median)))

One permutation draw would look like
groupPerm <- sample(group, length(group))
permMedianDifference <- abs(diff(tapply(outcome,groupPerm,median)))

To get your p-value, you find the percentage of times permMedianDifference > medianDifference
Comment: Thanks Ian, yes I realized after I posted it what looked wrong and it was the permuting the labels. What about the assumption of the difference in distributions
Answer: A problem with doing a permutation test of equality of means occurs if you think that the possible difference in variance of the two groups will remain even if the null of equal means is true. In that case the label assignments are not arbitrary when the null is true (the observations are not exchangeable) – since you'd appear to have no basis to argue that you can swap labels under the null, the reasoning behind the permutation test wouldn't seem to hold.
[Perhaps there's some other argument for being able to permute the labels under the null, but I don't know what it is.]
However, imagine instead that you have a case where you posit that mutation either has no effect on the distribution (the null case), or some effect on the distribution (impacting both mean and variance at the same time, say).
In that case, under the null you can permute (since the labels really are arbitrary at the null). But under those assumptions, you could also carry out an equal-variance t-test (as long as the assumption of normality under the null was reasonable enough that you're happy with the resulting test properties); the fact that equality-of-variance is violated under the alternative doesn't impact the correctness of the significance level nor of p-values (though it would impact power, so if you're relying on power calculations for sample size, you would definitely worry about it then – simulation would be one way of getting a sense of what the power could be like under various relative variances at any given difference in means).
Comment: You make a good point that is often overlooked in talking about "non-parametric" tests. The H0 for permutation based tests is always H0: f(x) = g(x), where f and g are the distributions of the two groups, so differences in variance can reject the null more than expected. That said, if you permute the labels and calculate the p-value using the welsh t-statistic, then as the sample size grows larger the statistic becomes ancillary to changes in variance. This way you get the best of both worlds, a valid test of H0: f(x)=g(x) for small samples and a valid test for H0:mu_1=mu_2 for large.

Permutation testing


permutation tests of group differences when data contain repeated measures

Question: I have data from several mice with id id. Each mouse either belongs to either group C or group T. I also have a repeated measures factor because each mouse wandered around two mazes (A and B). My dependent variable is score.
dat <- data.frame(id=c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6),
         maze=c("A", "B", "A", "B", "A", "B", "A", "B", "A", "B",
                "A", "B"),
         group=c("C", "C", "T", "T", "C", "C", "T", "T", "C", "C",
                 "T", "T"),
         score=c(10, 21, 13, 9, 12, 16, 3, 18, 3, 19, 22, 20))

   id maze group score
1   1    A     C    10
2   1    B     C    21
3   2    A     T    13
4   2    B     T     9
5   3    A     C    12
6   3    B     C    16
7   4    A     T     3
8   4    B     T    18
9   5    A     C     3
10  5    B     C    19
11  6    A     T    22
12  6    B     T    20

I'm familiar with permutation tests when each row is an independent observation, but if I'm interested in the effect of group, how should the shuffling be done? Can I simply shuffle the group labels randomly in every replicate, even though scores are not truly independent?
EDIT:
For example, I wondered if I should only shuffle the group labels, with the constraint that each id should get the same group label:
   id maze group score
1   1    A     T    10
2   1    B     T    21
3   2    A     C    13
4   2    B     C     9
5   3    A     C    12
6   3    B     C    16
7   4    A     C     3
8   4    B     C    18
9   5    A     T     3
10  5    B     T    19
11  6    A     C    22
12  6    B     C    20

randomly shuffling the group labels would break the correlation structure. For example, with the random shuffling of group labels below, id 1 now belongs to both groups, even though it was originally in group T only. Would this be valid?
   id maze group score
1   1    A     T    10
2   1    B     C    21
3   2    A     C    13
4   2    B     C     9
5   3    A     T    12
6   3    B     C    16
7   4    A     T     3
8   4    B     C    18
9   5    A     T     3
10  5    B     T    19
11  6    A     T    22
12  6    B     C    20

Comment: The answer depends on your null hypothesis.  What is it?
Comment: @whuber, that there is no difference in `scores` between mice in group `C` and group `T`. If there were no repeated measures (`maze`) this would be straightforward, but I'm not sure how to do the shuffling once observations are not independent anymore.
Comment: Your null hypothesis tells you how to do the shuffling: assuming no difference in scores, the assignment of "C" or "T" to each subject would not matter and therefore can be randomized.  Presumably it was randomized as part of your experimental design, anyway.
Comment: @whuber, thanks for the comment. Yes, I understand that the `C` and `T` labels should be shuffled, the question is rather how to deal with the fact that randomly shuffling group labels will likely make some ids belonging to both groups, since the data have repeated measures (`maze`).
I edited my question which I hope clarifies my problem.
Comment: I don't follow: when you shuffle the mice, of course you keep the measurements of each mouse attached to it.  You cannot justify shuffling the measurements among mice because you expect the measurements for any given mouse not to be independent.  (They will only be *conditionally* independent, if that.)  All your model and null hypothesis allow you to change are the *assignments* of mice to control and treatment groups.
Answer: Each mouse belongs to one group. Having it run through one or many mazes has no influence on your null ("that there is no difference in scores between mice in group C and group T") so we keep that structure in place and do not permute that.
The procedure is very similar to that in your previous question here: Permutations with repeated measures
Pivot the data to a wide format where each mouse has one row with one column defining the group. Then permute the one row (which group each mouse belongs to). Everything else needs no manipulation.
We know that some mouse got 10 points in maze A and 21 in maze B and we only need to permute, if that mouse was group 'C' or 'T' if that is what we want to investigate.
Comment: Yes, that's what I thought, I was just making sure I got it right. Thanks again for your answer.


How do I get robocopy to use a log file which includes spaces?

Question: I'm trying the following command:
robocopy "x:\dir" "y:\dir" /mir /z /tee /fft /nfl /ndl /eta /log:"x:\path to logs\12-15-11 01 file with spaces.txt"

I'm getting this error:
ERROR : Invalid Parameter #10 : "/log:x:\path to logs\12-15-11 01 file with spaces.txt"

EDIT #1
Turns out that the above command was valid, I had a typo in my path. If you have a path which includes spaces you can provide them to robocopy's /log switch like so: /log:"c:\path to a file\robocopy.log"
Comment: Works for me. Does it perhaps show a more detailed error at the top?
Comment: Are you running that command in the context of a script instead of directly at the command line.  Perhaps something else is adding some kind of escaping?
Comment: The error message suggests that the initial quote marks are before rather than after the colon; are you sure the command you were trying to run is as shown?
Comment: I so sorry, I had a typo in the path. Majorily embarrassed. Thanks for everyone's prompt help! What's the procedure, should I delete this question? Or can I rephrase it and add an answer showing that you can put quotes around the argument to /log switch of robocopy?
Comment: No reason to delete @slm. If one of the above comments helped you find the problem, ask them to post it as an answer, and then mark the answer correct. If the issue was something else entirely, write your own answer and mark it as the answer so future searchers will know to check that if they have a similar problem.
Answer: If you need to provide a path that includes spaces to robocopy's /log switch you can do it like this:
/log:"c:\path to logs files\some log file.txt"

Comment: I get Invalid Error:  parameter #11 "/log". I added it on to the end of an otherwise working command.
Comment: I no longer work where I support windows so have no way to test this.
Comment: Make sure the log file's parent directory exists. Robocopy won't created it, and, sadly, complains about the cmdline parameter if the dir doesn't exist.
Comment: I can't get this to work.   Any time a variable contains a space Robocopy breaks down.   I have tried '"D:\this not working\filename.txt"', '"""D:\this not working\filename.txt"""', 'D:\this not working\filename.txt'  Tried adding quotes around the variable in robocopy "$Src" "$Dest" /LOG:"$LogPath"   Nothing works.  What am I doing wrong?
Comment: Dummy me.   I used robocopy D:\Source Folder\ F:\Destination Folder\.    Needed to be D:\Source Folder\ F:\Destination Folder.  Watch that source-destination backslash.
Answer: There are four way of logging as the Powershell documentation
/log:<LogFile> : Writes the status output to the log file (overwrites the existing log file).

e.g: robocopy "c:\a" "c:\b" /log:"c:\copy_log.log"

/log+:<LogFile> : Writes the status output to the log file (appends the output to the existing log file).

e.g: robocopy "c:\a" "c:\b" /log+:"c:\copy_log.log"

/unilog:<LogFile> : Writes the status output to the log file as Unicode text (overwrites the existing log file).

e.g: robocopy "c:\a" "c:\b" /unilog:"c:\copy_log.log"

/unilog+:<LogFile> : Writes the status output to the log file as Unicode text (appends the output to the existing log file).

e.g: robocopy "c:\a" "c:\b" /unilog+:"c:\copy_log.log"

For more details https://technet.microsoft.com/en-us/library/cc733145(v=ws.11).aspx
Comment: I'll also recommend to add `/tee` switch as that also products command line output and lets user to see the progress of the copying of files in command line also.
Answer: It happens when need admin privileges/ or pop to create file into that directory
So try to have a log/temp directory and try to add log file into that log directory
$ mkdir C:\log

e.g:
$ robocopy "c:\a" "c:\b" /log:"c:\log\copy_log.log"

Answer: If the path to the log file contains spaces or some other scripting delimiters, please include it in quotes such as your EDIT #1 and @slm suggests. But also, please note the use of escape characters as described in this documentation on Batch scripting.
Comment: I'm having the same issue after a fairly disastrous and unwanted Win 10 migration.


Close connection when using a Transaction

Question: I have the following method which uses a transaction.
private string getDocumentDetailsByNumber(string DocNumber)
    {
       SqlTransaction transaction = DALDBConnection.SqlConnection.BeginTransaction();

            try
            {
                DataSet DocNum = new DataSet();

                string sDocNumber = "";
                string[] taleNamesDoc = new string[1];
                taleNamesDoc[0] = "docnumber";
                SqlParameter[] paramDoc = new SqlParameter[1];
                paramDoc[0] = new SqlParameter("@DocumentNumber", DocNumber.ToString().Trim());

                SqlHelper.FillDataset(transaction, CommandType.StoredProcedure, "spGetDocumentDetailsByNumber", DocNum, taleNamesDoc, paramDoc);
                string docTitle = DocNum.Tables["docnumber"].Rows[0][0].ToString();

                transaction.Commit();

                return docTitle;
            }
            catch (Exception ex)
            {

                transaction.Rollback();
                throw ex;
            }

    }

after running the method several times, user ended up getting the error message below.

the timeout period elapsed prior to obtaining a connection from the
  pool

Error occurred because I haven't closed the connection and the connection pool has over flown.
I tried to close the connection before committing the transaction.
transaction.Connection.Close();
transaction.Commit();

Then got the following error.

This SqlTransaction has completed; it is no longer usable

How can I close the connection to avoid the error?
Comment: you can use using (SqlTransaction tran = new SqlTransaction())
            {
//You code
            }
Answer: You cannot exhaust your pool by using a single connection. You need to close all connections you are using. Preferably after the transaction has ended one way or another. using blocks are your friend for almost all database related objects.
By the way:
throw ex;

This damages your exception by replacing the original stacktrace. Use:
throw;

to rethrow the exception you caught unchanged.
Comment: No, it does not. The connection itself should be in a using block.
Comment: So if I use using (SqlTransaction transaction = DALDBConnection.SqlConnection.BeginTransaction())
        { // my code } does it close the connection? and does it still close the connection after the return statement?
Answer: As mentioned, you should dispose of the connection properly. I've modified your code to demonstrate. Please note you will need to substitute the connection string with yours.
private string getDocumentDetailsByNumber(string DocNumber)
{
    using (var connection = new SqlConnection("My Connection String"))
    {
        SqlTransaction transaction = connection.BeginTransaction();

        DataSet DocNum = new DataSet();

        string sDocNumber = "";
        string[] taleNamesDoc = new string[1];
        taleNamesDoc[0] = "docnumber";
        SqlParameter[] paramDoc = new SqlParameter[1];
        paramDoc[0] = new SqlParameter("@DocumentNumber", DocNumber.ToString().Trim());

        SqlHelper.FillDataset(transaction, CommandType.StoredProcedure, "spGetDocumentDetailsByNumber", DocNum, taleNamesDoc, paramDoc);
        string docTitle = DocNum.Tables["docnumber"].Rows[0][0].ToString();

        transaction.Commit();

        return docTitle;
    }  // Connection is disposed and cleaned up.
}

Opening new connections are cheap and should not be frowned upon. Each one you call the database you should open a new one like this. By maintaining a connection and not disposing of it, you are taking resources away from the database as well. It does not have an infinite amount of connections in its pool that can be used at once.
edit
Removed try/catch as mentioned in comments. If an exception is thrown while in the using block, a rollback will occur and the exception passed up the stack.
Comment: No, the transaction is disposed by the using block, resulting in a rollback. The exception is passed on normally and can be caught at a higher level. That's the point of using blocks: they *will* dispose the object, no matter how they are left.
Comment: Putting the Transaction in a using block, too, would get rid of the whole exception handling.
Comment: Hmm, I guess I've never encountered an exception in a using block. Is an exception swallowed when thrown in a block?
Comment: Thanks for clarifying. I didn't realize it would automatically handle a rollback upon an exception being thrown. That's a nice piece of info to know.
Comment: SqlTransaction transaction = connection.BeginTransaction(); throws Invalid operation. The connection is closed.
Comment: I have code very similar to this. However, when I query the database, I find that - even though I committed the transaction in code - the transaction on the database is still open, locking tables. The session is sleeping, but the transaction is open, and I can't figure out how to close the damn thing.
Answer: Have you considered CALLNIG CLOSE ON IT? Would be obvious to close a connection or?
Anything that implements IDIsposable should be disposed, btw., not just closed. And SqlConnection implements IDisposable. THis has nothing to do with SqlTransaction - you violae a fundamental rule of the .NET world by not disposing a disposable routine.


I can't judge the screen size in real time when SSG with next.js

Question: I'm using next.js to create a static page that outputs in SSG mode.
I would like to use the react-device-detect library to determine the output component based on the screen size.
Since the page is created as SSG, even if the screen size is changed after accessing the page, the components will not be changed in real time.
Of course, if you change the screen size and reload it, it will be reflected, but I want to reflect it in real time.
If next.js is not used and only react is used, it will be rendered each time, so there was no problem. Is there a solution to this point?
Best regard.
The source is below.
import { isMobile, BrowserView, MobileView } from "react-device-detect";

const Header = ({ pathname }) => (

    {isMobile ? "mobile header" : "header"}
    <BrowserView>normal</BrowserView>
    <MobileView>mobile</MobileView>

);

export default Header;

Comment: Thank you for the reference link.
With this as a reference, I will approach it in a different way.
Comment: `react-device-detect` doesn't detect the screen size, it detects the device type based on the User-Agent. If you want to react to screen size changes look into solutions like these [Get viewport/window height in ReactJS](https://stackoverflow.com/questions/36862334/get-viewport-window-height-in-reactjs).
Answer: Nextjs is Server Side rendered Framework, by default it will render component in server side and paint the html directly on client side.
As per your use-case, you need to do client side rendering for header component, or any module which works in client/browsers.
import dynamic from 'next/dynamic'

const headerWithNoSSR = dynamic(
  () => import('../components/Header'),
  { ssr: false }
)

function Home() {
  return (

      <headerWithNoSSR />

  )
}

export default Home

Try this code whenever you are using header component, and then this
will work. More you can read here
Comment: you will not get screen size in nextjs as it is server side rendered pages, for that you need to import that login in client/browser side, as screen size logic is client/browser specific, so directly importing it will not work
Comment: Thanks for your comment.
I didn't know the NoSSR mode. thank you for teaching me.
I tried it, but the result was the same.
Do you mean to judge the screen size yourself without using this library?
Comment: Thanks for your comment. Certainly there is no screen on the server. I understand.
I will try to find another approach.


What are these notes in an advanced violin piece?

Question: I am rewriting this for two violins but am having a little trouble with the very first measure.  They look like some weird sort of triplet.  How do I enter the notes into a music editor?  I've never seen that kind of syntax!
Comment: They _are_  triplets, it's just the triplet marks are left out. It's not too uncommon as [seen here](http://music.stackexchange.com/questions/41597/how-is-it-that-12-eighth-notes-fit-in-a-measure-labeled-as-common-time). Just mark them as triplets in musescore.
Comment: What is your musical background/training?
Comment: violin lessons.
Answer: Dom has it right. They'd just be written as triplets with only the top or bottom notes present. You could enter them into the music editor the way you'd do any other triplet, with or without the triplet mark.

So, as far as stuff like left hand pizz, (which my computer keeps trying to say is "left hand pizza") it is currently not a possibility in Musescore to specify left hand pizzicato, but you can certainly tell it to perform pizzicato and write left hand in in the notes. (See: https://musescore.org/en/node/12183)
Triplets can be input with the information present here: https://musescore.org/en/node/11186
Which looks like this:

Although, as Tim said, it's possible that you'd want to use 12/8 instead of this method.
Comment: @CarlWitthoft Fair point, I've seen places, particularly in modern music, where left hand pizz is not specified, but I've also seen places where it is, especially when it's because you're alternating between pizz and arco without much of a break, but some naive musician may attempt to do a traditional pizz anyway. Think Fantasia from Boy Paganini, where in most copies, "left hand pizza" is notated by a little cross over the notes.
Comment: and i would enter them as eighth notes?
Comment: ok, entered!  now I have the new image in the question.  how do I make this look like the original?
Comment: @dalearn Not quite... Let me see here... Just a moment, I'll do it myself in Muscore and show you so you can see what I mean.
Comment: I'd swap them over, so the top line consists of the top notes. It could be written in 12/8, or 4/4 with a comment at the top stating a crotchet = 3 quaver triplets.
Comment: also, how do i put in left hand pizz?
Comment: @Tim is probably right. I was perhaps a bit hasty with my answer. As far as stuff like left hand pizz and whatnot, it really varies with the editor you're using. I understand that the OP is using musescore... So let me take a look-see...
Comment: @Tim, please turn that into an answer!  I converted everything to 12/8 and it is MUCH easier!
Comment: I'm not sure you need to write *anything* for LH pizz -- it's pretty obvious to the performer in most cases that the bow hand is unavailable for the pizzicato notes in question.  BTW,  I'm getting hungry for a left-hand pizza!
Answer: Thanks to GeneralNuisance for jogging my memory.  The Dolmetsch chart lists  a "+" sign over the note as indicating Left-hand Pizz.  So two suggestions:
1) place a text "+" where you want it in Musescore,
2) switch to Lilypond :-)
ETA for non-google people: lilypond
Comment: what is lillypond?
Comment: @dalearn see edit
Comment: Musescore 3 has a "+" for "mute" in the category Articulations, so unless you're concerned about how the playback sounds (which I don't think you should as it doesn't quite reflect how it might sound when played by actual human), you could simply use those as the l.h. pizz notation.


Is separability a topological property?

Question: Let $(M,d_M)$ be a separable metric space. That is, there is a countable subset $S\subset M$ whose closure in $M$ is $M$ itself, $\text{cl}_M(S)=M$.
Now suppose there is a homeomorphism $f:M\to N$. Must $N$ be separable?

My thoughts are as follows. Since $S$ is countable, so is $F=f(S)$. Using this, I broke up the problem into four cases, the last two of which I have been unable to complete.
Case 1:
If $S$ is closed in $M$, then $\text{cl}_M(S)=S=M$ and $F=f(S)=f(M)=N$, meaning that $\text{cl}_{N}(F)=N$. Thus $N$ is separable.
Case 2:
If $S$ is clopen (closed and open) in $M$, it is closed in $M$, and $N$ is separable.
Case 3:
If $S$ is open in $M$, $F$ is open in $N$, but this doesn't seem to help.
Case 4:
If $S$ is neither open nor closed in $M$, I have no idea what to do.
There must be a better way to go about this. Could I have some help? Thanks.
Answer: A homeomorphism is a bijection that takes open sets to open sets, closed sets to closed sets, so it follows that it also respects closure, therefore
$$\mathrm{cl}_N(f(S)) \ =\ f(\mathrm{cl}_M(S)) \ =\ f(M) \ =\ N$$
Comment: To show that $\overline{f(S)} = f(\overline S)$, note first that $S\subset\overline S$, so $f(S)\subset f(\overline S)$, which is closed, so $\overline{f(S)}\subset f(\overline S)$. For the converse, let $y\in f(\overline S)$, i.e., $y = f(x)$ with $x\in\overline  S$. Then there is $(x_n)\subset S$ such that $x_n\to x$. By continuity, $f(x_n)\to f(x) = y$, so $y\in\overline{f(S)}$.
Comment: Wow, that was extremely easy. Thank you.

Is separability a topological property?


How to overcome the lack of local variable for emacs lisp closure

Question: I'm now studying Emacs Lisp from the reference manual and Common Lisp from a LISP Book.
from the Common Lisp book
>> (setf power-of-two
     (let ((previous-power-of-two 1))
       #'(lambda ()
           (setf previous-power-of-two
             (* previous-power-of-two 2)))))

>> (funcall power-of-two)
2

>> (funcall power-of-two)
4

>> (funcall power-of-two)
8

The function won't work in Emacs Lisp because of its dynamic binding behavior.
I wonder if it is possible to implement the same function in Emacs Lisp without introducing a global variable ?
Comment: You might save yourself a lot of time by using a Common Lisp with Slime in emacs. SBCL is my favourite.
Comment: @justinhj: Thanks for the tip. However, I'm learning lisp just to get to know emacs better. Unless something is going to change my mind, I think I prefer python over lisp with a really wide margin.
Comment: That makes sense. BTW when using emacs lisp to extend emacs think about how you would do the same in Python. IMHO emacs lisp is an ideal language for extending a text editor, whilst Python, which I also really like, has many different uses.
Comment: Emacs lisp does not really reflect the experience of using lisps targeted at "real programming" like common lisp. Accordingly, it's not a fair comparison with python, which is not really intended to be used as an embedded scripting language as its first use.
Comment: Marcin, I'm sure lisp is a really powerful concept. Unfortunately, even after few months, I personally still not very comfortable with lisp syntax.
Answer: Update:
By now, Emacs 24 has been officially released, and it supports lexical binding without using lexical-let, when the buffer-local variable lexical-binding is non-nil. See also M-: (info "(elisp) using lexical binding") and pokita's answer.

You can use lexical-let from the Common Lisp Extensions (the "CL package"):
elisp> (require 'cl)
cl
elisp> (setf power-of-two
             (lexical-let ((previous-power-of-two 1))
               #'(lambda ()
                   (setf previous-power-of-two
                         (* previous-power-of-two 2)))))
(lambda
  (&rest --cl-rest--)
  (apply
   (lambda
     (G175638)
     (set G175638
          (*
           (symbol-value G175638)
           2)))
   '--previous-power-of-two-- --cl-rest--))

elisp> (funcall power-of-two)
2
elisp> (funcall power-of-two)
4
elisp> (funcall power-of-two)
8

I've also heard about a lexbind branch of GNU Emacs.
Comment: And `M-x ielm` to get the elisp REPL.
Comment: @phil I suppose the hint is for me ? :)
Comment: This is a good read to go deep into lexical scope in emacs lisp http://www.gnu.org/software/emacs/emacs-paper.html#SEC17
Answer: Emacs24 from bzr now supports lexical binding out of the box; it just isn't activated by default since there are many packages which still deliberately or inadvertently depend on dynamical scoping. Your above code should work just fine in Emacs24 in a buffer where the variable 'lexical-binding' is set to 't'.
Comment: Thanks for the info. I'm really curious if painless transition from dynamic-binding to lexical-binding could be possible. But it's great to know that emacs is still evolving. And I'm really looking forward to devote some effort to help when my skill is good enough.
Comment: Dynamic binding is one of the key reasons that Emacs is so easily extensible. It's certainly nice to have the alternative available, but I hope that dynamic binding will always be the standard for most elisp code.
Answer: See this page: http://www.emacswiki.org/emacs/FakeClosures
Answer: another solution using Emacs' unintern symbol:
ELISP> (setf power-of-two
         (let ((p (make-symbol "previous-power-of-two")))
           (set p 1) (list 'lambda '()
           (list 'setf p
             (list '* p 2)))))

ELISP> (funcall power-of-two)
2
ELISP> (funcall power-of-two)
4
ELISP> (funcall power-of-two)
8


Declaração correta no CSS de listagem de menu

Question: Tenho uma listagem de menu e gostaria de saber a forma mais correta de declarar no HTML+CSS.
O HTML está assim:

Home

Empresa

Produtos

Blog

Onde Comprar

Assistência

Contato

Quanto ao CSS, eu gostaria de alguma dica.
Claro, eu poderia colocar uma classe em cada li e deixar do jeito que eu quiser, mas não sei se seria o ideal, gostaria de economizar código.
O CSS está assim:
ul.menu li{
    font-family: "nexa_boldregular";
    font-size: 12pt;
    text-transform: uppercase;
    color: #1d1d1b;
    display: inline;
    margin-right: 35px;
}

Por exemplo, se eu quiser estilizar alguma li em especifico, teria que atribuir uma classe à ela, certo? Como fiz na logo. O ideal no CSS, seria como?
.logo, li.logo, ul.menu>li.logo?
Comment: Editei o [jsfiddle](http://jsfiddle.net/jaderw/7kqs2gc3/) e agora mostra como selecionar apenas o elemento desejado, em situações que usa as mesmas classes, veja...
Comment: Valeu @Jader, ajudou muito!
Comment: Não existe certo ou errado, vai depender do seu estilo de trabalhar ou se vai ter mais algum elemento com a classe `.logo` tem especificar que se refere ao elemento dentro do `.menu` e usar algo como: `.menu .logo`
Comment: Mas, existe uma forma mais estruturada. Para economizar trabalho.
Comment: Neste caso eu sugiro retirar as tags html do seletor, use só quando necessário... veja esse [jsfiddle](http://jsfiddle.net/jaderw/7kqs2gc3/)
Answer: Felipe,
Toda a vez que você trata apenas um elemento, você pode utilizar o ID. Sendo um grupo ao qual será atribuido um elemento em comum, ai você usa Classe
Existe a TAG nav a qual utilizo para geralmente estruturar da seguinte forma:

  <ul

Consecutivamente no CSS, me refiro assim:
nav ul {
}

nav ul li{
}

Ou seja, se você não possuí uma classe, você vai destrinchando os elementos e desenvolvendo a arvore.
Se você declarar um estilo para para nav ul, ele vai procurar uma TAG ul dentro do nav, idem ao nav ul li que poderia ser declarado como nav li por exemplo.
Sobre o .logo, você pode declarar a mesma singularmente porém em linhas sequencias do seu código, para organização, deixar o conteúdo relativo ao menu, totalmente agrupado. Ou seja, criar "setorizações".
Comment: Obrigado. Só uma dúvida, supondo que eu tenha mais de uma listagem de menus no site. Eu teria que criar uma classe nove para diferenciá-las, o ideal seria eu criar, assim por exemplo: `nav ul.menu1` e `nav ul.menu2`, correto?
Comment: Seguindo a sua estrutura, o correto seria você identificar a área a qual seu menu pertence. Por exemplo, um deles poderia ser `menuLateral` enquanto outro seria `menuSuperior`. Ou por exemplo, se caso um menu é principal e relativo a navegação, você poderia ter uma declaração `nav ul` e `nav li`, enquanto outro, `menuSecundario ul` e `menuSecundario li`


What does this downward triangular arrow mean?

Question: What does the prime symbol above the note mean? I have not seen it before.
This is from Haydn's Variations in F minor (Hob. XVII/6)
Answer: It's a form of staccato called staccatissimo.
Normal dot over/under a note means staccato, where the note is shortened by about a quarter of its normal length.
Staccatissimo, is an 'extreme' version, where the note is shortened by about three-quarters of its length. In this piece, those notes are played and let go of immediately, pretty well, the first F actuallly being shorter in duration than the second.
Comment: In addition from [Wikipedia: Accent (music)](https://en.wikipedia.org/wiki/Accent_(music))"... is usually interpreted as shorter than the staccato, but composers up to the time of Mozart used these symbols interchangeably. A staccatissimo crotchet (quarter note) would be correctly played in traditional art music as a lightly articulated semi-quaver (sixteenth note) followed by rests which fill the remainder of the beat." So it has a few meanings.
Answer: To add a caveat to Tim's answer: this marking should generally be taken with a grain of salt — or more like a rather large pinch of salt — in music written prior to the 20th century. Most such markings on scores of older music are putting forth a performance opinion of the editor, rather than anything that the composer specified — and some editors are better performers than others. Composers were inconsistent about what markings they used for staccato, although they usually used a dot and always, as far as I know, left the degree of "staccato-ness" up to the interpreter.
For example, in this one, you can have a look at this performance (your two-bar sample is played at 0:55, and can be seen in the last two measures of the third staff line):

You will notice that your two bars in this edition of the music here have a total of four ordinary staccato dots. That suggests that your wedges are an editor's opinion. Listening to Backhaus's performance, I get the idea he doesn't agree with that opinion, for I don't see any special degree of extremeness about the staccatos that he uses.
So, it's probably a good idea to approach any written score with a certain degree of skepticism. Beyond having the right notes, key and time signatures, and the like, finer degrees of detail should not be assumed to come from the composer. Look at different scores of the same music and form your own opinions.
In fact, I suggest that you consider your performances not as a recreation of a composer's ideas, but as a collaboration between you and the composer. So again, form your own opinions, and don't be too concerned with finding the intellectually correct way to play something. If something feels right, then play it that way.
Comment: @Athanasius Good point. I haven't seen the Henle edition of this, but from what I know of the faithfulness of Henle's attempts to represent the manuscript as accurately as possible, what you say seems very likely with regard to the use of strokes instead of dots here. That said, I remain skeptical of the idea that Haydn used strokes to indicate a greater degree of staccato than dots, or some sort of staccatissimo idea.
Comment: @user1488 Yeah, I recognize the shape of the note heads, now that you mention it. Henle is usually my favorite, partly because of the sharpness and clarity of the notes, and partly because they do their best to remain faithful to the manuscript. So, I'm going to change my position a bit. This isn't an editor deciding that a greater degree of staccato is needed, this is the closest approximation of what Haydn's staccato markings looked like. I still don't think that Haydn used the longer strokes to indicate a greater degree of staccato, since that convention didn't happen for another 200 years.
Comment: Thanks for this answer. I was confused because none of the recordings I listened to play it staccatissimo. Many play it legato
Comment: @user1488 Exactly. You might find it interesting to listen to some recordings from the early 20th century (say 1930s) by the likes of Paderewski, Cortot and Lhevinne. Then compare those with recordings of the same pieces from after 1950. You will notice that the earlier performers are much more willing to take liberties with the score. My point in mentioning this is that performers make those choices for themselves, although there's a sense of what's in current fashion going on as well.
Comment: I'd disagree a bit with this. It's impossible to know without having the edition that was the source in the question, but the use of the bracket in the right hand in the question around the stroke tends to indicate that the question's edition is a more "critical edition" version that's explicitly marking editorial additions to the score. Haydn's markings in manuscript were often more like strokes (in my recollection), and I think these "strokes" frequently appear in critical editions of Haydn. In any case, editions that use brackets often have some indication of sources used.
Comment: It's the Henle urtext edition.
Answer: (PhD in music history here). This isn't my period,  but I think that it's an mark of emphasis.
On a harpsichord (which was my major instrument in college), you can emphasize a note by making it a little short so that the end of the note is salient. This works pretty well on the clavichord and fairly well on early pianos.
So, it's easy to see that slight accent = slight staccato, on the right instrument.
How to play it on the modern piano? The action on a modern piano is mushy compared with the earlier instruments, and the end of the notes isn't so clear. So, the best thing, I think, would be to think of the notes as emphasized. Maybe best to do that with dynamics.
Comment: Yes, I'm not sure, but I can't imagine what else it would be. "Staccatissimo" (very short staccato) doesn't make any sense, and the wedge didn't mean that in Haydn's time, in any event. The wedge, the dot, and little lines were all used to mean the same sort of thing in Haydn's time. The exact sign varied from composer to composer, from publisher to publisher, and even from writing implement to writing implement. The standard sign we know come from the middle of the 19th century.
Comment: You may be aware of some pedal markings in Beethoven's sonatas that don't translate well to modern pianos, where he pedals through long passages, relying on notes dying away before they clash. In particular, the recitative passage introducing the (somewhat mangled) recapitulation in the first movement of the Op. 31 No. 2 ("Tempest") sonata. To get an effect approximating that on a fortepiano, you have to experiment with partially clearing the pedal, for if you don't, you get a mush.
Comment: @BobRobes: Or the first movement of the Moonlight, which is marked "senza sordini" (without dampers), which is just a muddle on modern pianos.
True story: Back in my h'chord days, I once sat at a modern piano, not having touched one for 4 or 5 years, and my immediate gut reaction was "What an inexpressive instrument!" Which is silly, of course, but it wouldn't do what I wanted - I couldn't articulate at all. I got used to it again after a while, of course. But the articulation really is much crisper on the older instruments.
Comment: So, there's a lot of information here, but TL;DR is that you don't know for sure. Do I understand correctly?
Comment: So wouldn't it be best marked as such?
Comment: To Tim: Agree. Depending on the edition, the editor should have either modernized the notation or explained what Haydn's notation meant in a footnote or the introduction or something. I checked the edition I have, though, and there's no explanation there. The editor just calls it a "wedge," which isn't helpful.
Comment: As a pianist who has played a little harpsichord and fortepiano, I don't think I would characterize the action of a (good) modern piano as mushy. In fact, I find it extremely precise in terms of doing what I tell it to do. (Telling it to do what I want it to do, now that's another story!) However, it is certainly possible to make extremely mushy sounds on a modern piano that weren't possible with earlier instruments, primarily due to the length of sustain in the envelope of a note.
Comment: Yes, probably so. On the other hand, a harpsichord, while crisper as you say, lacks the shading and nuancing capabilities of a piano. I've been on a Scarlatti kick for the last couple of years, and the decisions about articulation and phrasing and dynamics that a piano requires go well beyond the capabilities of the harpsichord. it often occurs to me that Scarlatti, if he is around somewhere listening to piano performances of his sonatas as I believe he is, is completely fascinated by the expanded palette that a piano affords and the decisions that performers make when applying that palette.