google activity recognition api not working

Question: I am using Google play services for activity recognition to detect various activities like: Still, On Foot etc. But the code works fine on Moto g devices and fails on HTC one. Can you please verify if my approach is correct? Here are the codes:
My Activity:
public class MyActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private PendingIntent pIntent;
    GoogleApiClient mGoogleApiClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(ActivityRecognition.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
        mGoogleApiClient.connect();
        IntentFilter filter = new IntentFilter();
        filter.addAction("ACTIVITY_RECOGNITION");//For filtering
    }

    @Override

    public void onConnected(Bundle arg0) {
        Intent intent = new Intent(this, ActivityRecognitionService.class);
        pIntent = PendingIntent.getService(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
        ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, 0, pIntent);//0
    }
    /*@Override
    public void onDisconnected() {
    }*/
    //@Override
    public void onConnectionSuspended(int arg0) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // TODO Auto-generated method stub
    }

where as ActivityRecognitionService looks like:
public class ActivityRecognitionService extends IntentService {
public ActivityRecognitionService() {
        super("My Activity Recognition Service");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if(ActivityRecognitionResult.hasResult(intent)){
            ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
            Log.i(TAG, getType(result.getMostProbableActivity().getType()) + "t" + result.getMostProbableActivity().getConfidence());
            /*Intent i = new Intent("ACTIVITY_RECOGNITION");
            i.putExtra("Activity", getType(result.getMostProbableActivity().getType()) );
            i.putExtra("Confidence", result.getMostProbableActivity().getConfidence());
            sendBroadcast(i);*/
            String aType = getType(result.getMostProbableActivity().getType());
            int aConf = result.getMostProbableActivity().getConfidence();
            fileWrite(aType, aConf);
        }
    }

    private String getType(int type){
        if(type == DetectedActivity.UNKNOWN)
            return "Unknown";
        else if(type == DetectedActivity.IN_VEHICLE)
            return "In Vehicle";
}

On HTC i am getting following message in logcat: (Although i got similar messages on moto g, but it still detects the activity)
09-28 19:09:11.143: W/asset(7697): Copying FileAsset 0x727dbe28 (zip:/data/app/com.example.activityRec-2.apk:/resources.arsc) to buffer size 254736 to make it aligned.
09-28 19:09:11.173: W/dalvikvm(7697): VFY: unable to find class referenced in signature (Landroid/support/v4/app/FragmentActivity;)
09-28 19:09:11.173: W/dalvikvm(7697): Unable to resolve superclass of Lcom/google/android/gms/internal/zzlp; (184)
09-28 19:09:11.173: W/dalvikvm(7697): Link of class 'Lcom/google/android/gms/internal/zzlp;' failed
09-28 19:09:11.173: W/dalvikvm(7697): VFY: unable to find class referenced in signature (Lcom/google/android/gms/internal/zzlp;)
09-28 19:09:11.173: W/dalvikvm(7697): Unable to resolve superclass of Lcom/google/android/gms/internal/zzlp; (184)
09-28 19:09:11.173: W/dalvikvm(7697): Link of class 'Lcom/google/android/gms/internal/zzlp;' failed
09-28 19:09:11.173: W/dalvikvm(7697): VFY: unable to find class referenced in signature (Lcom/google/android/gms/internal/zzlp;)
09-28 19:09:11.173: W/dalvikvm(7697): Unable to resolve superclass of Lcom/google/android/gms/internal/zzlp; (184)
09-28 19:09:11.173: W/dalvikvm(7697): Link of class 'Lcom/google/android/gms/internal/zzlp;' failed
09-28 19:09:11.173: W/dalvikvm(7697): VFY: unable to find class referenced in signature (Lcom/google/android/gms/internal/zzlp;)
09-28 19:09:11.173: W/dalvikvm(7697): Unable to resolve superclass of Lcom/google/android/gms/internal/zzlp; (184)
09-28 19:09:11.173: W/dalvikvm(7697): Link of class 'Lcom/google/android/gms/internal/zzlp;' failed
09-28 19:09:11.173: W/dalvikvm(7697): VFY: unable to resolve virtual method 21831: Lcom/google/android/gms/internal/zzlp;.zza (ILcom/google/android/gms/common/api/GoogleApiClient;Lcom/google/android/gms/common/api/GoogleApiClient$OnConnectionFailedListener;)V
09-28 19:09:11.173: W/dalvikvm(7697): Unable to resolve superclass of Lcom/google/android/gms/internal/zzlp; (184)
09-28 19:09:11.173: W/dalvikvm(7697): Link of class 'Lcom/google/android/gms/internal/zzlp;' failed
09-28 19:09:11.173: W/dalvikvm(7697): VFY: unable to resolve static method 21829: Lcom/google/android/gms/internal/zzlp;.zza (Landroid/support/v4/app/FragmentActivity;)Lcom/google/android/gms/internal/zzlp;
09-28 19:09:11.173: W/dalvikvm(7697): VFY: unable to find class referenced in signature (Landroid/support/v4/app/FragmentActivity;)
09-28 19:09:11.173: E/dalvikvm(7697): Could not find class 'android.support.v4.app.FragmentActivity', referenced from method com.google.android.gms.common.api.GoogleApiClient$Builder.enableAutoManage
09-28 19:09:11.173: W/dalvikvm(7697): VFY: unable to resolve check-cast 185 (Landroid/support/v4/app/FragmentActivity;) in Lcom/google/android/gms/common/api/GoogleApiClient$Builder;
09-28 19:09:11.173: W/dalvikvm(7697): VFY: unable to find class referenced in signature (Landroid/support/v4/app/FragmentActivity;)
09-28 19:09:11.173: W/dalvikvm(7697): VFY: unable to find class referenced in signature (Landroid/support/v4/app/FragmentActivity;)
09-28 19:09:11.173: W/dalvikvm(7697): VFY: unable to find class referenced in signature (Landroid/support/v4/app/Fragment;)
09-28 19:09:11.183: W/dalvikvm(7697): VFY: unable to find class referenced in signature (Landroid/support/v4/app/Fragment;)
09-28 19:09:11.183: W/dalvikvm(7697): VFY: unable to find class referenced in signature (Landroid/support/v4/app/Fragment;)
09-28 19:09:11.183: W/dalvikvm(7697): VFY: unable to find class referenced in signature (Landroid/support/v4/app/Fragment;)
09-28 19:09:11.183: W/dalvikvm(7697): VFY: unable to find class referenced in signature (Landroid/support/v4/app/Fragment;)
09-28 19:09:11.183: W/dalvikvm(7697): VFY: unable to find class referenced in signature (Landroid/support/v4/app/Fragment;)
09-28 19:09:11.183: W/dalvikvm(7697): VFY: unable to resolve virtual method 134: Landroid/app/Notification$Builder;.setLocalOnly (Z)Landroid/app/Notification$Builder;
09-28 19:09:11.183: E/dalvikvm(7697): Could not find class 'android.support.v4.app.NotificationCompat$Builder', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zza
09-28 19:09:11.183: W/dalvikvm(7697): VFY: unable to resolve new-instance 188 (Landroid/support/v4/app/NotificationCompat$Builder;) in Lcom/google/android/gms/common/GooglePlayServicesUtil;
09-28 19:09:11.183: E/dalvikvm(7697): Could not find class 'android.support.v4.app.FragmentActivity', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zza
09-28 19:09:11.183: W/dalvikvm(7697): VFY: unable to resolve instanceof 185 (Landroid/support/v4/app/FragmentActivity;) in Lcom/google/android/gms/common/GooglePlayServicesUtil;
09-28 19:09:11.183: E/dalvikvm(7697): Could not find class 'android.support.v4.app.FragmentActivity', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zza
09-28 19:09:11.183: W/dalvikvm(7697): VFY: unable to resolve check-cast 185 (Landroid/support/v4/app/FragmentActivity;) in Lcom/google/android/gms/common/GooglePlayServicesUtil;
09-28 19:09:11.183: W/dalvikvm(7697): VFY: unable to resolve virtual method 293: Landroid/content/pm/PackageManager;.getPackageInstaller ()Landroid/content/pm/PackageInstaller;
09-28 19:09:11.193: W/dalvikvm(7697): VFY: unable to find class referenced in signature (Landroid/support/v4/app/FragmentActivity;)
09-28 19:09:11.193: W/dalvikvm(7697): Unable to resolve superclass of Lcom/google/android/gms/internal/zzlp; (184)
09-28 19:09:11.193: W/dalvikvm(7697): Link of class 'Lcom/google/android/gms/internal/zzlp;' failed
09-28 19:09:11.193: W/dalvikvm(7697): VFY: unable to resolve static method 21829: Lcom/google/android/gms/internal/zzlp;.zza (Landroid/support/v4/app/FragmentActivity;)Lcom/google/android/gms/internal/zzlp;
09-28 19:09:11.193: W/GooglePlayServicesUtil(7697): Google Play services out of date.  Requires 8115000 but found 4324038
09-28 19:09:11.233: I/Adreno-EGL(7697): <qeglDrvAPI_eglInitialize:385>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.066_msm8974_refs/tags/AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.066__release_AU ()
09-28 19:09:11.233: I/Adreno-EGL(7697): OpenGL ES Shader Compiler Version: E031.24.00.06
09-28 19:09:11.233: I/Adreno-EGL(7697): Build Date: 02/06/14 Thu
09-28 19:09:11.233: I/Adreno-EGL(7697): Local Branch:
09-28 19:09:11.233: I/Adreno-EGL(7697): Remote Branch: refs/tags/AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.066
09-28 19:09:11.233: I/Adreno-EGL(7697): Local Patches: NONE
09-28 19:09:11.233: I/Adreno-EGL(7697): Reconstruct Branch: NOTHING
09-28 19:09:49.563: W/GooglePlayServicesUtil(7697): Google Play services out of date.  Requires 8115000 but found 4324038
09-28 19:11:22.253: W/GooglePlayServicesUtil(7697): Google Play services out of date.  Requires 8115000 but found 4324038
09-28 19:11:23.373: W/GooglePlayServicesUtil(7697): Google Play services out of date.  Requires 8115000 but found 4324038

Update

update2
error log
09-29 11:52:13.790: W/asset(10716): Copying FileAsset 0x77fe6e98 (zip:/data/app/com.example.activityRec-1.apk:/resources.arsc) to buffer size 254736 to make it aligned.
09-29 11:52:13.820: W/dalvikvm(10716): VFY: unable to resolve virtual method 236: Landroid/app/Notification$Builder;.setLocalOnly (Z)Landroid/app/Notification$Builder;
09-29 11:52:13.830: W/dalvikvm(10716): VFY: unable to resolve virtual method 527: Landroid/content/pm/PackageManager;.getPackageInstaller ()Landroid/content/pm/PackageInstaller;
09-29 11:52:13.830: D/At least(10716): it creats
09-29 11:52:13.840: W/GooglePlayServicesUtil(10716): Google Play services out of date.  Requires 8115000 but found 4324038
09-29 11:52:13.880: I/Adreno-EGL(10716): <qeglDrvAPI_eglInitialize:385>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.066_msm8974_refs/tags/AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.066__release_AU ()
09-29 11:52:13.880: I/Adreno-EGL(10716): OpenGL ES Shader Compiler Version: E031.24.00.06
09-29 11:52:13.880: I/Adreno-EGL(10716): Build Date: 02/06/14 Thu
09-29 11:52:13.880: I/Adreno-EGL(10716): Local Branch:
09-29 11:52:13.880: I/Adreno-EGL(10716): Remote Branch: refs/tags/AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.066
09-29 11:52:13.880: I/Adreno-EGL(10716): Local Patches: NONE
09-29 11:52:13.880: I/Adreno-EGL(10716): Reconstruct Branch: NOTHING

SDK image
Comment: eclipse or android studio?
Answer: The error is because you have missed this part of the support library setup guide

In the Order and Export tab, check the .jar files you just added to the build path, so they are available to projects that depend on this library project. For example, the appcompat project requires you to export both the android-support-v4.jar and android-support-v7-appcompat.jar files.

The app runs fine on lollipop because it has the classes needed for card views but the older devices don't hence the need for the support lib.
Comment: please see my update, is this the correct jar?, still the only error i get is similar to: Google Play services out of date. Requires 8115000 but found 4324038, which i always get for other phones too.
Comment: Have the first set of errors gone away? Please open the sdk manager from eclipse or using the android app and update the google play services library. YOu might find that the support library etc also might need to be updated. Sometimes you need to close and reopen eclipse and do a project clean and build for the changes to take effect
Comment: yup i did updated already, can you see any bug in my code. Also, quick question for app that is supposed to run on all various version/makes of Android, what should be the target API? I am hoping to get all users ranging from Moto g to S4 (all android versions too), any suggestions on both will be  very helpful


How to add a custom variable that can be accessed on bootstrap's menu--account.html.twig?

Question: I have a custom theme (subtheme of drupal bootstrap theme).  We are overriding menu--account.html.twig.  So I copied menu--account.html.twig from the bootstrap theme template folder into my theme's template folder, and I verified this template is being used because static text changes I added show up on screen.
Now I'm trying to add a variable that the menu--account.html.twig template can read.
How do I do that?  My variable's name is 'nickname'.  I tried this:
 function mymodule_preprocess_menu__account(&$variables)
 {
     $variables['nickname'] = 'Jeff';
 }

The variable is added to the array, and I can see it if I use dpm, but when I reference {{nickname}} in the template it's always null.
I also read I had to define the variable like this:
 function candidate_poral_theme_registry_alter(&$theme_registry)
 {
   $theme_registry['menu__account']['variables']['nickname'] = 'default';
 }

But that also doesn't work.
Any assistance would be welcome.
Comment: Have to ask, but is your theme registry alter hook spelled correctly? I noticed it says poral instead of portal. Can you verify the code is being hit on cache clear?
Comment: Well, you're right about the misspelling, but fixing it didn't have any effect other than allowing me to confirm (by dumpign $theme_registry via dsm) that the registry alter hook is being called on a cache clear.
Answer: I have done this for a theme on past projects. Be sure to pass it in through the content item:
Example
use Drupal\Core\Render\Markup;

function mytheme_theme_registry_alter(&$theme_registry) {
  $theme_registry['menu__account']['variables']['nickname'] = 'default';
}

function mytheme_preprocess_menu__account(&$variables) {
  // code...

  $variables['content']['#nickname'] = [
    .. renderable properties
  ];

  // or also...

  $variables['content']['#nickname'] = Markup::create('Jeff');
}

Then, in the twig template:
{{ custom_var }}


Connecting guitar to Amplitube

Question: I have a problem with my ASUS r553l. There's only one jack input for mic/headphones. I tried to plug my guitar via a jack adapter to it but it seems to not be recognized by the computer. I have Realtek HD Audio manager installed but Amplitube can't find my audio device. What should I do ?
Comment: You can get an adaptor to split out the combined jack to separate mic and headphones. Alternatively, get a USB adaptor with a guitar-specific input.
Comment: Seconding a usb audio interface. You don't need anything special unless you want to spend the money. You can find a cheap interface for under $50 USD. stay away from M Audio gear. There is ALWAYS a better alternative for the same price. http://www.music-group.com/Categories/Behringer/Computer-Audio/Audio-Interfaces/UCG102/p/P0198
Comment: For another datum point - I really really like the M-Audio sound interfaces I have used. Very low latency, superb quality - better than a lot of the competition at that price. So shop around.
Answer: Amp modeling software really don't work on laptops. I've had numerous experiences with laptops mixing the jack input with the microphone input causing unwanted distortion and really high latency. The only way I got it to work properly was by using a jack to USB cable as suggested by the comment. You should consider the rocksmith cable. I use it on guitar rig 5 regularly and gives a much better sound quality than a normal jack with an adapter. Or alternatively buy a USB soundcard that has a jack. Check out the m-audio fastrack sound card or anything that's similar
Comment: A RockSmith is not a "jack to USB cable". It is an active electronic device called a **digital audio interface**, or more properly and **analog-to-digital converter**. Good digital audio interfaces cost a good deal of money. There is no "cable" solution for connecting a guitar to a cheap laptop computer.

Connecting guitar to Amplitube


Logistic regression vs Random forest vs GBM: equal performance?

Question: I'm trying to convince my boss that we should consider using machine learning in our field (oncology). We study brain tumours, roughly 90% die within a few years. I wanted to compare the performance of logistic regression, random forest and GBM for classification. My results show that there is no noteworthy difference in their performance. I do recognize that there are inherent flaws to such comparisons; e.g the logistic model could be improved with some interactions and splines (which are better taken care of out of the box by tree-based models).
I would expect to see a difference between these models. What am I doing wrong?
Reproducible example
# Load data
file <- read.csv("https://www.dropbox.com/s/kcy5nm01996famo/data.csv?dl=1", header=T, sep=",")
file$outcome <- as.factor(file$outcome)

# Create trainin and test data
smp_size <- floor(0.70 * nrow(file))
set.seed(1)
train_ind <- sample(seq_len(nrow(file)), size = smp_size)
train     <- file[train_ind, ]
test      <- file[-train_ind, ]

# LOGISTIC REGRESSION
glm.model <- glm(outcome=="1" ~ ., family="binomial", data=train); summary(logmod)
glm.prediction <- predict(object=glm.model, newdata=test, type="response")

# RANDOM FOREST
# 5000 trees should be sufficient. I tried more without noting any material difference.
rf.model <- randomForest(outcome=="1" ~ ., ntree=5000, na.action=na.fail, importance=T, keep.forest=T, data=train)
rf.prediction  <- data.frame(predict(object=rf.model, newdata=test, type="prob"))[,2]

# GBM - testing many trees and using cross validation to find optimal number of trees
gbm.test <- gbm(outcome=="1" ~ ., distribution = "bernoulli", n.trees=20000, cv.folds=5, shrinkage=0.01, verbose=F, data=train)
best.iterations <- gbm.perf(gbm.test) # optimal nr of trees = 2981

# New GBM with optimal nr trees
gbm.model <- gbm(outcome=="1" ~ ., distribution = "bernoulli", n.trees=2981, shrinkage=0.01, verbose=F, data=train)
gbm.prediction <- predict(object=gbm.model, newdata=test, type="response", n.trees=best.iterations)

# Set cut-off to 90% probability to classify as "will die"
# I understand that i could use tree votes (for RF, gbm) but I use probability for all models instead
test$glm.class <- ifelse(glm.prediction>0.9, 1, 0)
test$rf.class <- ifelse(rf.prediction>0.9, 1, 0)
test$gbm.class <- ifelse(gbm.prediction>0.9, 1, 0)

library(pROC) #install.packages("pROC)

roc1 <- roc(response=test$outcome, predictor=test$glm.class, percent=T, auc=T, plot=T)
roc2 <- roc(response=test$outcome, predictor=test$rf.class, percent=T, auc=T, plot=T)
roc3 <- roc(response=test$outcome, predictor=test$gbm.class, percent=T, auc=T, plot=T)

auc(roc1)
auc(roc2)
auc(roc3)

library(caret)
sens.glm <- sensitivity(factor(test$glm.class), factor(test$outcome))
spec.glm <- specificity(factor(test$glm.class), factor(test$outcome))

sens.rf <- sensitivity(factor(test$rf.class), factor(test$outcome))
spec.rf <- specificity(factor(test$rf.class), factor(test$outcome))

sens.gbm <- sensitivity(factor(test$gbm.class), factor(test$outcome))
spec.gbm <- specificity(factor(test$gbm.class), factor(test$outcome))

Comment: Check out SuperLearner, which is a way of maximizing the performance across several machine learning algorithms. A good introductory article that was written for social scientists is Baćak & Kennedy (2018).
Answer: For the ROC and AUC, you should use the probability predictions:
roc1 <- roc(response=test$outcome, predictor=glm.prediction, percent=T, auc=T, plot=T)
roc2 <- roc(response=test$outcome, predictor=rf.prediction, percent=T, auc=T, plot=T)

auc(roc1)
auc(roc2)

Also make sure that you train a random forest for classification
rf.model <- randomForest(outcome ~ ., ntree=500, na.action=na.fail, importance=F, keep.forest=T, data=train)
rf.prediction  <- data.frame(predict(object=rf.model, newdata=test, type="prob"))[,2]

The performance is quite similar, (AUC: 90.9 vs 90.78). Depending on the data RF sometimes cannot get much better performance than logistic regression. See here for an interesting comparison: https://epub.ub.uni-muenchen.de/39955/1/TR.pdf
Comment: Many thanks. Will read the paper (seems very good) and follow the advice and get back to you.


How to make network calls when flutter app changes from offline to online?

Question: I am working on an flutter app that stores data in the database in the form of objects when it is offline.
When the user is back online the app must make all the post requests .Is it possible to find out when the user is back online and can i do it even if the user is on another app or locked out .
Answer: You can use the package connectivity
And create a stream to listen to connectivity changes.
Define a stream :
StreamSubscription<ConnectivityResult> networkSubscription;

In the initState() method add :
networkSubscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
    // This will be called every time a connectivity change happens
    try {
        final result = await InternetAddress.lookup('google.com');
        if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
            print('Connected to internet');
            // Connectivity changed from disconnected to connected
        }
    } on SocketException catch (_) {
        print('Not connected to internet');
        // Connectivity changed from connected to disconnected
    }
});

Don't forgot to dispose the stream :
@override
void dispose() {
    networkSubscription.cancel();
    super.dispose();
}

I don't know how to do this when the app is closed or on background.


Predictable process is adapted?

Question: If I start with the definition of a predictable process as a measurable mappings on the predictable $\sigma$-algebra generated by sets like
$$
(s,t]\times F, \quad s<t, \quad F \in \mathcal{F}_s
$$
and
$$
\{0\}\times F,\quad F \in \mathcal{F}_0,
$$
is it obvious why such a process, $X(t,\omega)$, would be adapted to the above filtration?  Form my reading, I am told that this is the case, but I don't quite see it.
Answer: Yes. Set $ t\ge 0 $, note that
$$ X\colon [0,\infty)\times \Omega \to \mathbb{R} $$
is predictable, $$(t,\cdot)\colon \Omega \to [0,\infty)\times \Omega$$ is $\mathcal{F}_t$ measurable and $$X_t=X \circ (t,\cdot).$$
In fact, $${(t,\cdot)}^{-1}\left( (u,v]\times F \right) = F
$$
when $t>u$ (with $F\in \mathcal{F}_u\subset \mathcal{F}_t$) and
$$ {(t,\cdot)}^{-1}\left( (u,v]\times F \right)=\emptyset$$
when $t\le u$.
Comment: I assume you mean $\mathcal{F}_t$ measurable (not medible)

Predictable process is adapted?


Filtering array with value from Observable/subscribe?

Question: I use ngx-translate to translate keyword through my app, including a list of tags. User should be able to search through them in any language.
Previously I was doing
this.tag_array_filtered = this.tag_array.filter(tag =>
   tag.toUpperCase().includes(this.tag_searched.toUpperCase()));
)

but it only search the key word, not through translations.
this is how I get a translation from a key
this.translate.get(tag).subscribe(value => {
   console.log(value);
})

the variable tag_arrayis an array of key, ready to be translated. tag_searched contain the user input. tag_array_filtered is the array of key (not translated) to be displayed
What I want to do: (not working obviously)
 this.tag_array_filtered = this.tag_array.filter(tag =>
    this.translate.get(tag.toUpperCase()).subscribe((value: string) => {
      value.includes(this.tag_searched.toUpperCase())
  })
 )

How can I filter my array while transforming the value with a subscribe ? I want to compare each value translated from the array to the user input.
I could do it with hand-made loops I guess but if there is a solution already existing it would probably be much faster.
Answer: The translate.get() method also accepts an array of strings.
You could try like this. The final output will be an object which you could transform it into an array if needed.

let tag_array_filtered = this.tag_array.filter(tag =>
 tag.toUpperCase()
    .includes(this.tag_searched.toUpperCase())
    .map(e => e.toUpperCase())
this.translate.get(matching_tags).subscribe((values: {}) => {
  this.tag_array_filtered_object =  values
})


Log all program console output to file on demand

Question: I have a task to implement a logging method that will take all program content up to logging method call and save it to file. The method should not overwrite already present info in file, but rather add new content to it.
What I need to write:

all program messages and output;
all user inputs in the way they appear on console (the program inquires it several times);

My thought on it is to create a StringBuilder object and start appending everything to it. Once logging method is invoked, ask for a file to save log to and save contents of StringBuilder to it. Then flush StringBuilder and continue to gather information. On second invocation, if the same filename is provided, just append new info gathered by StringBuilder.
However, this means that I will need to place gathering invocations all over the place where program output and user input are. Seems like not very optimal to me.
Are there any ideas on how to reach my goal differently and more optimally?
Thank you in advance.
Best regards,
Vadim
UPDATE: I actually was able to redirect system.out to gather everything to ByteArrayStream and then write to file on demand. But I still don't understand how to do it for inputstream. I don't need to redirect it, I still have to input eveyrthing from keyboard, it's just values that have to make it to logs in correct places. Am still searching for a solution.
Comment: that is the meaning of "extended" in previous comment: the corresponding stream must log in parallel to its default operation (similar to the `tee` command on unix)
Comment: you can change the `System.in`,  `System.out` and `System.err` to add the logging to the corresponding extended `InputStream` and `PrinterStream`
Comment: and will it preserve console output, if I redirect System.out to different place? Thank you.
Comment: Thank you, will have to do my research, since it's not something I've done before.
Answer: Do not reinvent the wheel. Go for a logging framework. There is one integrated into java anyway.
Alternatively you can use log4j, and there are other such frameworks out there.
Comment: Probably I have to. I'm taking courses and we haven't still dealt with logging frameworks and logging in general. Therefore I think I have to use whatever we've learnt at this point.
Comment: Just redirect stdout. Continue to use System.out.println() or whatever. Here is an example: https://github.com/paulwedeck/settlers-remake/blob/master/jsettlers.logic/src/main/java/jsettlers/main/JSettlersGame.java#L382
Comment: Thank you. I need to double outputs to StringBuilder and to console and inputs as well. Will look into it.


Loop com colunas e rows

Question: Tenho tentando fazer assim:
<?php foreach ($unfollow as $row): ?>

      <?php var_dump($row)?>

<?php endforeach ?>

Só que isso me tráz 1 row e uma coluna de 4.

O correto seria 1 row 3 colunas de col-md-4.
Como corrigir?
Answer: Pode tentar desta forma, criando uma nova .row cada vez que um contador alcançar um múltiplo de 3 (veja comentários explicativos no código):
<?php
$col = 1; // contador do laço
$divrow = "
"; // HTML da .row
$ufsize = sizeof($unfollow); // tamanho da array
echo $divrow; // imprime a abertura da .row
foreach ($unfollow as $row):
?>

      <?php var_dump($row)?>

<?php
   // se chegar na coluna 3, ou o valor do contador for igual ao tamanho da array,
   // fecha a div
   if($col%3 == 0 || $col == $ufsize){
      echo "
"; // imprime o fechamento da div da .row
      // se o valor do contador for menor que o tamanho da array,
      // imprime a abertura do .row
      if($col < $ufsize) echo $divrow;
   }
   $col++; // incrementa o contador
?>
<?php endforeach ?>

Comment: Resolvi com o comentário do amigo à cima
Answer: Você pode mudar o loop para as colunas:

  <?php foreach ($unfollow as $row): ?>

      <?php var_dump($row)?>

  <?php endforeach ?>

Desta forma irá produzir:

        ...

        ...

        ...

        ...

        ...

    ...

Como o Bootstrap é responsivo, irá alinhas as colunas "col-md-4" com este espaçamento e automaticamente irá arranjar as colunas excedentes em nova linha.
Espero ter ajudado.
Comment: Opa vlw amigo, deu certo

Loop com colunas e rows


Why do these 3 rules cause problems for me in iptables? (COMMIT line error)

Question: I am trying to export my rules from one server to another, but for some reason they fail on one.  One server is Xen and the other OpenVZ (this one is the one causing trouble).  They are both running Ubuntu (though different versions, 8.04 and 10.10 respectively) and also different versions of iptables (1.3.8 and 1.4.4 respectively).
I exported my rules fine, but when I run them I'm getting an error on the COMMIT line.  So I commented out each line in my rules one by one and discovered these three lines are the culprits:
<code>-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p tcp -m state --state NEW --dport 23 -j ACCEPT
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
</code>
What is wrong with these lines?  They look fine to me and they run fine on my Xen server...
This is the contents of the original rules file:
<code>*filter

#  Allows all loopback (lo0) traffic and drop all traffic to 127/8 that doesn't use lo0
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -d 127.0.0.0/8 -j REJECT

#  Accepts all established inbound connections
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

#  Allows all outbound traffic
#  You can modify this to only allow certain traffic
-A OUTPUT -j ACCEPT

# Allows HTTP and HTTPS connections from anywhere (the normal ports for websites)
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 443 -j ACCEPT

# Allows Tomcat, sms, and newrelic
-A INPUT -p tcp --dport 8080 -j ACCEPT
#-A INPUT -p tcp --dport 8009 -j ACCEPT

#  Allows SSH connections
#
# THE -dport NUMBER IS THE SAME ONE YOU SET UP IN THE SSHD_CONFIG FILE
#
-A INPUT -p tcp -m state --state NEW --dport 23 -j ACCEPT

# Allow ping
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT

# log iptables denied calls
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7

# Reject all other inbound - default deny unless explicitly allowed policy
-A INPUT -j REJECT
-A FORWARD -j REJECT

COMMIT
</code>
UPDATE:
Ok, so it looks like the only thing in common between all three of these is the option "-m", none of the rules which work have that option... what gives?
Comment: What does line 47 say?
Comment: Its just the COMMIT line... so it only says COMMIT
Comment: How about line 46, maybe?  Sorry, I've got nothing.
Comment: ill just post my rules haha
Comment: Have you tried feeding the lines into iptables one by one? That should give you an idea where the problem really is.
Comment: @wolfgangsz: yup, looks like there are 3 lines causing me trouble, i've reworded the question and posted my results above.
Answer: The errors are probably related to the fact that you need to load the relevant kernel modules before some of the options can be executed. Depending on the distro, some of these are loaded by default and others may be loaded automatically if certain options are used. It would appear that in your case you may need to load some manually, using modprobe.
<code>-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
</code>
In order to use a state condition, you need to load the ip_conntrack module.
<code>-A INPUT -p tcp -m state --state NEW --dport 23 -j ACCEPT
</code>
Same issue here
<code>-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
</code>
Not sure why this one is causing a problem.
I would recommend reading the man pages for iptables on that particular distro very carefully, then examine which kernel modules are loaded and possibly add some lines at the top of the batch file to load required kernel modules.
Here is the relevant output from one of our public gateways, which uses similar iptables rules.
<code>#> lsmod | grep ip
iptable_mangle         11392  0
ipt_recent             16672  2
ipt_LOG                13828  4
iptable_nat            13840  0
nf_nat                 25496  2 nf_nat_ftp,iptable_nat
ipv6                  287784  65 sit
dm_multipath           23704  0
</code>
Comment: Thanks wolfgangsz, I'll contact my VPS provider because I don't think I can load things into the kernel myself on a shared server right?  Also, the new server, when I run lsmod | grep ip, I get nothing, but when I run it on the old server I get something very similar to yours, with 2 extra modules (specifically the nf_conntrack and nf_contrack_ipv4.  Any suggestions before I contact my provider?
Comment: In order to load kernel modules you will probably need root access. Do you know whether you have sudo rights? You could just try to load a kernel module and see what happens. I know this sounds a little guerilla like, but AFAICT there is no real danger.
Comment: Yup I do have root access, so I'll give it a go then.  Do you have a link for how to get the kernel modules loaded on?  Also, any idea why nothing is showing up in lsmod | grep ip?  I tried also to ls /lib/modules/$(uname -r)/kernel/net/ipv4/netfilter and that didn't work because the folder kernel doesn't exist on the OpenVZ either!
Comment: Run lsmod and see what you get. There should be something. You might have to use find to locate the kernel modules (but I do admit that the missing kernel folder is rather strange).
Comment: Theres nothing... so weird, I just get the columns "Module                  Size  Used by", but nothing under them.  This is what I get from running $ modprobe nf_conntrack
WARNING: Deprecated config file /etc/modprobe.conf, all config files belong into /etc/modprobe.d/.
FATAL: Module nf_conntrack not found.
Comment: Hmm, that's strange, too. Almost as if this box was upgraded from a much earlier version and the upgrade failed halfway through. Do you have the folder /etc/modprobe.d/? And what is in it?
Comment: Yes I do, the contents of that folder are: blacklist-ath_pci.conf, blacklist-framebuffer.conf, blacklist.conf, blacklist-firewire.conf, blacklist-watchdog.conf, intel-5300-iwlagn-disable11n.conf... by the way, I think I've figured out the issue, after some research it seems that I can't load kernel modules into an OpenVZ container, my provider needs to do that on the host node and make it available to my container, cause the same kernel is used among all containers.  I'm waiting for my provider to respond to my request I'll let you know what happens, thanks for your help!
Comment: If you have other ideas though I'm always open to try things out :)
Comment: I think in this case you need to work with your service provider.
Comment: User [GiH](http://serverfault.com/users/55302/gih) wanted to add "If on the OpenVZ platform you will not be able to load kernel modules from within your container. Your provider must configure the host node to enable iptables."
Answer: Copy / Paste isn't the appropriate manner
You should use

iptables-save > somefilename.rules

to export the rules in a format compliant with what iptables-restore expects
and then

iptables-restore < somefilename.rules

to proceed with restore
See also the pretty good tutorial on making iptables rules persistant
Comment: thanks, but for some reason when i do iptables-save > somefile.rules, and then I open up the file in vi I see a blank file... what am I doing wrong?
Comment: Figured out what i was doing wrong :), forgot to sudo haha! Ok, so I got the iptables exported and copied them onto the new server, but I still get the same error, now its on a different line (18) because iptables-save compressed the rules and removed all the comments, but it still fails on the COMMIT line


Control the view in MVVM

Question: I created a project with the MVVM model, and done so with the view-first approach.
I have a TextBox in my XAML code, along with a Button to pass the data from the TextBox:

<TextBox
    MinWidth="30"
    Name="TagId"/>

<Button
    Command="{Binding AddTagCommand}"
    CommandParameter="{Binding Text, ElementName=TagId}"
    Content="Add"/>

When I click the button, I want the TextBox cleared.
According to the Prism manual:

In some cases, the code-behind may contain UI logic code that implements visual behavior that is difficult or inefficient to express in Extensible Application Markup Language (XAML), such as complex animations, or when the code needs to directly manipulate visual elements that are part of the view.

Here's the code behind, and the viewmodel.
//View - code behind
public partial class ApplicationStarterView : UserControl
{
    public ApplicationStarterView()
    {
    }

    public ApplicationStarterView(ApplicationStarterViewModel viewModel) : this()
    {
        DataContext = viewModel;
        InitializeComponent();
    }
}

//View model
public class ApplicationStarterViewModel : BindableBase
{
    private readonly IUnityContainer _container;

    public ApplicationStarterViewModel(IUnityContainer container)
    {
        _container = container;
        AddTagCommand = new DelegateCommand<object>(AddTag);
    }

    public ICommand AddTagCommand { get; private set; }

    private void AddTag(object input)
    {
        //Forward stuff
        //Clear TextBox
    }
}

Can I in any way squeeze in some code to do a TagId.Clear()?
Answer: I'd bind the text to another property on the view model.
That way, you can skip the command parameter and the AddTagCommand can directly read the new Text property, do his adding stuff and then clear it, thus updating TagId.
Completely unrelated piece of advice: it is almost never a good idea to inject the IUnityContainer... if you need to create stuff, use factories.
Comment: Property for ``Text`` sounds like the way to go. What do i do with the UnityContainer then? I need to be able to access it somehow...
Comment: What do you need it for? If you need it to do `Container.Resolve()`, rather inject an `IMyTagFactory` that has a `CreateTag` method.
Comment: This is the pattern you refer to, correct: http://www.dofactory.com/net/factory-method-design-pattern. I need the container to get all my different intances in the model. Since I do it view-first, the view creates the view-model, which creates the model, which does stuff for me. I might have misunderstood how the container should be used...
Comment: Yes, that's the pattern I referred to. Don't get me wrong - the container is great for creating instances, that's all what it is made for. BUT - if a class depends on the container, how does a user of that class know what the class uses the container for? If the class depends on a `IXYFactory`, it's obvious that it wants to create `IXY`s. Imagine you have to write a unit test for the class, how would you configure a mock for the container? So better hide the `Container.Resolve` in a factory in production code, and create a mock for the factory in the test.
Comment: Fair point. I will try to do more of that in the future. :) Thanks a lot!

Control the view in MVVM


Why am I getting this error from azure sql? Error Code [70527]

Question: I am encountering this error in azure SQL [70527] any suggestions on how to fix this? This is the first time I have encountered this error.

I would appreciate any advice at all, I'm at a loss how to fix this issue, I am not well versed with azure SQL at all
Comment: Was this database uploaded from a local SQL Server?
Comment: @MikeSmith-MCT-MVP yes it was imported from a local server
Comment: @IvanApungan can you show us more details about the error title?
Comment: Take a look at this article on "partially contained databases" and the issues of where a user is defined. https://learn.microsoft.com/en-us/sql/relational-databases/databases/contained-databases?view=sql-server-ver15
Answer: I am assuming you are migrating a database from on premise sql serve to Azure. I suggest you use the migration agent which will highlight all these issues with possible resolution in some cases.
The error code 70527 is related to user login which is highlighted in the following post as well
SQL70527 error in database project
You may have to create the user as per suggestion in the post above using the script method rather than the backup restore.
You can download the migration agent from below link
https://www.microsoft.com/en-us/download/details.aspx?id=53595


The vertices of the $n$-cube are painted in two colors

Question: The vertices of the $n$-dimensional cube are painted in two colors. The number of vertices of each color is the same ($2^{n-1}$). Prove that  at least $2^{n-1}$ edges connect vertices of different colors.
Comment: Yes, of course.
Comment: Do you mean coloring in the graph-theoretical sense, i.e., coloring of the hypercube $Q_n$?
Comment: @ blazs: No, I mean arbitrary painting of hypercube.
Comment: Ok, just to make perfectly sure: you allow vertices connected by an edge to have the same color?
Comment: @grizzly Where did this problem come from?  What have you tried?
Comment: @Tad We discussed this problem on the forum [dxdy](http://dxdy.ru/topic98745.html) (in Russian). We tried to find a combinatorial solution. Today I knew that this problem was given for homework in the book: _Combinatorics_ by Naum Ya. Vilenkin et al (In Russian).
Answer: The question can be phrased as follows: for any subset $S$ of $2^{n-1}$ vertices in the $n$-dimensional hypercube graph $H_n$, show that $|\delta(S)|\ge2^{n-1}$, where
$$\delta(S) := \{(u,v)\mid u\in S, v\notin S\}$$
is the boundary of $S$.
It is a standard result of spectral graph theory that, for any subset $S$ of a graph $G$,
$$|\delta(S)| \ge \lambda_2 |S| (1-|S|/|V(G)|)$$
where $0=\lambda_1\le\lambda_2\le\cdots\le\lambda_{n-1}$ are the eigenvalues of the Laplacian of $G$.
Now, $H_n$ is the $n$-fold (Cartesian) graph product of the graph $H_1$ having two vertices and one edge.  The eigenvalues of (the Laplacian of) $H_1$ are $0$ and $2$, and it follows that the eigenvalues of $H_n$ are $0, 2,\ldots, 2n$, each with multiplicity $\binom nk$. Thus, for $H_n$, we have $\lambda_2=2$; it follows that if $|S|=2^{n-1}$, we have
$$|\delta(S)| \ge \lambda_2 |S| (1-|S|/|V(H_n)|)=2\cdot 2^{n-1}\cdot(1-2^{n-1}/2^n)=2^{n-1},$$
as required.
One reference which seems to have all of this, with some more detail, is Alexandra Kolla's lecture notes.
Comment: Thank you for an interesting solution. I have not studied the graph theory, but I was able to understand it in general terms. I know that combinatorics and graph theory are connected. But here it is at such a depth... It is impressive!
Answer: Let's reformulate this problem as follows: prove that a randomly chosen edge is bichromatic (has ends of different colors) with probability of at least $1/n$.
Instead of picking a random edge directly, you can equivalently first pick two random antipodal vertices ($x$ and $\neg x$) of the hypercube, then pick a random $n$-edge path between them, and then pick a random edge from that path.
There are two cases: either $x$ and $\neg x$ are of the same color or not. If they are not of the same color, then at least one edge on any $n$-edge path between them is bichromatic. So the chance that a randomly chosen edge on that path is bichromatic is at least $1/n$.
The second case is when $x$ and $\neg x$ of the same color, for example, both are white. Let's divide the set of vertices in the hypercube into layers. Layer $k$ will consist of all vertices with the Hamming distance $k$ from $x$. Since there are the same number of black and white vertices, and white has already been used for $x$ and $\neg x$, at least one of these layers, say layer $k$, will have more than half of its vertices black. Choosing a random $n$-edge path from $x$ to $\neg x$ is equivalent to choosing a random vertex $y$ from layer $k$, and then choosing a random $k$-edge path from $x$ to $y$, and a random $(n-k)$-edge path from $y$ to $\neg x$. If vertex $y$ is black (probability $> 1/2$), then since both $x$ and $\neg x$ are white, each of the paths $x$-to-$y$ and $y$-to-$\neg x$ contains a bichromatic edge. So with probability $> 1/2$, there are at least 2 bichromatic edges on a path from $x$ to $\neg x$, which means that the expected number of bichromatic edges on such a path is $> 1$. This means that a random edge on such a path is bichromatic with probability $> 1/n$.
What colorings achieve the $1/n$ lower bound? Since the second case ($x$ and $\neg x$ same color) results in the probability $> 1/n$, colorings that achieve the lower bound have all antipodal pairs of vertices of different colors. Moreover, any $n$-edge path between such vertices has exactly 1 bichromatic edge. This is a pretty strong condition because given any two (bichromatic) edges that flip different bits, one can find a pair of antipodal points and an $n$-edge path between them where both edges occur. This means that colorings that achieve the lower bound have bichromatic edges all flipping the same bit. This means that the only colorings that achieve the lower bound are colorings that are based on the value of the bit at some fixed index.
Comment: This is interesting, thanks. Perhaps this will work. So far, it is not entirely clear to me how to take into account that many different paths can pass through the same bichromatic edge. This interferes with this probabilistic construction.
Comment: Describing the set of n-edge-paths between antipodal points that contain a given edge seems indeed non-trivial. But I don't think this is needed here. All that is needed, it seems to me, is that the random edge sampling described in the 2nd paragraph of my answer is equivalent to uniform edge sampling. Is the validity of this equivalence that is your concern here?
Comment: Here's a sketch of my reasoning. Let a "rotation" of a hypercube mean any of its symmetries (https://math.stackexchange.com/a/15457/643521). The edge sampling method in 2nd paragraph is rotation-agnostic, that is, the effect is the same on the original hypercube and on any of its rotations. Also, using the generators of this symmetry group, it's not difficult to convince oneself that this group is edge-transitive, that is you can transform any edge into any other edge by rotating the hypercube. These two facts together imply that all edges should be selected with the same probability.
Comment: Intuitively, I can agree with your answer. But I still do not quite understand its formal construction. You are considering a probability space of edges that make up paths. You get >1/n probability that a random edge of each path is bichromatic. OK.
Comment: To complete the solution, you need to move to another probability space of arbitrary cube edges. You want to say that out of n randomly chosen edges of the cube, at least 1 is bichromatic. You argue this with considerations of symmetry. Intuitively I agree, but I don't trust my intuition.


File Upload / The connection was reset

Question: I am writing an upload handler (asp.net) to handle image uploads.
The aim is to check the image type and content size before the entire file is uploaded.  So I cannot use the Request object directly as doing so loads the entire file input stream.  I therefore use the HttpWorkerRequest.
However, I keep getting "The connection to the server was reset while the page was loading".
After quite a bit of investigation it has become apparent that when posting the file the call works only if the entire input stream is read.
This, of course, is exactly what I do not want to do :)
Can someone please tell me how I can close off the request without causing the "connection reset" issue and having the browser process the response?
Answer: There is no way to do this, as this is how HTTP functions. The best you can do is slurp the data from the client (i.e. read it in chunks) and immediately forget about it. This should prevent your memory requirements from being hammered, though will hurt your bandwidth.
Comment: Thanks Mike.  Since my upload is done using ajax (jquery form) I can still cause the call to fail so that the entire file is _not_ uploaded.  I have another bit polling the status so I'll handle the failure there.

File Upload / The connection was reset


Fazer um foreach que não repita o mesmo dados

Question: Tenho esse foreach, em uma tabela com mais de 5000 registros. Existe apenas 6 tipos de unidade de negócio. Gostaria que no foreach e na linq, quando aparecesse um tipo de UN, ele carrega e depois não mais repita ele, ou seja, ele carrega outro diferente e assim por diante, de forma que o resultado venha somente 6 registros. Abaixo meu foreach.
foreach (var _idmotivo in monta_arvore)
            {
                _listaUnidade = db.Apresentacao
                                .Where(un => un.Codigo_Unidade_Negocio == _idmotivo.Codigo_Unidade_Negocio)
                                .Select(u => new MontaArvoreAcao
                                {
                                    Unidade_Negocio = u.Unidade_Negocio,
                                    Codigo_Unidade_Negocio = u.Codigo_Unidade_Negocio
                                }).ToList().OrderBy(o => o.Unidade_Negocio);
            }

Comment: Não entendi em qual você quer fazer. É no monta_arvore ou no _listaUnidade?
Comment: No _listaUnidade, pois ele me trás vários nomes e não gostaria de ver repetidos. Usei distinct e nada.
Answer: Você pode fazer usando o GroupBy.
_listaUnidade = db.Apresentacao
                                .Where(un => un.Codigo_Unidade_Negocio == _idmotivo.Codigo_Unidade_Negocio)
                                .Select(u => new MontaArvoreAcao
                                {
                                    Unidade_Negocio = u.Unidade_Negocio,
                                    Codigo_Unidade_Negocio = u.Codigo_Unidade_Negocio
                                })
                                .GroupBy(x=>x.Unidade_Negocio)
                                .Select(x=>x.First()
                                .ToList().OrderBy(o => o.Unidade_Negocio);

Comment: Deixa-me explicar. Dessa forma só trás um e não é isso que eu quero, exemplo. Eu tenho um total de 6 motivos. Para cada motivo, eu posso ter um ou mais UN e também são 6 UN no total. Então, há Motivos que pode trazer 3 UN, outros podem trazer 2, 4 ou mais ou menos. É isso que eu necessito. Porém, um motivo pode ter 300 Genéricos, aí só quero que mostre apenas 1(Genérico) e o mesmo para MIP, RX e etc....
Comment: A minha dificuldade está no meu where. Vou fazer outro post pensando apenas no where e como trazer cada UN referente ao ID passado. O resposta do Diego Zanardo está correta. Fiz um pouco diferente, mas é a mesma coisa postada pelo Diego Zanardo.


C# Export to Excel format

Question: ActionResult:
var strLawTable = new StringBuilder();

strLawTable.Append("
");
strLawTable.Append("
");

strLawTable.Append("Dollar	");

strLawTable.Append("
");
strLawTable.Append("
");

strLawTable.Append("
");

foreach (Currency currency in Model.List)
{
strLawTable.Append("
");

strLawTable.Append("=\"" + GetExcellFormatString(Currency.USD) + "\"	");

strLawTable.Append("
");
}

strLawTable.Append("
");

string headerTable = "
" + strLawTable + "
";

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=TestFile.xls");
Response.ContentType = "application/ms-excel";

Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

System.IO.StringWriter sw = new System.IO.StringWriter();
sw.Write(headerTable);

System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);

Response.Write(sw.ToString());
Response.End();

GetExcellFormatString method:
public string GetExcellFormatString(double doubleAmount)
{
            if (doubleAmount < 1000)
                return doubleAmount.ToString("0.00");
            else if (doubleAmount < 1000000)
                return doubleAmount.ToString("0000.00");
            else if (doubleAmount < 1000000000)
                return doubleAmount.ToString("0000,000.00");
            else if (doubleAmount < 1000000000000)
                return doubleAmount.ToString("0000000000.00");
            else return doubleAmount.ToString();
}

My question:
After I exported the data into an Excel file, I have values in my Excel table below,
Exported Excel table
Dollar
50.0

35.0

40.0

60.0

etc..

If I press to "ctrl" and click with mouse 35.0 and 40.0 Excel can not sum 35.0 and 40.0 because 35.0 is string displays "35.0" and 40.0 is string displays "40.0".
The problem is about sum selected rows however I can not sum because values are string not numeric
How can I remove " " out of string number in Excel table by C# code ?
Thanks.
Comment: What if you try using another decimal separator, `,` instead of `.`?
Comment: why not just remove the quotes from your string? change `strLawTable.Append("=\"" + GetExcellFormatString(Currency.USD) + "\"");
` to -> `strLawTable.Append("=" + GetExcellFormatString(Currency.USD) + "");`
Comment: i have to put . any solutions please ?
Comment: @chancea your answer is the best of the best. it worked.this was what i looked for all day today.. Please answer and i will accept it best answer thank you so much
Comment: @Richard glad it worked, I posted that as the answer
Answer: To remove the quotes change this line:
strLawTable.Append("=\"" + GetExcellFormatString(Currency.USD) + "\"	");
                                                     ^^remove                                     ^^remove

to this:
strLawTable.Append("=" + GetExcellFormatString(Currency.USD) + "	");

Answer: If you're not opposed to using third party libraries, there is this solution:
http://www.codeproject.com/Articles/692092/A-free-Export-to-Excel-Csharp-class-using-OpenXML
It uses OpenXML library (available through nuget).
It works like a charm - well, if there are only integers and strings in your data. It can be customized, though. The method to look at is WriteDataTableToExcelWorksheet(DataTable dt, WorksheetPart worksheetPart), where you'll have to take care of different data types (Double, Decimal, DateTime...). I also recomend using number.ToString(CultureInfo.InvariantCulture) when getting string values of numeric columns. Otherwise there will be the same problem that you have: the column won't be recognized as a correct number (at best it will be a text column, or there will be error in the cell).
You can also set up custom formatting of numbers in your column (if you really have to use specific formatting for your numbers): http://lateral8.com/articles/2010/6/11/openxml-sdk-20-formatting-excel-values.aspx

C# Export to Excel format


Python program getting stuck on an elif

Question: Fairly new to coding so apologies if this is basic.
I am doing this as a project to pull up useful information quickly whilst flying.  Everything has been working pretty well but I can't get past this.   The program is meant to ask what I want data on.  I would like to be able to type short hand glafail and it will ask which runway then depending on my answer pull up a procedure.  If I ask for glfail however it puts me into the previous elif branch, it asks me 'Which runway? 16 or 34?  When it should ask 'Which runway? 05 or 23?.   I would be grateful of any ideas on where I am going wrong?
regards
elif answer == 'efailabz' or answer == 'engfailabz' or answer == 'efailegpd' or answer == 'engoutabz' or answer == 'eturnabz' or 'efail abz' or answer == 'engfail abz' or answer == 'efail egpd' or answer == 'engout abz' or answer == 'eturn abz':
    print('')
    print('')
    print('')
    print('which runway? 16 or 34?')
    orient = input()
    if orient == '16':
        engpop(abdn16)
        main()
    elif orient == '34':
        engpop(abdn34)

elif answer == 'glfail' or answer == 'engfailgla' or answer == 'efailegpf' or answer == 'engoutgla' or answer == 'eturngla' or 'efail gla' or answer == 'engfail gla' or answer == 'efail egpf' or answer == 'engout gla' or answer == 'eturn gla':
    print('')
    print('')
    print('')
    print('which runway? 05 or 23?')
    orient = input()
    if orient == '05':
        engpop(gla05)
        main()
    elif orient == '23':
        engpop(gla23)
        main()

Comment: use `answer in ['', '', '']`
Comment: you should not call the main as you have called
Comment: `answer == 'eturngla' or 'efail gla'` will never work for 'efail gla'.
Comment: Thanks all, especially The_spider.  Can't believe I missed that! solved!
Answer: As @The_Spider pointed out was the problem within answer == 'eturngla' or 'efail gla'.
Here are some pointers for you since you mentioned that you are new to coding:
You can shorten your if statements. Use the notation pointed out by @azro:
if answer == 'efailabz' or answer == 'engfailabz' or answer == 'efailegpd' or answer == 'engoutabz' or answer == 'eturnabz' or 'efail abz' or answer == 'engfail abz' or answer == 'efail egpd' or answer == 'engout abz' or answer == 'eturn abz':
    # do stuff

Can be written like this:
if answer in ['efailabz', 'engfailabz', 'efailegpd', 'engoutabz', 'eturnabz', 'efail abz', 'engfail abz', 'efail egpd', 'engout abz', 'eturn abz']:
    # do more readable stuff

Avoid using the main() function for anything other than to kick off your program

Many languages, such as C, C++, Java, and several others, define a
special function that must be called main() that the operating system
automatically calls when it executes the compiled program. This
function is often called the entry point because it is where execution
enters the program.
By contrast, Python does not have a special function that serves as
the entry point to a script. You can actually give the entry point
function in a Python script any name you want!
Although Python does not assign any significance to a function named
main(), the best practice is to name the entry point function main()
anyways. That way, any other programmers who read your script
immediately know that this function is the starting point of the code
that accomplishes the primary task of the script.
Source: Defining Main Functions in Python
(realpython.com)

Print multiple newlines in one print() call
You can print multiple new lines using \n. Like this:
print("\n\n\n")

This will print 3 new blank lines.

Python program getting stuck on an elif


User photo gallery that another user can view

Question: I'm looking to give my user the ability to to have a personal photo gallery that when another user clicks on their profile they can see said gallery?
I know i can create a content type and view, but not sure where to go from there as far as only exposing the necessary photos for a specific user to another. basically a dumb-ed down version of what Facebook has as far as photos.
Answer: for some interesting options, take a look at the Album Photos module. I'm not sure if it will do what you're asking OOB, but if you use it, it would change your question so I'll suggest it.

"Album Photos" is an image album module providing multi-user album
  features. The module development objective is to provide a
  comprehensive image album solution for Drupal.
Version 7.x-3.x Highlights
Integrates with core image styles. Uses Libraries API 2.x for
  Jeditable. Built in support for Colorbox. Vote on images with Voting
  API. Comment on images. Built in support for Plupload. Upload multiple
  images with Plupload. Limit the number of albums created per role.
  Reads image exif parameters. Nice presentation of the images. Views
  integration. Support for private file system. Drag and drop interface
  to re arrange photos and albums to sort by custom weight order. Photos
  Access Included as a sub module. Enable this module to control who has
  access to the photos and galleries.
Create password protected photo galleries. Create galleries with a
  list of collaborators who can edit the same gallery. Create private /
  locked galleries that can only be seen / edited by the gallery owner.
  photo gallery, image gallery, user managed photo albums
Answer: You can add an image field to the profile fields rather than use a node and content type, under configuration and account settings choose manage fields and add it there.
If you do want to use a content type and a node, add a reference to node:author and add a contextual filter with a default value to get user ID from URL, that will only show the images from the node(s) that user has created.


What changes should I make while bowling to get back to best of my line and length?

Question: I was a fast bowler when I was younger. I used to mark 14 steps for my run-up. It was a smooth and clean run-up with the most accurate line and length.
It has been more than 10 years since I gave up playing cricket, other than playing a few matches in leather ball four years ago. Now, I'm 32 and back playing tennis ball cricket. I look like a novice when I try to bowl, especially with my run-up. I tried making the same 14 steps and failed. I had to make so many adjustments before making it to the crease, and my line and length is totally off.
What changes should I make while bowling to get back to best of my line and length?
Answer: Did the same - took a lengthy break before getting back into club cricket in my 30s. A lot changes in 10 years! The length of your stride, your strength, your fitness...my advice would be, don't try to force your adult self into your youthful self's shoes. Trying to mimic the same run up is only going to frustrate you.
What worked for me, was remembering the rhythm of delivery - how it felt when I bowled a good ball. Delivery stride, upper body position, arm movement, head position...that moment of delivery. Then, I went to the nets and experimented with different run ups until I felt, not the same, but similarly comfortable, at which point line and length came back quickly with practice.
The key really being practice, though. Pound the nets until it comes back. Put markers on a good length and keep plugging at it until you can reliably put the ball where you want to, then build up the pace. And if you've lost a couple of yards of max pace, don't beat yourself up if it doesn't come back straight away or at all - work on variations instead. A surprising cutter mixed in now and then can be just as effective as a blistering yorker. If you end up with both in your bag, all the better!
Good luck!
Answer: Just Relax. Start with new Run Up with which you are comfortable now. Dont go with too much pace at start. Just practice with your line and length by hitting regular spots. You can do this by keeping some marks on the pitch and try to hit it. Once you master your line and length then you can think of adding pace and other variations. Try off-cutter and leg-cutter if you are very fast bowler.
Answer: Unfortunately, there's no secret - it will require dedication and time. However, there have been many instances of bowlers re-inventing themselves (at all levels of cricket). As a seamer myself, when I remodelled my action and approach earlier this year, I focussed on a few key things:

Wrist position - get it stiff, extended and (for an outswing bowler) angling towards 1st slip.
Maintain a strong left arm (for a right arm quick), keep it nice and high.
Try and be upright through your delivery stride.

Probably the key aspect for your return @andrew would be to clarify if you are a front-on or side-on bowler (either is fine, compare Dale Steyn and Jimmy Anderson for instance). This will allow you to align your shoulders and hips accordingly reducing the risk of probably the thing most likely to derail your return, which would be a back injury. Then echoing in the the words of the other comments, build your run-up up slowly and go from there! Wishing you the best of luck in your return!


Can I create a chained SSL certificate that is recognized by browsers?

Question: Let's say I have a certificate that is valid for example.com (and backed by a known SSL vendor). I want to be able to have a test version of the domain, test.example.com, that is also secured with an SSL certificate, but I'd like to do so without paying for a commercial certificate (I realize there are "free" certificates but nearly all of them come with time limitations, which doesn't work for me).
It's apparently possible to create a chained certificate off of that certificate. What I'm wondering is whether browsers will recognize that chained certificate as valid.
Note that the certificate for example.com is an SAN certificate and covers other domains like docs.example.com, example.org, etc.
Ideally I would like the chained certificate to also be an SAN certificate, and just provide test analogs of each domain: test.example.com, test.docs.example.com, test.example.org, etc.
I'm aware I'll need a separate IP address for the test certificate.
This is on Apache and CentOS, by the way.
Comment: You can perhaps hire the NSA to use top-flight mathematicians to invent new science and engineer a hash collision attack on the CA.  Alternatively, you can buy a wildcard cert.
Comment: A wildcard would not be sufficient. Sounds like I either create a self-signed CA certificate or buy another SAN certificate.
Answer:
What I'm wondering is whether browsers will recognize that chained certificate as valid.

None of them. Within your certificate, it has the entry under Certificate Basic Constraints:
Not Critical
Is not a Certification Authority

Once the browser sees that as an intermediate certificate, it'll reject the ones you 'sign' it with.
Answer: You cannot issue more certificates off of your example.com certificate.  Check its x509 Basic Constraints field.  Every certificate that a trusted CA issues to a client should always have the CA:FALSE constraint (though recently, a major CA admitted to issuing a certificate to a client with this restriction removed).
If you need to test with certificates that you craft, you'll need to make your own CA and trust it in the client browsers.
Answer: If you have bought your certificate already then tough luck. If not, look at buying either a wildcard or putting Subject Alternative Name attribute in the CSR. Most CAs will happily sign it without charging you extra.
Comment: Note that the certificate I bought is great and perfect for my normal needs and needs no adjustment. I just need to either create a self-signed certificate or buy another SAN certificate (I'll probably go with the former).
Comment: Well, you asked for a cert that is recognized by browsers. Self-signed one is certainly not.
Comment: Yeah, I'll just have to tell all my testers to install the CA. Would have been nice to skip that step.


Rails - Can I use observer to cancel the save of a model

Question: I have a before_save observer in one of my models, can I cancel the saving process if a certain condition is matched in the observer?
Answer: Yes you can. Just return false from your observer. It will cancel the save.
At least if you use Rails 3.1 that is. If you use an older version of Rails, you have to define a callback method using:
class MyModel < ActiveRecord::Base
  before_save :my_callback

  def my_callback
    # do something
    false
  end
end


Where can I configure user and admin email message in Ubercart cart module?

Question: Where can I configure user and admin email message in Ubercart cart module in Drupal 7?
I want to change the email body of user notification email and admin.
Answer: Go to

sites/all/module/ubercart/uc_order/templates/

than select file user or admin


Solving an equation modulo 9

Question: solve for x in :
a) $4x+3\equiv 8$ (mod9)
So do we just subtract the 3? I know how to solve if it were asking
$4x\equiv 3$ (mod9) but Im not sure how to do the problem above.
Comment: Yes, subtract 3 from both sides, giving $4x\equiv 5\mod{9}$; then all you have to do is find the inverse of $4\mod 9$.
Comment: $4x\equiv 5\pmod9\Rightarrow x=8$ (because $4\cdot8=32=27+5$)
Answer: it is $$4x\equiv 5\mod 9$$ so $$x\equiv \frac {5}{4}\mod 9$$ and we get
$$x\equiv \frac{5+9+9+9}{4}\equiv \frac{32}{4}\equiv 8\mod 9$$
Comment: What are fractions of integers modulo $9$?
Comment: add the $9$s *before* dividing by $4$, and this answer would be better
Comment: why would this be better?
Comment: Respectfully, I tend to side with Zubin on this one, but $4$ is coprime to $9$ so what you did is legitimate ...
Answer: To solve $\;4x\equiv 5\mod 9$, you have to find the inverse of $4$ modulo $9$, which exists since $49-$ and $9$ are coprime;
Start from a Bézout's relation between $4$   and $9$:
$$1\cdot 9-2\cdot 4=1$$
This relation implies $\;(-2)4\equiv 1\mod 9$, so the inverse if $4$ modulo $9$ is $-2$ and we obtain the solution of the equation as follows:
$$x\equiv 5\mod 9 \implies (-2)4x\equiv (-2)5\mod 9\iff x\equiv-10\equiv-1\mod 9$$
Answer: Subtract the 3
$4x \equiv 5 \pmod{9}$
In modulo, dividing is multiplying by the inverse, so we need to know what $4^{-1} \pmod{9}$ is. You can solve this using The extended euclidean algorithm, or with small modulos like this, just guess and check. We are looking for what to multiply 4 by to get one more than a multiple of 9 (because the inverse of a number is what we multiply the number with to obtain the identity, which in this case is 1), or
$4y \equiv 1 \pmod{9}$. Which ends up being $y = 7$ (since $7\cdot 4 = 28$ which is one more than 27, which is a multiple of 9), thus $4^{-1} \equiv 7 \pmod{9}$
So now
$4^{-1}4x \equiv 4^{-1}5 \pmod{9} \Rightarrow x \equiv (7)5 \pmod{9} \Rightarrow x \equiv 35 \equiv 8 \pmod{9}$
Answer: The reason we can subtract 3 on both sides is because
$4x +3 \equiv 11 (\mod 9) $ is the same as saying
$(4x+3)+9k=11$
$(4x+3)-3+9k=11-3 $
$(4x+3-3)+9k=8 \implies 4x \equiv 8 ( \mod 9)$

Solving an equation modulo 9


How to keep a dynamic table row when it has no value?

Question: I have this code :
const HistoricalGrid = ((props) => {
return (

        <DataTable rows={props.selectedFile} headers={headers}>
            {({ rows, headers, getTableProps, getHeaderProps, getRowProps }) => (

                    <TableHead>
                        <TableRow>
                            {headers.map((header) => (
                                <TableHeader {...getHeaderProps({ header })}>
                                    {header.header}
                                </TableHeader>
                            ))}
                        </TableRow>
                    </TableHead>
                    <TableBody>
                        {props.selectedFile.map((row) => (
                            <TableRow rows="4"  {...getRowProps({ row })}>
                                <TableCell key={row.id} >{row.name}</TableCell>
                                <TableCell key={row.id}>{row.type}</TableCell>
                                <TableCell key={row.id}>{new Date().toString()}</TableCell>
                            </TableRow>
                        ))}
                    </TableBody>

            )}
        </DataTable>

But, I only get the rows data when a button is clicked, how can I keep the rows even if has no value ?
Answer:
const generateNRows = nb => {
     const rows = [];
     for($i = 0; $i < $nb; $i++){
         rows.push(
);
     }
     return rows;
}

const nowDate = new Date();

return (...

                        {props.selectedFile.map((row) => (
                            <TableRow  {...row} key={row.id} >
                                <TableCell>{row.name}</TableCell>
                                <TableCell>{row.type}</TableCell>
                                <TableCell>{nowDate.toString()}</TableCell>
                            </TableRow>
                        ))}
                        {props.selectedFile.length < 4 && (
                            <>
                                {generateNRows(4 - props.selectedFile.length)}
                            </>
                         )}

Answer: you can check the array length and use a ternary :
                        {props.selectedFile.length
                            ? props.selectedFile.map((row) => (
                               ...
                            ))
                            : <TableRow>No result</TableRow>
                        }

Comment: how can I do that with 4 rows? because if I use 4 row in the else... when I get data it will be one row in the true condition, you know ?
Comment: I haven't enough informations to help you clearly I think. For example, what do your TableRow component do ?
What you do looks really strange without TableRow props context.
Because TableRow probably render a  no ? which contains 3 .
So the rows="4" is for what ? You render 4 times {props.children} by array index ?.
Anyway, if you want to set 4 tr in the else you can do :
`: <>

`
Comment: yeah, almost... I want to set 4 initial empty rows, but when I receive the data, the 4 rows will turn into one according to my code... how can I fill the 4 rows naturally ?


Can tbats forecast partial years

Question: I have several years of daily data from August to December. I read that I can use
tbats from the forecast package. Each year has approximately 153 days but sometimes
it has less. I am using the code below. Is this correct? I am trying to predict for the
next 1224 days (8 years) but I am getting a straight line for the predictions.
library(forecast)

head(creek)
creek <- creek[,c(1,2)]
y <- msts(creek$Mean, seasonal.periods=c(7,153))
fit <- tbats(y)
fit
fc <- forecast(fit, h = 1224) ;fc
plot(fc)
autoplot(fc)

Data is here: https://login.filesanywhere.com/fs/v.aspx?v=8c6d638c60606fa66d9d
Answer: TBATS models seasonality in the data with periods equal to the seasonal periods specified. If your data is not periodic, then it's not going to find the seasonal patterns, and may just settle for a simple model with no seasonality. That is what appears to have happened here.
When you create the msts object, all the date information is lost, so there is no way it can tell what is a full year or a partial year. It just looks for periodicities of length 7 and 153, but can't find them.
Comment: Thanks, will try Arima maybe?

Can tbats forecast partial years


JS script not working else if with redirect

Question: I have the code below its just a simple validator script/code that checks if field is empty it throws an error message and redirect if not. Somehow it's not working im just a beginner to this though. The validation works but when redirecting its not.

Input your Name and Submit

<form name="form1" onsubmit="required()">

<input type='text' name ='text1'/>

*Required Field

<input type="submit" name="submit" value="Submit" />

</form>

Javascript:
function required()
{
var empt = document.form1.text1.value;
if (empt === "")
{
alert("Please input a Value");
return false;
}
else
{
window.location.href = '../continue.php';
return true;
}
}

The checking if empty works but the redirection if not empty is not working.
Comment: what happens when the redirection doesn't work?
Comment: You are submitting a form and you are setting the location. Pick one or the other. If you want to change the page, than just set the action of the form.
Comment: `window.location.href = '../continue.php';` this line has no problem. Make sure that PHP page is really doing stuff, because if you change the page to e.g. Google, it works.
Comment: http://stackoverflow.com/questions/3350247/how-to-prevent-form-from-being-submitted

onsubmit="return require()"
Answer: Okay so you have a couple of issues. One you are trying to cancel the form submission, but you lack a return statement in the onsubmit handler.
<form name="form1" onsubmit="return required()">

Next issue is you have a form that is trying to submit back to itself and you are setting the location. So you have two actions that have a race condition where one will win. So you got to pick one. Either you submit the form, or you change the location. Now the form can change the location if you set the action attribute.
<form name="form1" onsubmit="return required()" action="NewPage.html">

and the script:
function required() {
    var empt = document.form1.text1.value;
    if (empt === "") {
        alert("Please input a Value");
        return false;
    }
    return true;
}

or return false in the else and set the location like you were.
Answer: You could do this :
<form name="form1" onsubmit="return required()" >

<input type='text' name ='text1'/>

*Required Field

<input type="submit" name="submit" value="Submit" />

</form>

and then :
else
{
  window.location.replace('../continue.php');
  return false;
}


I want OpenID on GAE/J. I don't want yet another +100kB JAR. Am I lost?

Question: Usually people ask for 'best library', but I assume OpenID authentication is only a couple of requests in/out...? And I'm on GAE where more JARs means slower cold-start. For example openid4java-0.9.5.jar has 190kB. That seems like an insanely high cost for some URL reading and text parsing.
Am I missing something? Is it more complicated then what is needed when requesting access_token and user info from Facebook?
Is there some well explained howto? (This looks good but seems to be useful only for Google Accounts.)
Or is the authentication that complicated (or identity providers that non-compatible) that I should just accept +190kB and add them to my JARs? (Or maybe wait with OpenID for now.)
Comment: App Engine now supports OpenID natively. Is there a reason you can't use that?
Comment: The only reason would be that I did not know that. Silly, I know. :P Thank you, Nick!! Could you give me some URL please? I'm unable to google anything that would look 'official' enough.
Comment: http://code.google.com/appengine/docs/java/users/overview.html
Comment: I already have it, the link has shown when I switched from Google Account authentication to Federated login. :) If you care about rep. write this as answer, I will give you the credit. Thanks anyways!
Answer: Use the Federated login characteristics provided by the Google App Engine.
Federated Login refers to any service that allows users to create a single ID or account and use it to authenticate with various services. OpenID is the only Federated Login supported by the Google App Engine Users service.
You can find more information about the Authentication Options here:
http://code.google.com/appengine/docs/java/users/overview.html#Authentication_Options
And I would recommend to read the "User Experience summary for Federated Login" also:
http://sites.google.com/site/oauthgoog/UXFedLogin/summary
Comment: Thanks, I already got the answer, see above. (It has not been marked because it was given in a comment.)
Answer: I think it's always better to use a good library than to write thing by oneself. Is 100 kB a big amount for a server-side code? If you really want to reduce the size of your final code, better use a good obfuscator, for example ProGuard can shorten method names and remove unnecessary code.
But remember that premature optimization is the root of all evil - such stripping JARs may have big sense for applets or other code that users have to download, but IMO has little sense for server-side applications.
Comment: Thanks, but I don't think it is reasonable to use library for something that can be done in 5 lines of code. But it is very common thing to see...
Answer: +1 for the default Open Id (though experimental) support in GAE
Nevertheless, I've used RPX (now janrain) : http://www.janrain.com/products/engage eariler. Nicely fits into your requirement - no jars, least amount of code and support for all login openid / social interfaces. All you need a publicly accessible call back URL.
Check it out!


$\forall x\in[a,b],\;M(x)\in O_{2n+1}(\Bbb R)$. Why is $M'(x)$ non-invertible?

Question: Let $M$ be a function from $[a ; b]$ to $M_{2n+1}(\mathbb{R})$, of class $\mathcal{C}^1$ such that:
$$\forall x \in[a ; b], { }^t M(x) \cdot M(x) = I_n.
$$
I want to show that:
$$\forall x \in [a ; b], M^{\prime}(x) \notin GL_{2n+1}(\mathbb{R}).
$$
Starting by taking the derivative, I get:
$$\forall x \in [a ; b], { }^tM(x)M^{\prime} (x)+ { }^tM^{\prime}(x)M(x)=0.
$$
Any help!
Comment: How did you arrive at your derivative?
Comment: For families $A(x), B(x)$ of operators we have for fixed $x$ $$A(x+h)B(x+h)=(A(x)+hA'(x)+o(h))(B(x)+hB'(x)+o(h))=A(x)B(x)+h(A'(x)B(x)+A(x)B'(x))+o(h).$$ Thus, $$(A(x)B(x))'=A'(x)B(x)+A(x)B'(x).$$
Comment: What about taking the determinant of your relation?
Comment: Will that be true though? Consider the simplest case of a rotation by an angle $x$. Would the derivative of that respect your condition?
Comment: Yes, sorry I knew the derivative.. Unfortunately I didn't write it correctly in latex. I will modify it!
Comment: I tried, it doesn't work..
Answer: If you look at this link you can see one can write $M'(t)=A(t)M(t)$, where $A(t)$ is antisymmetric $\forall t\in I$.
Taking the determinant:
$$\det \left( M'(t)\right)=\det\left(A(t)\right)\det\left(M(t)\right)=\pm\det\left(A(t)\right)$$
For an $n\times n$ antisymmetric matrix $A$, we have $n=1[2]\implies \det\left(A(t)\right)=0$, thus $M'$ is singular for odd $n$.
Comment: @Motaka Indeed, I forgot to write the $\pm$
Comment: That's great. One last Qst: why did you consider $det(M(t))=1$, I think it may be $-1$. I know that it will not change the rest of the proof..


Comparando dois valores para efectuar um if

Question: Bom dia,boa tarde e boa noite.
Tenho um código que contempla uma listagem de checkbox e radio para que meu usuário selecione a operação desejada, porém ao marcar um radio o mesmo não deveria poder selecionar qualquer check que não fosse o da linha do rádio, mas não estou conseguindo fazer esse bloqueio para as demais linhas, ele funciona apenas na primeira linha da minha tabela e não tenho muito conhecimento em JS. A função que não funciona como imaginava é a validaMawb.
   function testaCheck(idMaster) {
    var inputs, i, checados = 0;
    inputs = document.getElementsByTagName("input");
    for (i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "checkbox") {
            if (inputs[i].checked == true) {
                checados++;
                document.getElementsByName('DS_MD' + idMaster).value = idMaster;
                $("#formSelectMAWB").find("#masterDireto").val(idMaster);
            }

        }

    }

    if (checados > 1) {
                uncheckAll(inputs);
                document.getElementsByName('DS_MD' + idMaster).value = null;
                $("#formSelectMAWB").find("#masterDireto").val(null);
            }
};

function uncheckAll(inputItems){
    alert("MAWB não selecionado ou MAWB diferente do Direto. Favor refazer a seleção");
    for (i = 0; i < inputItems.length; i++) {
        inputItems[i].checked = false;
    }
}

function validaMawb(){

var d = document.getElementsByName('DS_MD' + idMaster).value();
var m = document.getElementById('idMAWB').value;

if(d.value !== m.value){
    uncheckAll(inputs);
    document.getElementsByName('DS_MD' + idMaster).value = null;
    $("#formSelectMAWB").find("#masterDireto").val(null);

}}

                        <input type="radio" name="idMAWB" id="idMAWB" value="<%=ID_CD_MAWB%>" onClick="selecionaMAWB(this.value);">
                        <%=DS_MAWB%>

                    <label for="DS_MD<%=ID_CD_MAWB%>">
                    <input type="checkbox" name="DS_MD<%=ID_CD_MAWB%>" id="masterDireto<%=ID_CD_MAWB%>" onClick="testaCheck(<%=ID_CD_MAWB%>);validaMawb();">
                      Master Direto

Comment: Não pode repetir id's, senão irá pegar sempre o primeiro.
Comment: Então aonde eu tenho o script do validaMawb eu teria de usar outro meio para chamar as variáveis de comparação?
Comment: Qual é a div que se repete?
Comment: A `` que é a terceira div sempre se repete por ser parte da construção da listagem.
Comment: Teria que usar outro meio. Mas o seu código está todo errado. Tem que refazer ele quase todo, ao meu ver.
Comment: Entendi Sam, se puder me dar um rumo por onde começar ou algum lugar para estudar melhor agradeço, estou iniciando em js
Answer: Depois de refazer o código, consegui o que necessitava com este tópico, caso alguém necessite segue abaixo o código funcional.
function testaCheck(idMaster) {
    var inputs, i, checados = 0;
    var idmasterOption = $("#formSelectMAWB").find("#idMAWB").val();
    inputs = document.getElementsByTagName("input");
    for (i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "checkbox") {
            if (inputs[i].checked == true) {
                if (idMaster != idmasterOption) {
                     uncheckAll(inputs);
                    $("#formSelectMAWB").find("#masterDireto").val(null);
                    $("#formSelectMAWB").find("#idMAWB").val(null);
                        if ( valor != null){
                            $("#formSelectMAWB").find("#idMAWB").val(null);
                        }
                    }
                else {
                    document.getElementsByName('DS_MD' + idMaster).value = idMaster;
                    $("#formSelectMAWB").find("#masterDireto").val(idMaster);
                    }
                    checados++;
            }
        }
    }
    if (checados > 1) {
                uncheckAll(inputs);
                $("#formSelectMAWB").find("#masterDireto").val(null);
                $("#formSelectMAWB").find("#idMAWB").val(null);
            }
};

function uncheckAll(inputItems){
    alert("MAWB não selecionado ou MAWB diferente do Direto. Favor refazer a seleção");
    for (i = 0; i < inputItems.length; i++) {
        inputItems[i].checked = false;
    }
}


SHA-2 with TLS below 1.1 or lower

Question: I have a call to a 3rd party webservice that uses HTTPs for transport security.
The 3rd party are due to upgrade their certificate to SHA-2, withdrawing SHA-1.  Does my call need to be able to use TLS1.2 to continue connecting, or can TLS1.1 or below interact with SHA-2 certificates?
Answer: The digital signature of the X.509 certificate has no impact on TLS.  It's the former that is changing from SHA-1 to SHA-256 as part of the SHA-1 deprecation programme.
It is true that TLS has a HMAC within it that use the SHA algorithm and TLS 1.1 does not use SHA-256 for this, but that's completely different to the X.509 certificate with SHA-256 digital signatures which your 3rd party will be upgrading to.

SHA-2 with TLS below 1.1 or lower


Transferring SSL certificate to new server


Why do we have different versions of main functions in c++?

Question:
Possible Duplicate:
What is the difference between _tmain() and main() in C++?

How the void main(...), int main(..) and int _tmain() differs. They all are single entry and single exit systems. But in what situations we use these start-up functions?
Comment: http://stackoverflow.com/questions/895827/what-is-the-difference-between-tmain-and-main-in-c
Comment: `void main()` was *never* valid C++.
Comment: `void main()` has also never been valid C (except that an implementation may support it as an extension). The same standard (the 1989 ANSI C standard) that introduced the `void` keyword defined the two valid forms: `int main(void)` and `int main(int argc, char *argv[])` or equivalent. Certain book authors invented the false idea that `void main()` is valid; I'd like to know why.
Comment: AFAIK _tmain is Microsoft specific...
Comment: And `void main()` is very old C++.
Comment: http://stackoverflow.com/questions/895827/what-is-the-difference-between-tmain-and-main-in-c
Comment: @Keith: I assume that they had previously been writing `main` functions with implicit-int return value, that fell off the end of the function instead of returning a defined value. At some point their compiler complained about a non-void function not returning a value, and the laziest possible way to "fix" that was to change `main` to return `void`, disregarding that it's still not valid. I believe that a common implementation detail to support both required forms of `main` is just to not check the signature of `main` at all.
Comment: @SteveJessop: Would it have been enough to just add int? As the standard explicitly mentions that the return statement is not necessary => return 0 [§220.127.116.11]
Comment: @MFH: the C99 standard says that, but we're talking about the era of the C89 standardization.
Answer: void main() is invalid; the C++ standard requires main to return int. Some compilers let you get away with it.
int main() is one of the two standard forms. The other is int main(int argc, char *argv[]), which can be used to receive command-line arguments. Implementations may permit other forms, but are not required to -- but all such forms must return int.
int _tmain() is specific to Microsoft.
Comment: nm. you're totally right. 3.6.1 p2
Comment: [N3337](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf) section 3.6.1 [basic.start.main]; `int main(int argc)` is not one of the required forms.
Answer: The reason why different implementations support different entry points (or choices of entry points) is that different OSes or environments have different ways of running programs, or different ways of passing argument information into the program.
There are two kinds of C++ implementation:
"hosted" implementations assume the existence of some kind of OS. On hosted implementations, main is required in conforming programs and must return int.
"freestanding" implementations don't assume the existence of an OS. On freestanding implementations it's up to the implementation whether to require main or not, but the standard does still say that if main is required then it must return int.
It's common practice for implementations to provide the facilities of a hosted implementation, but to allow entry points other than main. This conforms to the standard for a hosted implementation, provided that a conforming program that does define main is accepted. In effect the implementation allows (as an extension) certain non-conforming programs with no main function provided they contain instead the implementation-defined alternative. Technically I think it must diagnose the "error", but in practice nobody would use such an extension by accident, so they probably don't want to see a diagnostic.
Similarly, a conforming implementation can accept a program containing void main. Again, for the implementation to conform it must diagnose that the program doesn't conform.
The meaning of a non-conforming program that the implementation accepts anyway, is up to the implementation.
_tmain is a MS extension. It is an alias for main in narrow-character builds and wmain in wide-character builds. wmain is also a MS extension, it's like main except that argv are provided as wide strings instead of narrow strings. So this is an example of an environment where there are two different ways to give arguments to programs, depending whether or not the program handles characters outside the range of narrow characters (i.e. outside the 8-bit code page).


How does one write boldface characters on paper or a chalkboard?

Question: This is a soft question.
Context: In mathematics, one often writes in boldface to signify certain mathematical objects. For example, we might write $c$ to signify a real number, and yet write $\mathbf{c}$ to signify a column vector of real numbers.
The problem is that it is hard to write $\mathbf{c}$ on paper or a chalkboard/whiteboard; writing $\mathbf{c}$ on paper just looks like writing $c$.
Of course, we never run into this problem on math.stackexchange because we write in latex.
Question: Is there some widely held convention in the mathematics community that allows one to signify bold letters when writing on paper (or chalkboard/whiteboard)? Underlining? Underlining twice, or some such practice?
Comment: When I write vectors by hand (and only when I need to distinguish them from scalars) I fall back to the old-school $\vec c$ notation.
Comment: While writing on a board, you choose your own notation, so there is never any need to use bold (though the blackboard font is meant to replicate it).
Comment: The slightly cheeky answer is to use bigger chalk.  I had a prof who always wrote with sidewalk chalk on the chalkboard... certainly looked much bolder than traditional "small" chalk.
Answer: The standard marking, in the sense of standard proof correction marks, for boldface is to underline with a wavy line. (A straight underline is for italic, and underlining twice  is for small caps.)
While this is standard in a way I doubt this is all that widely known nowadays (I'll confess I had to look it up to recall which type of line it was).
There is also the font-family called blackboard bold that you surely know $\mathbb{A,B,C,N,Z,Q,R}$ hinting at another way to write bold on the blackboard, namely draw some lines twice.
For practical purposes, I suggest to do whatever works well for you. Likely underlining with a straight line is preferable to the 'standard' wavy line in this context, as likely you will not have the need to also signal italic.


non-disjoint permutations

Question: So, since apparently every calculator I encounter to check my answer does not help with joint cycles, I came humbly to ask if I did this correctly.
$\alpha$ = (1, 3, 2, 5)(6, 4, 7, 3) y $\beta$ = (3, 6, 5, 2)(1, 4, 7, 3)
So, they ask for these: $α$, $\beta$, $α^2$, $α^2$$β$,
Here are my answers:

Writing it as disjoint cycles:

$\alpha$ = (1 3 6 4 7 2 5)
$\beta$ = (1 4 7 6 5 2 3)

Then operating:

$\alpha^2$ = (6 1 4 2 3 7 6)
$α^2$$β$ = (2 4 6 5 1 3 7)

Hopefully I did this right.
Comment: $\alpha$ and $\beta$ look fine, but the rest is strange. How did you calculate $\alpha^2$? (The simple way to do it would be to read off every second element, wrapping around as necessary.)
Comment: @hardmath I'm puzzled because whatever process was used to get $\alpha$ doesn't seem to have been used to get $\alpha^2$.
Comment: @chrisoname:  The opposite of "disjoint cycles" is not "joint cycles".  I'd be inclined to use "non-disjoint cycles" to describe your compositions.
Comment: Do you compose (multiply) permutations left-to-right [e.g. $(1,2)(1,3)=(1,2,3)$]; or do you compose them right-to-left [e.g. $(1,2)(1,3)=(1,3,2)$]?
Comment: @Théophile:  Many authors compose permutations from left to right.  If the OP is correct about $\alpha$, it means these cycles are composed right to left.  You are correct about the simple way to calculate $\alpha^2$.
Comment: I did:

1 -> 3 -> 6
2 -> 5 -> 1
3 -> 6 -> 4
4 -> 7 -> 2
5 -> 1 -> 3
6 -> 4 -> 7
Comment: @Théophile right to left I was taught. like functions.
Comment: I see. That makes sense; you just wrote down the result strangely. See my answer for details.
Answer: You're confusing two different notations. There is a long way to describe a permutation and a short way. The long way list which element maps to which:
$$\sigma = \begin{pmatrix}
1 & 2 & 3 & 4 \\
1 & 4 & 2 & 3 \\
\end{pmatrix}$$
Here we have $1$ as a fixed element, while $\sigma(2)=4, \sigma(3)=2$, and $\sigma(4)=3$.
The short way is to write out cycles; the same permutation can be written
$$\sigma = (1)(2 4 3)$$
showing that $1$ is fixed, while we have $2 \to 4 \to 3 \to 2$.
In your answer for $\alpha^2$ and $\alpha^2\beta$, you've written out the bottom row of the long notation, which doesn't make sense when read as cycle notation.
Comment: @chrisoname Yes, exactly. This is $\alpha^2$. The cycle notation would be $(1675342)$.
Comment: Perfect! So I'm in the right track. Thank you very much. Hopefully I can do harder problems now and with better understanding of the difference in notations.
Comment: $$\alpha^2 = \begin{pmatrix}
1 & 2 & 3 & 4 & 5 & 6 & 7 \\
6 & 1 & 4 & 2 & 3 & 7 & 5 \\
\end{pmatrix}$$

is this what you mean?

non-disjoint permutations