text:
Q: get the key of Firebase Recycler view holder for deleting specific post on long click i had a recycler view holder which consist of comments for a post,i need to delete the comment on long press, but for that i need the key of that comment at the position.
In my bindview holder i have the code like below but it is showing me error on getref() method that cannot reslove method getref(int)
       @Override
       public void onBindViewHolder(final CommentViewHolder holder, final int position) {

        final Comm comment = mComments.get(position);

        final DatabaseReference postRef = getRef(position);
        final String postKey = postRef.getKey();

if I get the post key I can delete the comment.How can i get key of that specific comment?

A: The idea is you have to make a callback from adapter to calling fragment/activity and remove the comment from list and call notifyDataSetChange() on your adapter.
The callback will have an int position as the parameter which can be used to get the object at given position and remove from list.
//your constructor for adapter

  private OnClickViewItemListener mItemListener;
     private List<Comm> listData;
        public YourAdapter(List<Comm> listData, OnClickViewItemListener mItemListener) {
            this.listData = listData;
            this.mContext = mContext;
            this.mItemListener = mItemListener;
        }

Your adapter viewholder should have following changes.
 public CommentViewHolder(View itemView) {
        super(itemView);
        mButton = (Button)itemView.findViewById(R.id.btDelete);
        mButton.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(final View v) {
                mItemListener.onClickViewItem(v,getAdapterPosition());
                return false;
            }
        });
    }

now implement OnClickViewItemListener in your activity or fragment and do what ever you want.
 @Override
    public void onClickViewItem(View view, int position) {
        //here handle the item click listener
        // remove the comment here and notify adapter
       commList.remove(position);

    }


text:
Q: ¿Cómo puedo solucionar este problema con expresiones regulares en golang? Hola a todos les pido ayuda ya que estoy teniendo un problema en golang que no se como resolver, estoy usando expresiones regulares para analizar el contenido de un archivo, y estoy buscando el patron "{{ ... }}" (donde puse "..." va cualquier valor, solo busco "{{", "}}", y el contenido dentro de las llaves) Lo que quiero hacer con este patron es tener todos los resultados que hayan en una linea, si solo hay una coincidencia no hay problema y funciona como espero, pero lo malo es cuando hay mas de una coincidencia. Ejemplo, si uso este texto:
Lorem ipsum {{ texto1 }} dolor sit amet, consectetur {{ texto2 }} adipiscing elit

Lo que me gustaria hacer es tener como resultado que me devuelva lo que esta dentro de texto1 y lo que esta dentro de texto2 pero por separado, pero en su lugar lo que hace es que me devuelve todo lo que esta desde texto1 hasta texto2 y no dentro de, por lo que de resultado tengo:
{{ texto1 }} dolor sit amet, consectetur {{ texto2 }}

Y no:
{{ texto1 }},  {{ texto2 }}

Ahora que he intentado explicar lo que quiero hacer, aqui esta mi codigo:
package main

import (
  "regexp"
  "log"
)

func main() {
    re := regexp.MustCompile("{{.*}}")

    buscar := re.FindAllStringSubmatch("Lorem ipsum {{ texto1 }} dolor sit amet, consectetur {{ texto2 }} adipiscing elit", -1)

    log.Print(validLine)

}

Espero que me puedan ayudar y espero haberme explicado bien, desde ya gracias :).

A: Buen día,
Al trabajar con regex hay una función llamada "codicioso" (En inglés greedy) que en caso de haber múltiples coincidencias lo que hace es tomar todo lo que haya desde la primera coincidencia hasta la última.
En tu caso lo que hay que hacer es hacerlo "no codicioso" o también llamado "perezoso" (En inglés non-greedy) para que busque cada grupo por separado. Para eso utilizamos el signo de interrogación ?.
Hay una página que yo utilizo para probar los regex que es múy útil ya que a la derecha te explica como funciona lo que estás haciendo, se llama regex101.
Conclusión:
Para poder obtener únicamente los grupos puedes utilizar el siguiente regex:
{{.*?}}

Si quisieras obtener únicamente lo que está adentro de las llaves entonces hay que agregar paréntesis:
{{(.*?)}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Optimisation of finding all 3 integers add up to zero Given in an array n, I want to find all the distinct a, b, c elements such that a+b+c=0. For instance, imagine
n = [-1, 0, 1, 2, -1, -4]

result should be
[ [-1, 0, 1], [-1, -1, 2] ]

I came up with the following algorithm, which I think gives the complexity of O(n^2). My question is, can we make it more efficient computationally?
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Set<List<Integer>> collection = new HashSet<List<Integer>>();

        Arrays.sort(nums);

        int leadingPointer, tailPointer, container;
        for(int i=0; i<nums.length-2; i++){
            leadingPointer = i+1;
            tailPointer = nums.length-1;
            while(leadingPointer<tailPointer){
                container = nums[i] + nums[leadingPointer] + nums[tailPointer];
                if(container == 0){
                     collection.add(new ArrayList<Integer> (Arrays.asList(
                            nums[i],
                            nums[leadingPointer],
                            nums[tailPointer]
                    )));
                    tailPointer--;
                    leadingPointer++;
                } else if(container > 0){
                    tailPointer--;
                } else{
                    leadingPointer++;
                }
            }
        }

        List<List<Integer>> finalResult = new ArrayList<List<Integer>>();
        finalResult.addAll(collection);

        return finalResult;
    }
}

A: Using nested loops, use each element of the set N as a . Now use each element of the set N excluding a as b. Now check if the set N excluding a and b contains the value -a - b if so add [a, b, -a -b] to the answer set. You may want to remove duplicates from the answer set if the question is to find distinct possibilities.


text:
Q: How to display Recent view product in Django? I am new to Django, and I am looking for this answer. Please let me know how I can solve this issue. Suppose, if a user visits on my website and he clicks on any product then that product should be shown in recent view on his PC/Laptop, suppose if a user exit from website and after 2-3 hours he/she visit again then previous views product should be shown in his recent viewed product. and I want to do this without logging in a user, please let me know how I can do it.
if anybody has code for this please submit here or explain the process.

A: There is nothing inbuilt function like you want but you can apple your own logic you have to made store user visited product in one sprat data base model with (auto_new_add=TRUE)this will add time and data automatically and right following logic after the login event that bring that story data bake(use time and date to identify resent visited product)
x = visted.objects.filter(time=time)


text:
Q: Why does ErrorCollector demands for assignment at the moment of declaration? Checkinging many XML strings, I use the ErrorCollector construction frequently. But still I do not understand how it works.
When I am declaring an ErrorCollector, I have to assign it at once:
@Rule
public ErrorCollector collector= new ErrorCollector();

If I want to refresh the collector before every test, I am putting an assignment
collector= new ErrorCollector();

in the @Before method. But thus the first assignment at the declaration is excessive. But I can't remove it.
What is the sense of this must-to-be-assignment? And how it works? I thought, that @Rule is about the declaration only?
@Matthew Farwell at What is the logic of @Rule(JUnit) declaration and assignment in a Groovy class says "In Java, the JUnit runner checks that the @Rule annotation is applied to a public non-static field or public non-static method which returns either a TestRule or MethodRule." But what is checked here is not the declaration, but the assignment and it is something that happens afterwards, after both building and test construction ?

A: As with most / all @Rules in JUnit, they are refreshed or cleared before each test automatically. So you just declare it as a @Rule as you have listed above. You DO NOT need to do anything to it in your @Before method. We way to think of it is that JUnit will invoke the ErrorCollector before and after each test. Before each test the ErrorCollector can initialize itself (clearing any previously stored errors). After each test, if an error has been collected it reports the error(s).
Here is the source for ErrorCollector
From Comment:
It must be assigned because JUnit must have an instance of the rule to work with. Otherwise the object would be null. Remember that the JUnit code is using reflection to get the instance of the Object with the @Rule annotation and using instanceof to determine if it is a TestRule or MethodRule. I believe the @Before method is called within the Statement and therefore after the Rule is invoked
FROM MatthewFarwell:
When you run a JUnit test, for example, FooTest, then the runner will create an instance of FooTest for each test method. So if you're using public ErrorCollector collector= new ErrorCollector(); as above, then this gets naturally re-instantiated once per test method.
Conclusing: Make sure that you don't save state between your tests! Of course you shouldn't have done that anyway since order is not guaranteed.
Thanks Matt!


text:
Q: How to paste HTML into a CS class My ASP.NET MVC app sends an email to users once they have created an inventory along with the PDF file for them to download. I have created a HTML form so people dont get just a bad looking text but a nice email.
I have tried pasting the html where I put ("here") in the following string
var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, to, subject, "Correo generado por Elyssa, se ha generado un inventario.", "("here")");
So far I am getting +99 errors in the console and I dont really know whats going on, any help would be very much appreciated.

A: Try putting an @ before the string, it will instruct the compiler to interpret the string literally. My best guess is that the compiler is assuming you have character escape sequences and is 'busting up' your HTML string.


text:
Q: How would I go about having a chat update after loading? I've tried searching on here for a bit to try and find someone with a similar question. I haven't quite yet gotten into implementing the actual retrieval and insertion into the database for the chat messages but I would like to know ahead of time what I'll need to do. You see, on several websites there is updates done to the page after its already been loaded, such as with chat rooms where you're actively given new messages after the page has already loaded. I'm really just posting this as a quick question to see whether this is done through forcing all clients to reload when a new message is posted or what. I would also like to know, if this is done a different way, what language relates to it so I can learn it ahead of time. Thank you.

A: There are various ways you can do it.
One of the more common is to use a websocket server like Socket.io, which maintains a realtime connection between each web client and the server. The realtime server pushes whatever updates you send to the clients.
You can achieve a similar effect using Service Workers and the native browser Push API, as demonstrated here.
You could also just set an interval timer to ping a server for updates every second, but that is less efficient and performant.


text:
Q: Linux doesn't boot after update-grub I had a problem with my HDMI without sound and I found this fix.
Edit /etc/default/grub and change this line:

GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

to this line

GRUB_CMDLINE_LINUX_DEFAULT="quiet splash radeon.audio=1"

Now run "sudo update-grub", then reboot your computer.

Now, the boot stuck in a file systems check. Each time it's stucked in a different message. Sometimes, about bluetooth, others for network monitor etc. I cannot open Linux from recovery and from older versions, each one stuck in a black screen.
I cannot access my pc and if I will not find a sollution soon, I will turn to a clean install with losing all my data :(

A: If you can access the grub (as can be read in the comments), just press E look for the line starting with linux and ending in quiet splash radeon.audio=1, like this:
linux   /vmlinuz-3.13-1-amd64 root=UUID=cead26d6-08f4-4894-ac78-a9a4ce59f773 ro initrd=/install/initrd.gz quiet splash radeon.audio=1

and remove the offending parameter. Press Ctrl + X to boot the system. After that, just editing the /etc/default/grub and running update-grub should be a permanent fix (or reversion) of whatever you have done.


text:
Q: JVM metrics for java application running on EC2 I have a use case to monitor the JVM metrics like(heap size,garbage collection etc) when my JAVA application is running .My application is running on EC2.
can you help me how JCONSOLE be used in EC2,or any other open source or will cloud watch help in doing this when my appication is running
Thanks

A: You can use AWS CloudWatch metrics to have monitoring of the instance. You can use Datadog services to have extra monitoring. You can use this document as a reference for datadog JMX integration.
If not, you can install JMX Directly on your EC2 instance


text:
Q: Some questions on shape creation I am digging into shapes and found some questions which were hard to find an answer. Hope you can help me:
1 - What is the meaning of shape="0" ?
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="0"
>

2 - Why setting so precise value of corners? Is there some tool maybe that converts shapes into XML and that's the reason for such precision?
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="0"
    >
    <gradient
    ...
    >
    <corners
        android:topLeftRadius="0.100000024dip"
        android:topRightRadius="0.100000024dip"
        android:bottomLeftRadius="10.0dip"
        android:bottomRightRadius="10.0dip"
        >
    </corners>
</shape>

3 - What is the best radius for background gradient? I saw some people use 300-and-something value.
Thanks

A: More or less complete info on shapes is here

*

*I suppose 0 means default value("rectangle")

*There's no need in such precision. You can even use non-float values(10dip equals 10.0dip)

*"The best value" always depends on the task. Try and see for yourself.

A: Where are you getting that sample code?  It looks crazy!  Here is the documentation on ShapeDrawables.  The android:shape tells Android what kind of shape it is.  The choices are "rectangle", "oval", "line" and "ring".  The corner radius is in what ever units you specify.  In the example you show it's in Density Independent Pixels which means it should look the same on all devices, but still, 0.100000024 pixels doesn't make much sense anywhere!  The radius of the gradient depends on what look you're going for.  If you want it to fill the screen, or overflow the edge or just be in one corner.


text: Q: Вставить Яндекс карту в Ворд документ С PHP получается создать Ворд документ. Создаётся после обработки Excel файла. В файле есть поле адреса. Из этого адреса нужно сделать фото яндекс карты и вставить в файл. Это возможно?


text:
Q: Does sbf() use metric argument to optimize model? Passing ROC as metric argument value to the caretSBF function
Our objective is to use the ROC summary metric for model selection while running the Selection By Filtering sbf() function for features selection.
The BreastCancer dataset was used as a reproducible example from mlbench package to run train() and sbf() with metric = "Accuracy" and metric = "ROC"
We want to make sure sbf() takes the metric argument as applied by the train() and rfe() functions to optimize the model. To this aim, we planned to make use of the train() function with the sbf() function.  The caretSBF$fit function makes a call to train(), and caretSBF is passed to sbfControl.
From the output, it seems the metric argument is used just for inner resampling and not for the sbf part, i.e. for the outer resampling of the output, the metric argument was not applied as used by train() and rfe().
As we have used caretSBF which uses train(), it appears that the metric argument is limited in scope to train() and hence is not passed to sbf.
We would appreciate clarification on whether sbf() uses metric argument for optimizing model, i.e. for outer resampling?
Here is our work on reproducible example, showing train() uses metric argument using Accuracy and ROC, but for sbf we are not sure.
I. DATA SECTION
  ## Loading required packages
  library(mlbench)
  library(caret)

  ## Loading `BreastCancer` Dataset from *mlbench* package
  data("BreastCancer")

  ## Data cleaning for missing values
  # Remove rows/observation with NA Values in any of the columns
  BrC1 <- BreastCancer[complete.cases(BreastCancer),]

  # Removing Class and Id Column and keeping just Numeric Predictors
  Num_Pred <- BrC1[,2:10]

II. CUSTOMIZED SUMMARY FUNCTION
Defining fiveStats summary function
  fiveStats <- function(...) c(twoClassSummary(...),
                         defaultSummary(...))

III. TRAIN SECTION
Defining trControl
  trCtrl <- trainControl(method="repeatedcv", number=10,
  repeats=1, classProbs = TRUE, summaryFunction = fiveStats)

TRAIN + METRIC = "Accuracy"
   set.seed(1)
   TR_acc <- train(Num_Pred,BrC1$Class, method="rf",metric="Accuracy",
   trControl = trCtrl,tuneGrid=expand.grid(.mtry=c(2,3,4,5)))

   TR_acc
   # Random Forest
   #
   # 683 samples
   #   9 predictor
   #   2 classes: 'benign', 'malignant'
   #
   # No pre-processing
   # Resampling: Cross-Validated (10 fold, repeated 1 times)
   # Summary of sample sizes: 615, 615, 614, 614, 614, 615, ...
   # Resampling results across tuning parameters:
   #
   #   mtry  ROC        Sens       Spec       Accuracy   Kappa
   #   2     0.9936532  0.9729798  0.9833333  0.9765772  0.9490311
   #   3     0.9936544  0.9729293  0.9791667  0.9750853  0.9457534
   #   4     0.9929957  0.9684343  0.9750000  0.9706948  0.9361373
   #   5     0.9922907  0.9684343  0.9666667  0.9677536  0.9295782
   #
   # Accuracy was used to select the optimal model using  the largest value.
   # The final value used for the model was mtry = 2.

TRAIN + METRIC = "ROC"
   set.seed(1)
   TR_roc <- train(Num_Pred,BrC1$Class, method="rf",metric="ROC",
   trControl = trCtrl,tuneGrid=expand.grid(.mtry=c(2,3,4,5)))
   TR_roc
   # Random Forest
   #
   # 683 samples
   #   9 predictor
   #   2 classes: 'benign', 'malignant'
   #
   # No pre-processing
   # Resampling: Cross-Validated (10 fold, repeated 1 times)
   # Summary of sample sizes: 615, 615, 614, 614, 614, 615, ...
   # Resampling results across tuning parameters:
   #
   #   mtry  ROC        Sens       Spec       Accuracy   Kappa
   #   2     0.9936532  0.9729798  0.9833333  0.9765772  0.9490311
   #   3     0.9936544  0.9729293  0.9791667  0.9750853  0.9457534
   #   4     0.9929957  0.9684343  0.9750000  0.9706948  0.9361373
   #   5     0.9922907  0.9684343  0.9666667  0.9677536  0.9295782
   #
   # ROC was used to select the optimal model using  the largest value.
   # The final value used for the model was mtry = 3.

IV. EDITING caretSBF
Editing caretSBF summary Function
   caretSBF$summary <- fiveStats

V. SBF SECTION
Defining sbfControl
   sbfCtrl <- sbfControl(functions=caretSBF,
   method="repeatedcv", number=10, repeats=1,
   verbose=T, saveDetails = T)

SBF + METRIC = "Accuracy"
   set.seed(1)
   sbf_acc <- sbf(Num_Pred, BrC1$Class,
   sbfControl = sbfCtrl,
   trControl = trCtrl, method="rf", metric="Accuracy")

   ## sbf_acc
   sbf_acc

   # Selection By Filter
   #
   # Outer resampling method: Cross-Validated (10 fold, repeated 1 times)
   #
   # Resampling performance:
   #
   #     ROC  Sens   Spec Accuracy Kappa    ROCSD SensSD  SpecSD AccuracySD  KappaSD
   #  0.9931 0.973 0.9833   0.9766 0.949 0.006272 0.0231 0.02913    0.01226 0.02646
   #
   # Using the training set, 9 variables were selected:
   #    Cl.thickness, Cell.size, Cell.shape, Marg.adhesion, Epith.c.size...
   #
   # During resampling, the top 5 selected variables (out of a possible 9):
   #    Bare.nuclei (100%), Bl.cromatin (100%), Cell.shape (100%), Cell.size (100%), Cl.thickness (100%)
   #
   # On average, 9 variables were selected (min = 9, max = 9)

   ## Class of sbf_acc
   class(sbf_acc)
   # [1] "sbf"

   ## Names of elements of sbf_acc
   names(sbf_acc)
   #  [1] "pred"         "variables"    "results"      "fit"          "optVariables"
   #  [6] "call"         "control"      "resample"     "metrics"      "times"
   # [11] "resampledCM"  "obsLevels"    "dots"

   ## sbf_acc fit element*
   sbf_acc$fit
   # Random Forest
   #
   # 683 samples
   #   9 predictor
   #   2 classes: 'benign', 'malignant'
   #
   # No pre-processing
   # Resampling: Cross-Validated (10 fold, repeated 1 times)
   # Summary of sample sizes: 615, 614, 614, 615, 615, 615, ...
   # Resampling results across tuning parameters:
   #
   #   mtry  ROC        Sens       Spec       Accuracy   Kappa
   #   2     0.9933176  0.9706566  0.9833333  0.9751492  0.9460717
   #   5     0.9920034  0.9662121  0.9791667  0.9707801  0.9363708
   #   9     0.9914825  0.9684343  0.9708333  0.9693308  0.9327662
   #
   # Accuracy was used to select the optimal model using  the largest value.
   # The final value used for the model was mtry = 2.

   ##  Elements of sbf_acc fit
   names(sbf_acc$fit)
   #  [1] "method"       "modelInfo"    "modelType"    "results"      "pred"
   #  [6] "bestTune"     "call"         "dots"         "metric"       "control"
   # [11] "finalModel"   "preProcess"   "trainingData" "resample"     "resampledCM"
   # [16] "perfNames"    "maximize"     "yLimits"      "times"        "levels"

   ## sbf_acc fit final Model
   sbf_acc$fit$finalModel

   # Call:
   #  randomForest(x = x, y = y, mtry = param$mtry)
   #                Type of random forest: classification
   #                      Number of trees: 500
   # No. of variables tried at each split: 2
   #
   #         OOB estimate of  error rate: 2.34%
   # Confusion matrix:
   #           benign malignant class.error
   # benign       431        13  0.02927928
   # malignant      3       236  0.01255230

   ## sbf_acc metric
   sbf_acc$fit$metric
   # [1] "Accuracy"

   ## sbf_acc fit best Tune*
   sbf_acc$fit$bestTune
   #   mtry
   # 1    2

SBF + METRIC = "ROC"
   set.seed(1)
   sbf_roc <- sbf(Num_Pred, BrC1$Class,
   sbfControl = sbfCtrl,
   trControl = trCtrl, method="rf", metric="ROC")

   ## sbf_roc
   sbf_roc

   # Selection By Filter
   #
   # Outer resampling method: Cross-Validated (10 fold, repeated 1 times)
   #
   # Resampling performance:
   #
   #     ROC  Sens   Spec Accuracy Kappa    ROCSD SensSD  SpecSD AccuracySD KappaSD
   #  0.9931 0.973 0.9833   0.9766 0.949 0.006272 0.0231 0.02913    0.01226 0.02646
   #
   # Using the training set, 9 variables were selected:
   #    Cl.thickness, Cell.size, Cell.shape, Marg.adhesion, Epith.c.size...
   #
   # During resampling, the top 5 selected variables (out of a possible 9):
   #    Bare.nuclei (100%), Bl.cromatin (100%), Cell.shape (100%), Cell.size (100%), Cl.thickness (100%)
   #
   # On average, 9 variables were selected (min = 9, max = 9)

   ## Class of sbf_roc
   class(sbf_roc)
   # [1] "sbf"

   ## Names of elements of sbf_roc
   names(sbf_roc)
   #  [1] "pred"         "variables"    "results"      "fit"          "optVariables"
   #  [6] "call"         "control"      "resample"     "metrics"      "times"
   # [11] "resampledCM"  "obsLevels"    "dots"

   ## sbf_roc fit element*
   sbf_roc$fit
   # Random Forest
   #
   # 683 samples
   #   9 predictor
   #   2 classes: 'benign', 'malignant'
   #
   # No pre-processing
   # Resampling: Cross-Validated (10 fold, repeated 1 times)
   # Summary of sample sizes: 615, 614, 614, 615, 615, 615, ...
   # Resampling results across tuning parameters:
   #
   #   mtry  ROC        Sens       Spec       Accuracy   Kappa
   #   2     0.9933176  0.9706566  0.9833333  0.9751492  0.9460717
   #   5     0.9920034  0.9662121  0.9791667  0.9707801  0.9363708
   #   9     0.9914825  0.9684343  0.9708333  0.9693308  0.9327662
   #
   # ROC was used to select the optimal model using  the largest value.
   # The final value used for the model was mtry = 2.

   ##  Elements of sbf_roc fit
   names(sbf_roc$fit)
   #  [1] "method"       "modelInfo"    "modelType"    "results"      "pred"
   #  [6] "bestTune"     "call"         "dots"         "metric"       "control"
   # [11] "finalModel"   "preProcess"   "trainingData" "resample"      "resampledCM"
   # [16] "perfNames"    "maximize"     "yLimits"      "times"        "levels"

   ## sbf_roc fit final Model
   sbf_roc$fit$finalModel

   # Call:
   #  randomForest(x = x, y = y, mtry = param$mtry)
   #                Type of random forest: classification
   #                      Number of trees: 500
   # No. of variables tried at each split: 2
   #
   #         OOB estimate of  error rate: 2.34%
   # Confusion matrix:
   #           benign malignant class.error
   # benign       431        13  0.02927928
   # malignant      3       236  0.01255230

   ## sbf_roc metric
   sbf_roc$fit$metric
   # [1] "ROC"

   ## sbf_roc fit best Tune
   sbf_roc$fit$bestTune
   #   mtry
   # 1    2

Does sbf() use metric argument to optimize model?  If yes, what metric does sbf() use as default? If sbf() uses metric argument, then how to set it to ROC?
Thanks.

A: sbf doesn't use the metric to optimize anything (unlike rfe); all sbf does is do a feature selection step before calling the model. Of course, you define the filters but there is no way to tune the filter using sbf so no metric is needed to guide that step.
Using sbf(x, y, metric = "ROC") will pass metric = "ROC" to whatever modeling function that you are using (and it designed to work with train when caretSBF is used. This happens because there is no metric argument to sbf:
> names(formals(caret:::sbf.default))
[1] "x"          "y"          "sbfControl" "..."


text:
Q: sql server analysis studio predicthistogram sort on adjustedprobability column I'm using SQL Server Analysis Studio 2008 to query a Naive Bayes classification model. I'm using PredictHistogram so it returns a nice table of support, probabilities, etc., however I want the returned data to be sorted by AdjustedProbability and not any other the other columns.
Does anyone know syntactically how to adjust my query below? I've tried several things but it's not happy in SQL Server Management Studio. Thanks,
mj
select predicthistogram([bayes].[code]) from [bayes]
natural prediction join
  (select
    (select 'michael' as [name]) as [name_table]
  ) as t

A: I figured it out.
select topcount(predicthistogram([bayes].[code]), $adjustedprobability, 10) from [bayes]
natural prediction join
  (select
    (select 'michael' as [name]) as [name_table]
  ) as t

TopCount is necessary to sort everything coming back from a predicthistogram call.


text:
Q: In tealium, is it possible to fire a tag based on a url? At work we are getting ready to convert from Google Tag Manager to Tealium.  In GTM, I know I'm able to fire tags based on a url.
Example: If I have a url such as www.mycompany.com/product1, I know I can make a tag that will parse the url and fire on product1.
Is something like this possible with Tealium?

A: Yes, such functionality is possible in Tealium through the use of a Load Rule. There are various built-in variables in the Data Layer that you can use for this such as "url", "pathname", and "domain". You would simply create a load rule to specify these data layer values on the left, type the values to match on in the right and specify how to evaluate the comparison (e.g. contains, equals, does not equal, etc.).
This load rule would be mapped to a tag you've created and if you had custom logic you wished to add, best practices would be to create an extension that's scoped to that tag and add your logic there.


text:
Q: ParseException line 5:19 cannot recognize input near 'SELECT' 'MIN' '(' in expression specification (state=42000,code=40000) I am running below query on hive
SELECT
  a.NDC,
  a.filetag,
  b.filetag AS filetag_RMIID1,
  a.medid,
  b.MED_REF_FED_LEGEND_IND,
  b.MED_MEDID_DESC
FROM
  TMPTBL_RMINDC1_MERGED_SORTED_ND a
  INNER JOIN TMPTBL_RMIID1_MERGED_SORTED_ND b ON a.medid = b.medid
WHERE
  b.filetag = (SELECT MIN(c.filetag) FROM TMPTBL_RMIID1_MERGED_SORTED_ND c WHERE c.medid = a.medid AND c.filetag >= a.filetag)

and getting below error
Error: Error while compiling statement: FAILED: ParseException line
5:19 cannot recognize input near 'SELECT' 'MIN' '(' in expression
specification (state=42000,code=40000)

please help me on this.

A: Hive supports only IN/NOT IN, EXISTS/NOT EXISTS in where clause sub query. In your query replace where condition with below and it should work:
b.filetag in (SELECT MIN(c.filetag) FROM TMPTBL_RMIID1_MERGED_SORTED_ND c
WHERE c.medid = a.medid AND c.filetag >= a.filetag)

More details on hive subquery support can be found here:
Hive Subqueries


text:
Q: Error 'declares a non-template function' in C++ I compile a project with make command but this give me these errors:
g++ -std=gnu++11 -c Array.cc
In file included from Array.cc:5:0:
Array.h:9:65: warning: friend declaration 'std::ostream&    operator<<(std::ostream&, Array<Items>&)' declares a non-template function [-Wnon-template-friend]
friend ostream& operator << (ostream& fout, Array<Items>& ary);
                                                             ^
Array.h:9:65: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)
In file included from Array.cc:9:0:
List.h:28:64: warning: friend declaration 'std::ostream& operator<<(std::ostream&, List<Items>&)' declares a non-template function [-Wnon-template-friend]
friend ostream& operator << (ostream& fout, List<Items>& lst);
                                                            ^
 Array.cc:112:5: error: specializing member 'Array<int>::compare' requires 'template<>' syntax
int Array<int>::compare(Array<int>* ar2)
 ^
Makefile:30: recipe for target 'Array.o' failed
make: *** [Array.o] Error 1

The code in Array.cc is
#include "Array.h"

The code in Array.h:9:65 is:
class Array{
    friend ostream& operator << (ostream& fout, Array<Items>& ary);
  private:
  int theSz;
  int totSz;
  Items *theAry;

Can you explain to me these errors?  I use Ubuntu 15.10.  Maybe these are from deprecated function in C++, because this algorithm was developed in 2005.

A: If your Array class is not meant to be a template, your function should have the signature
friend ostream& operator << (ostream& fout, Array& ary);

Then you can loop over your ary.theAry within that function. Something like
ostream& operator << (ostream& fout, Array& ary)
{
    for (int i = 0; i < ary.theSz; ++i)
    {
        fout << ary.theAry[i] << " ";
    }
}

As written Array<Items>& declares a reference to an Items specialization of the Array class, but your class is not a template, so you cannot pass a template argument.
If your Array class is supposed to be a template, you should declare it as such
template <class Items>
class Array
{
  friend ostream& operator << (ostream& fout, Array& ary);
  private:
  int theSz;
  int totSz;
  Items *theAry;
};


text:
Q: Angular: Make a routerLink inside a routerLink Basically i have a page that is loaded using router link and I want it to have the content change by using router link as well but I don't want to be copying an pasting the html of the topBar and the botBar. Basically a routerLink is used to go to each page and then I want to use it to change its content without always having to copy the HTML of the topBar and botBar.

/*This is the routing for every page there is. The HTML shown is for /douroVinhas*/
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import {HomePageComponent} from './home-page/home-page.component';
import {DouroVinhasComponent} from './douro-vinhas/douro-vinhas.component';
import {AVerOMarComponent} from './a-ver-omar/a-ver-omar.component';
import {MediterraneoComponent} from './mediterraneo/mediterraneo.component';

const routes: Routes = [
  { path: '', redirectTo: '/homePage', pathMatch: 'full' },
  { path: 'homePage', component: HomePageComponent },
  { path: 'douroVinhas', component: DouroVinhasComponent },
  { path: 'aVerOMar', component: AVerOMarComponent },
  { path: 'mediterraneo', component: MediterraneoComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
.hotelPage {
    display: grid;
    grid-template-columns: auto;
    grid-template-rows: 180px auto;
}

.topo {
    grid-row-start: 1;
    grid-row-end: 1;
    text-align: center;
    background-color: black;
}

.logo {
    float: left;
    width: auto;
    color: white;
    max-width: 15%;
    max-height: 100%;
    margin-top: 0.5%;
    z-index: 10;
}

.nomeHotel {
    position: absolute;
    color: white;
    text-shadow: -1px 1px 0 #000, 1px 1px 0 #000, 1px -1px 0 #000, -1px -1px 0 #000;
    z-index: 0;
    left: 40%;
}

.topNav {
    color: white;
    float: right;
    padding-right: 0;
    top: 0;
    text-align: center;
    font-size: 250%;
    text-shadow: -1px 1px 0 #000, 1px 1px 0 #000, 1px -1px 0 #000, -1px -1px 0 #000;
    width: 35%;
    padding-top: 2%;
}

.topNavA {
    padding: 5%;
}

.telefone {
    width: 5%;
    height: 5%;
}

.botBar {
    background-color: black;
    overflow: hidden;
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 5%;
}

.botBar a {
    float: left;
    display: block;
    color: #f2f2f2;
    text-align: center;
    text-decoration: none;
    font-size: 15px;
}

#nrTelefone,
#mail {
    color: white;
}

.icon {
    width: 10%;
}

        <button>Change Content</button>

This is what I want to be loaded using router link, basically this part changes by pressing a button on topNav.

A: Router-outlet allows you to render components loaded by routing.
For more information, you can read it here
You can simply use router-outlet as follows

        <button>Change Content</button>

        <router-outlet></router-outlet>

Also, why do you have angular 1.7 script in your html? Do you use both angularjs and angular together?


text:
Q: Uniquness of convex combination Let $a$ and $b$ be real numbers such that $0<a<b$ and let $x$ be such that $a<x<b$. How can I determine $a_x$ and $b_x$ such that
$$
x=a_x\cdot a+b_x\cdot b~~,~~a_x\geq 0,~~b_x\geq 0,~~a_x+b_x=1?
$$
Do $a_x$ and $b_x$ exist unique? I know that a possible solution is
$$
a_x = \frac{b-x}{b-a},~b_x = \frac{x-a}{b-a},
$$
but I do not know how to derive it and if this is the unique solution.

A: Consider
$$
a_x\cdot a+b_x\cdot b = x\\
a_x+b_x=1
$$
as a linear system in $a_x$ and $a_y$. This system is easily solved for all $x$, provided $a\ne b$, and it gives the solution you have. This proves it is unique.

A: Write $a_x=1-b_x$, and substitute into $x=a_x\cdot a + b_x\cdot b$ to get:
$$x=(1-b_x)a + b_xb$$
$$x=a+b_x(b-a)$$
$$b_x=\dfrac{x-a}{b-a}$$


text:
Q: Ubuntu terminal not opening , neither software update , software download and can't reinstall ubuntu I am new to linux / ubuntu and today I can't open my terminal nor my software updater and other apps ..I even tried to solve terminal issue by alt+ctrl+f3 and all other keys
but it gives blinking cursor only.I deleted the snap and used flatpak and even delete the original python in ubuntu if that's what caused the problem..I can't reinstall ubuntu as startup disk also doesn't open ..How can I make ubuntu work again or reinstall ubuntu


text:
Q: Angular cannot resolve promise I have created a service to communicate with a server via $http.post.
app.factory("dataService", [
    "$http", "$q", "$timeout", function ($http, $q) {

        function post(url, data) {
            var deferred = $q.defer();
            $http.post(url, data)
            .success(function (result) {
                deferred.resolve(result);
            })
            .error(function (error) {
                deferred.reject(error);
            });
            return deferred.promise;
        }

        return {
            post: post
        };

In the controller I am doing:
dataService.get(someUrl,someData).
  then(function (data) {
     $scope.result = data;
 });

Everything works fine, but if I call this generic "dataService" in some other service, for an example:
 app.factory("userService", ["$http", "$q","dataService", function ($http, $q,dataService) {

        function postUser(user) {
            dataService.post(usersUrl, user);
        }

        return {
            postUser: postUser
        };
    }

and call this "userService" in controller
userService.postUser($scope.user).then(){}, I am getting the following error:

Can anyone explain me why this is happening?

A: Try this :
app.factory("dataService", [
              "$http", "$timeout", function ($http) {

                function post(url, data) {
                  return new Promise(function(resolve, reject) {
                    $http.post(url, data)
                      .success(function (result) {
                        resolve(result)
                      })
                      .error(function (error) {
                        resolve(error)
                      });
                  });
                }
                return {
                  post: post
                };

And
app.factory("userService", ["$http", "$q","dataService", function ($http, $q,dataService) {

              function postUser(user) {
                return dataService.post(usersUrl, user);
              }

              // OR

              function postUser(user,callback) {
                dataService.post(usersUrl, user).then(function(data){callback(data);});
              }

              return {
                postUser: postUser
              };
            }

Hope it helps ;)
More info here

A: I have found a solution. Just needed to assign resolved promise to variable and then return that variable.
   function postUser(user) {
            var result = dataService.post(usersUrl,user);
            return result;
        };

A: You don't need to use $q here.There are a few angular services that return a $promise, for example $http,$timeout,$interval. Therefore you should not use $q here because a promise is already returned by the $http service.
Your service should look like this:
.factory('myService', function($http) {
       return {
        postMyData : function(){
        return $http.post(data);
 }

At this point you already have a promise returned by the $http angular service. Now you can just resolve it as you want ( controller ).
For example:
var myPromise = myService.postMyData(data).
        myPromise.then(function(){//success
                  },function(){//error
                  },function(){//inform that action is in progress
        })

A: If you call userService.postUser($scope.user).then(){} the function in userService should return the promise:
 function postUser(user) {
   return dataService.post(usersUrl, user);
 }


text:
Q: PHP namespace Error (the name is already in use) I'm trying to run this code on the same file:
namespace Foo1\Bar\SubBar;

class SubBarClass {

    public function __construct() {
        echo 'From Foo1';
    }

}

namespace Foo2\Bar\SubBar;

class SubBarClass {

    public function __construct() {
        echo 'From Foo2';
    }

}

use Foo1\Bar\SubBar;
$foo1 = new SubBarClass;

use Foo2\Bar\SubBar;
$foo2 = new SubBarClass;

The ideia is to change namespaces and echo the related value.
But it's returning the following error:
( ! ) Fatal error: Cannot use Foo2\Bar\SubBar as SubBar because the name is already in use in C:\wamp\www\xxx\namespaces.php on line 30
Line 30: use Foo2\Bar\SubBar;
How can I interchange namespaces on the same file?
Thks!

A: use keyword is used to import that namespace to be accessed in your current file scope. It does not act as a namespace "instance constructor".
You're current under Foo2\Bar\SubBar namespace. Like a directory of classes, while you're here, you should access other namespaces from the root (\):
$foo2 = new SubBarClass;
$foo1 = new \Foo1\Bar\SubBar\SubBarClass;

There is no need to use use for those namespaces (although you can, specially when they share parent namespaces), they are already declared in the same file you're using them.
For more information about this, consider reading the manual, where it describes using multiple namespaces in the same file.

A: This happens because the last defined namespace is the one currently active.
So, when I type:
use Foo1\Bar\SubBar;

I'm still on the last defined namespace: Foo2\Bar\SubBar.
Hence, when I type:
use Foo2\Bar\SubBar;

I'm trying to use the currently active namespace. That's why the Fatal error is returned.
On possible solution is:
namespace Foo1\Bar\SubBar;

class SubBarClass {

    public function __construct() {
        echo 'From Foo1';
    }

}

namespace Foo2\Bar\SubBar;

class SubBarClass {

    public function __construct() {
        echo 'From Foo2';
    }

}

use Foo1\Bar\SubBar;
$foo1 = new SubBar\SubBarClass;

echo '<br>';
$foo2 = new SubBarClass;

Cheers!


text:
Q: Text markers on the margin Sometimes, I want to mark a section of my manuscript for later inspection. So far I have been using a different color, but I really do not like it. I was wondering if I can draw a black strip on the margin. Ideally, it should work across pages and with equations. I believe it should be possible to do since draft mode already does something similar. But I do not know where to start.
MWE for testing:
\documentclass{article}
\usepackage{lipsum}
\newenvironment{marked}{}{}

\begin{document}
\lipsum[1-4]
\begin{marked}
  \lipsum[5]
  \[ x = y\]
  \lipsum[6]
\end{marked}
\end{document}

Desired output:


text:
Q: Хранение структурированных данных, введённых с клавиатуры Доброй ночи друзья! Язык C++ я не знаю, но подруге очень хочу помочь, вот и стал ковыряться. Ей дали задание :
описать структуру с именем znak, содержащую следующие поля:

*

*фамилия, имя;

*знак зодиака;

*дата рождения (массив из трех чисел)

написать программу, выполняющую след. действия:
-ввод с клавиатуры данных в массив, состоящий из восьми элементов типа znak;
записи должны быть упорядочены по датам рождения;
Я бы конечно начал учить язык по-нормальному, приобрёл бы несколько книжек рекомендованных вами, но результат нужен уже завтра утром, и вот что я надумал, но не могу нормально записать AddThey в массив People :
#include <iostream>
#include <conio.h>
using namespace std;
#include <string>
//
int PeopleCounter;
//
struct znak {
    int id;
    string LastName;
    string FirstName;
    string Sign;
    int Day;
    int Month;
    int Year;
};
//
znak People[];
//
string ReceiveAData() {
    string content;
    string line;
    //
    do {
        getline(cin, line);
        content += line + '\n';
    } while (!line.empty());
    //
    return content;
}
//
int AddThis() {
    znak AddThey;
    //
    AddThey.id          =   PeopleCounter + 1;
    cout << "Введите фамилию :" << endl;
    AddThey.LastName    =   ReceiveAData();
    //
    cout << "Введите имя :" << endl;
    AddThey.FirstName   =   ReceiveAData();
    //
    cout << "Введите знак зодиака :" << endl;
    AddThey.Sign        =   ReceiveAData();
    //
    cout << "Укажите день(1-31) рождения :" << endl;
    AddThey.Day         =   stoi(ReceiveAData());
    //
    cout << "Укажите месяц(1-12) рождения :" << endl;
    AddThey.Month       =   stoi(ReceiveAData());
    //
    cout << "Укажите год(4 числа) рождения :" << endl;
    AddThey.Year        =   stoi(ReceiveAData());
    //
    People[PeopleCounter]   =   AddThey;
    PeopleCounter++;
    //
    return 1;
}
//
int main(int nNumberofArgs, char* pszArgs[]) {
    setlocale(LC_ALL,"Rus");
    cout << endl;
    cout << "Стартанули, выберите задачу :" << endl << endl;
    cout << "1 Ввести данные" << endl;
    cout << "2 Вывести список введённого" << endl;
    //
    if (_getch() == '1'){
        cout << endl;
        cout << "Режим ввода данных" << endl << endl;
        AddThis();
        //
        cout << PeopleCounter;
    }
    //
    _getch();
    return 1;
}

A: Посмотрите, подойдет ли подруге?
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct znak {
  string fname, lname, zname;
  int id, day, mon, year;
};

static inline bool check_date (znak *p)
{
  if (p->day < 1 || p->day > 31)
    return false;
  if (p->mon < 1 || p-> mon > 12)
    return false;
  if (p->year < 1900 || p->year > 2014)
    return false;
  return true;
}

// функция читает очередную структуру и увеличивает id
// возвращаем 0 при EOF (в консоли ^D или ^Z в винде)
znak *
get_pdata (int *curid)  // Глобальные переменные это нехорошо. Постараемся все делать через параметры функций
{
  static znak p;  // Это область памяти, адрес которой возвращаем. В main данные будут копироваться в вектор
  /* Обратите внимание на static перед структурой. Это важно!
     Память выделяемая таким образом сохраняется неизменной между вызовами функции.
     Таким образом данные могут быть простым способом возвращены в вызывающую процедуру.
     Тут, конечно, минус. Последние введенные strings в структуре останутся в памяти до конца всего процесса.
  */

  do { // будем читать в цикле, пока не введут все правильно
    cout << "Enter: first & last names, zodiac, day, month, year: ";
    cin >> p.fname >> p.lname >> p.zname >> p.day >> p.mon >> p.year;
    if (cin.good()) {
      if (check_date(&p))
        break;
      cout << "Invalid date format (1-31, 1-12, 1900-2014) repeate...\n";
      continue;
    }
    if (cin.eof()) {
      cout << "\nEnd of input\n";
      return 0;
    } else {
      string errline;
      // Похоже, что вместо чисел в дате вводились буквы.
      // Обязательно надо убрать их из потока ввода.
      getline(cin, errline); // проще всего прочесть их вместе с остатком строки
      cin.clear(); // и сообщить крестам о том, что мы исправили ситуацию
      cout << "Bad input. Try again...\n";
    }
  } while (1);

  p.id = ++(*curid); // увеличим "глобальный id" и присвоим его текущей персоне
  return &p;
}

static void
print_p (vector<znak> p)
{
  for (int i = 0; i < p.size(); i++)
    cout << p[i].id << ":\t" << p[i].fname << " " << p[i].lname << " ("
         << p[i].zname << ")\t"
         << p[i].day << '/' << p[i].mon << '/' << p[i].year << '\n';
}

// функция компаратор 2-х дат для крестовой сортировки
static bool cmp_date_p (znak p1, znak p2)
{
  int d = p1.year - p2.year;
  if (d)
    return d < 0;
  if (d = p1.mon - p2.mon)
    return d < 0;
  return p1.day < p2.day;
}

int main (int ac, char *av[])
{
  vector<znak> p; // здесь запоминаем все структуры по мере их ввода
  znak *per;      // адрес только-что введенных данных
  int curid = 0;

  while (per = get_pdata(&curid)) {
    p.push_back(*per); // добавим очередную персону
  }

  cout <<  p.size() << " persons loaded\n";
  print_p(p);
  sort(p.begin(), p.end(), cmp_date_p); // это встроенная сортировка из <algorithms>

  cout <<  p.size() << " persons sorted\n";
  print_p(p);

}

Я не издеваюсь, просто короче не получилось... В принципе static и inline в описаниях функций можно и убрать (чтобы меньше было вопросов).
Компилировал в линуксе.
Если что-то совсем непонятно, то спрашивайте.
A: С\С++ низкоуровневый язык, потому при создании массива нужно сразу указать размер и этот размер должен быть const на момент компиляции, так же размер массива нельзя будет изменить.
если выделять массив в динамической памяти (через new) то можно указывать не const размер и размер такого массива можно будет изменять (создавая новый массив и копирую туда данные из старого).
советую заглянуть вот сюда http://www.cplusplus.com/ и приглядеться к контейнерам set,vector,map так как они будут за вас работать с памятью.
однако при "сдаче" нужно будет объяснить "что это такое" хотя бы в двух словах


text:
Q: What is the easiest way to insert data in MySQL using a ruby script I did a ruby script that parses a lot of files in ruby data structures, like hashes for example.
I need to insert all this data in a MySQL database.
What I found:
mysql2
tmtm
dbi
Is there some native way to do this?
Thanks for any help
EDIT
Lets say that I have a hash with 100 entries like this:
hash = {"a" => 1, "b" => 2 ..., "c" => 100}

I would like to create a table at mysql with all this columns. I am afraid of Active Record is gonna be hard to do that.
PS: Im not using Rails, just a simple ruby script

A: If I were you, I would prefer ActiveRecord, because I don't have to clutter my code with lots of SQL statements.  Besides activerecord makes life easier.
Set it up like this
require 'active_record'

ActiveRecord::Base.establish_connection(
 :adapter => "mysql2",
 :host => "host",
 :username=>"user",
 :password=>"user",
 :database => "your_db"
)

Then use tables like this
class SingularTableName < ActiveRecord::Base
  has_many :table_relationship
end

Then query like this
SingularTableName.all #=> all records
SingularTableName.first #=> first record
SingularTableName.where("query")
SingularTableName.create("...) #=> create a record/row

You can find more methods here => http://api.rubyonrails.org/classes/ActiveRecord/Base.html
Update:
To overcome plural table names and default primary key, you can use
class AnyName < ActiveRecord::Base
  self.table_name = 'your table name'
  self.primary_key = 'your primary key'
  ...
end


text:
Q: How can I find everything until something else in PHP and return that as a string? I want to return these unique values from my URLs
394_black
500_mono2

The URLs:
/shop/swarovski/394_black_the-reagan-swarovski-maxi-dress
/shop/celeb/500_mono2_the-reagan-swarovski-maxi-dress

Can I do this in PHP?
Pseudo Code
$url    =       get url
$firstvar = after 3rd / and after second _ save text (500_mono2) from $url

$secondvar = using $firstvar return only first 3 numbers
//substr($firstvar, 0, 3);  (I think this will be it)

Updated my Question above, easier to understand

A: <?php

    $url = '/shop/celeb/500_mono2_the-reagan-swarovski-maxi-dress';
    $urlparts = explode('/', $url);

    list($var1, $var2, $var3) = explode('_', end($urlparts));

    echo $var1 . '
' . $var2 . '
' . $var3;

?>


text:
Q: How do I run a command without root properties Say I am logged in root, and some commands don't let me to run them in root. I tried to login different accounts, but I'm not able to do such a thing.
How can I execute such command (logged in root) without the root properties?

A: sudo -u <user> -H <command>

A: su -c "command and args" username


text:
Q: How does test and je/jne work Okay so I started working a little with assembly. I began with the following instructions:
test       al, al
jne        0x1000bffcc

Using the debugger, I wanted the code to not jump to address 0x1000bffcc so I set a breakpoint on the jne instruction and then inverted the al register using following lldb command:
expr $al = 1

This worked well so I continued until I stumbled across the following, very similar instruction pair:
test       al, al
je         0x1000bffcc

While this looks similar, inverting the al register doesn't seem to have an affect. It keeps on jumping to address 0x1000bffcc. So I did some research and figured out that test runs a logical AND with al itself and then sets the zero flag or ZF accordingly. This leads to two questions:

*

*Why did it help to invert the al register in the first example?

*Why does it not work in the second example?

*How can I use the debugger to make the code not jump in the second example?

Thanks a lot for your help!

A: test    al, al
jne     0x1000bffcc

The test instruction performs a logical and of the two operands and sets the CPU flags register according to the result (which is not stored anywhere).  If al is zero, the anded result is zero and that sets the Z flag.  If al is nonzero, it clears the Z flag.  (Other flags, such as Carry, oVerflow, Sign, Parity, etc. are affected too, but this code has no instruction testing them.)
The jne instruction alters EIP if the Z flag is not set.  There is another mnemonic for the same operation called jnz.
If you let the test instruction execute and then changed al before the conditional jump instruction, the conditional jump is still going to do whatever it was going to do before altering al.  That is because the value of al no longer affects the conditional jump.  If you change the value before the test, then it will work as expected.
As for why changing it sometimes has an effect:  It must be because the revised value of al is affecting other logic.
To use the debugger to make the instruction not jump, change the flags such that the Z flag is set.  It might be called ZF, or you might have to modify the bit in the EFLAGS register.  How to do this varies by the debugger and possibly its revision.


text:
Q: Regular expression - return string after equal sign and before a pipe I attempted to resolve this on my own, but I need some help.
I have a strong that is located in my syslogs - and while I know grep would be easier, I have my reasons for building a regular expression.
For example:   somerandomstufffilter-category=Web_Advertisements|andhereis more random stuff
In that garbled mess, there is an exact string 'filter-category=Web_Advertisements|'
I created this regex:     (filter-category=).*?(?=["|"])
Which pulls the exact string I want, and up to the pipe. Instead of giving me the entire string, I only want everything after the equal sign (and not include it in my match), and before the pipe.
Right now I am getting:    'filter-category=Web_Advertisements'
What I want to get is:   'Web_Advertisements' on its own. The trick is that whatever follows filter-category, can be anything, not just Web-Advertisements. That is why it MUST end with the first pipe it encounters.

A: *

*You don't need to capture filter-category=, so drop the ().

*You don't need to use a lookahead here, so drop the (?=...).

*By the way, you were misusing character classes by writing ["|"]—that would have meant you were going to match either a double-quote " or a pipe |.

Here's what you want:
filter-category=(.*?)\|

A: acheong87's answer could include pipes in the capture... if it's greedy and there is more than one pipe, it will capture everything up to the last pipe.
Try
filter-category=([^\|]*)\|
Like acheong87's answer, this will match the whole of
filter-category=Web_Advertisements|
from which you have to extract the part you want to keep, captured into $1


text:
Q: "No space left on device" but plenty of disk and inodes I have an 8TB WD red disk, with 273gb available disk space, and plenty of inodes. But I cannot even create a directory.
user@server:/media/WD 8TB 2$ mkdir tmp
mkdir: cannot create directory 'tmp': No space left on device

I've been searching for answers, but unable to find anything useful.
It's a fresh Ubuntu 18.04.3 LTS install. Though the content on the /media\WD 8TB x aren't new.
$ df -h -Bg
Filesystem                                    1G-blocks  Used Available Use% Mounted on
udev                                                 2G    0G        2G   0% /dev
tmpfs                                                1G    1G        1G   1% /run
/dev/sda2                                          146G   14G      125G  10% /
tmpfs                                                2G    0G        2G   0% /dev/shm
tmpfs                                                1G    0G        1G   0% /run/lock
tmpfs                                                2G    0G        2G   0% /sys/fs/cgroup
/dev/loop0                                           1G    1G        0G 100% /snap/core/7270
/dev/loop1                                           1G    1G        0G 100% /snap/core/8268
/dev/sdb1                                         7394G 7096G        0G 100% /media/WD 8TB 1
/dev/sdd1                                         7394G 7373G        0G 100% /media/WD 8TB 3
/dev/sdc1                                         7394G 7121G        0G 100% /media/WD 8TB 2
tmpfs                                                1G    0G        1G   0% /run/user/1000
/dev/sde1                                         1833G  349G     1392G  21% /media/WD Elements

$ df -i
Filesystem                                       Inodes  IUsed     IFree IUse% Mounted on
udev                                             491041    510    490531    1% /dev
tmpfs                                            498893    764    498129    1% /run
/dev/sda2                                       9773056 643326   9129730    7% /
tmpfs                                            498893      1    498892    1% /dev/shm
tmpfs                                            498893      3    498890    1% /run/lock
tmpfs                                            498893     18    498875    1% /sys/fs/cgroup
/dev/loop0                                        12823  12823         0  100% /snap/core/7270
/dev/loop1                                        12842  12842         0  100% /snap/core/8268
/dev/sdb1                                     244191232   9294 244181938    1% /media/WD 8TB 1
/dev/sdd1                                     244191232  19039 244172193    1% /media/WD 8TB 3
/dev/sdc1                                     244191232  15604 244175628    1% /media/WD 8TB 2
tmpfs                                            498893     11    498882    1% /run/user/1000
/dev/sde1                                     122093568   2150 122091418    1% /media/WD Elements


text:
Q: Post запрос ASP.NET web api при попытке отправки Post запроса с клиента(Angular2) на сервер ASP.NET web api, в ответе с сервера приходит ошибка
{"Message":"Запрошенный ресурс не поддерживает HTTP-метод \"GET\"."}

С чем это может быть связано? и как можно решить проблему
Сам код контроллера:
using RealAgency.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Web.Http.Results;
using System.Web.Http.Cors;
using System.Web.Http;

namespace RealAgency.Controllers
{
    [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers:     "*", methods: "*")]
public class PostAdController : ApiController
{
    [HttpPost]
    public System.Web.Mvc.JsonResult PostAd( Card data)
    {
        return new System.Web.Mvc.JsonResult();
    }
}

}

A: Метод, который Вы описали в коде принимает только Post запросы, поэтому и возникает ошибка. Для того, чтобы это исправить добавьте метод с атрибутом [HttpGet] или поменяйте атрибут у текущего метода.

A: По всей видимости вы отправляете GET-запрос,в то время как контроллер поддерживает только POST-запросы. Добавте метод с атрибутом [HttpGet], этот метод будет срабатывать при получении GET-запроса.
Гайд по запросам Asp.Net можно найти на Metanit, к примеру вот этот:
https://metanit.com/sharp/aspnet5/5.2.php
Или вот этот:
https://metanit.com/web/angular2/6.4.php


text:
Q: Excel cannot connect to the SharePoint list I'm getting this error while exporting a custom list to excel. Any ideas why I'm getting this error?

Here is the same question. Still couldn't solve this error.
P.S.: "Check for server certificate revocation" setting in InternetExplorer did not solve my problem.


text:
Q: C# PropertyInfo GetValue() returns "Object does not match target type" I have a project that is reading rows returned from a SQL Server View, let's call the view 'Foo', and writing these rows to a series of files.  Using LINQ2SQL to reference the view in my project, results from  Foo are called 'FooResults'.
The method provided below accepts the type of object to parse as well as the delimiter, the path to write the file to and a generic list of the data to be parsed. I've indicated where the exception is thrown.
public void WriteRecords<T>(T classType, string delimiter, string outputPath, List<T> data)
{
    // Extract the property names and format as a delimited string
    var properties = classType.GetType().GetProperties().ToList();
    var headerLine = string.Join(delimiter, properties.Select(p => p.Name).ToArray());
    var formattedHeaderLine = new[] { headerLine };

    // Foreach line in the data provided, extract the values and format as delimited string
    foreach (var d in data)
    {
        try
        {
            foreach (var pinfo in d.GetType().GetProperties())
            {
                // This is the line causing the problems
                var value = pinfo.GetValue(pinfo, null);
            }
        }
        catch (Exception ex)
        {
            var message = ex.Message;
        }
    }
}

The exception is:

Object does not match target type

A: var value = pinfo.GetValue(pinfo, null);

Should be
var value = pinfo.GetValue(d, null);

You should be passing the instance instead of the PropertInfo itself.


text:
Q: How to sort the data in asc and desc order in table I am new to react js. Here, I am trying to sort the data when the user clicks on the icons.
Technology

So, Now I have data which is in the form of an array of objects.
In this, I have 5 columns and sort icon is on every column. So, How do I Implement this thing using the react?
I want to sort using the alphabetical order.
My data looks like,
[{
        "id": "5b7d4a566c5fd00507501051",
        "hrmsJdId": null,
        "companyId": null,
        "jdName": "Senior/ Lead UI Developer",
        "jobDescription": null,
        "technology": java,
    }, {
        "id": "5b7fb04d6c5fd004efdb826f",
        "hrmsJdId": null,
        "companyId": null,
        "jdName": "Content Innovation Lead",
        "jobDescription": null,
        "technology": css
    }, {
        "id": "5b7fb0b26c5fd004efdb8271",
        "hrmsJdId": null,
        "companyId": null,
        "jdName": "Urgent Opening for DSP Engineer/ Senior Engineer for",
        "jobDescription": null,
        "technology": react,
    }]

 {item.technology}
                17

{item.jdName}

                  {(key + 1 === 1) &&
New
}

This is how I render the data. Now,
By default, I sort it using the

          {props.jobList && props.jobList && props.jobList.length > 0 && props.jobList.sort((a, b) => b.createdAt - a.createdAt).map((item, key) => {
            return (

                 <input type="checkbox" name="myTextEditBox" value="checked" />
                {item.technology}
                17

{item.jdName}

                  {(key + 1 === 1) &&
New
}

                30
                30

So, How do I implement this ?
What I did is ,
Technology

then in container
    sortData = (key,event) => {
        console.log("key is,", key);
        this.props.sortAscending(key);
      }

<UserJobsTabel jobList={filteredList} sortAscending={this.sortData} />

passed as a props.
Now in action,
export const sortAscending = (type) => {
  return {
    type: "SORT_ASCENDING",
    payload: type
  }
}

In  reducer,
case FETCHING_JOBDESCRIPTION_SUCCESS:
            return {
                ...state,
                jobList: action.data.jobData ? action.data.jobData.sort((a, b) => b.createdAt - a.createdAt) : action.data.jobData,
                yesterDayScore: action.data.yesterdayScore,
                todayScore: action.data.todayScore,
                error: false,
            }

 case "SORT_ASCENDING":
          const { sortKey } = action.payload;
            const jobList = [ ...state.jobList ]
        .sort((a, b) => a[sortKey].localeCompare(b[sortKey]));
      return { ...state, jobList };

×
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

I am getting this error.

A: React Js arrays have a sort function:
['b', 'a'].sort((e1, e2) => e1.id < e2.id  ? 1 : - 1)

If the lambda function returns 0, it does nothing. Otherwise, the two elements in the array will be sorted by the sign of the returned value.
If there are duplicate IDs in the database then the function will return 0.
To swap the order, change either the sign of the return value or the "smaller than" operator to a greater than operator.

A: Use localeCompare() to sort in alphabetical order.
Have the sorting done in reducer while the component just dispatches the "sort" action. Every re-sort will cause a component re-render for jobList prop (in mapStateToProps) is updated.
In reducer:
const initialState = {
  jobList: [],
};

export const jobList = (state = initialState, action) => {
  switch(action.type) {
    case Action.SORT_ALPHA_ASC:
      const { sortKey } = action.payload;
      const jobList = [ ...state.jobList ]
        .sort((a, b) => a[sortKey].localeCompare(b[sortKey]));

      return { ...state, jobList };

    default:
      return state;
  }
}

In your component:
// alphaSort will dispatch action: SORT_ALPHA_ASC
const { jobList, alphaSort } = this.props;
if (! jobList || jobList.length < 1) {
  // no job list
  return null;
}

return (

    { /* TODO: use th/td */ }
    <SomeIcon name='asc-technology' onClick={() => alphaSort('technology')} />
    <SomeIcon name='asc-jdname' onClick={() => alphaSort('jdName')} />
    { /* TODO: other fields */ }

  {
    jobList.map((job) => ({

        {job.technology}

{job.jdName}

        { /* TODO: other fields */ }

    }))
  }

);

NOTE:
descending alpha sort and other fields will be for the OP to continue. :)


text:
Q: Using string conditionals to determine document class I am trying to set up a set of templates for most of the styles I have created or collected. Right now I am using a bunch of LaTeX files with the \input{} and setting variables with \def. What I am looking to accomplish is to have the template setup execute a series of steps depending on the variable sent. For example.
My main document will have something like this on the first couple of lines.
\def\doctype{letter} % this could also be a book, article, beamer presentation, etc.
\input{template-setup}

Based on the doctype I want to get my template setup to select the right document class. I know of the xstring or xifthen packages, but since I want to use the doctype variable to select the right document class, this is not possible (since you cannot use a package before \documentclass). Can somebody please help me?

A: I will use a general class file that can load the specific class as an option and create a boolean type test for all the different classes. The following is just a first try. It can be enhanced with keyvalues, etc.
Edit 1: Add command \ClassList to provide your own class list.
%%%% generalclass.cls %%%%

\NeedsTeXFormat{LaTeX2e}[1995/12/01]
\ProvidesClass{generalclass}[2012/04/19 v0.1 General class (DNJ ELS)]

\RequirePackage{etoolbox}

\newcommand*\DeclareClassList[2]{%
    \def\@clsopt@select{#1}%-------------------- default class
    \edef\@clsopt@list{\zap@space#2 \@empty}%--- list of classes
    \@for\@clsopt@item:=\@clsopt@list\do{%
        \newbool{@clsopt@test@\@clsopt@item}%
        \csedef{@clsopt@def@\@clsopt@item}{%
            \def\noexpand\@clsopt@select{\@clsopt@item}}}
    \edef\@currclass@opt{\@ptionlist{\@currname.\@currext}}%
    \@for\CurrentOption:=\@currclass@opt\do{%--- Go through documents options
        \ifcsdef{@clsopt@def@\CurrentOption}{%
            \csuse{@clsopt@def@\CurrentOption}%
            \csdef{ds@\CurrentOption}{}%
            \@use@ption}{}}}

\newcommand*\ThisClass{}
\newcommand\SetClassOption{%
    \edef\@clsopt@temp{%
        \noexpand\booltrue{@clsopt@test@\@clsopt@select}%
        \def\noexpand\ThisClass{\@clsopt@select}}%
    \@clsopt@temp}

\newcommand\IfClass[3]{%
    \ifbool{@clsopt@test@#1}{#2}{#3}}

%----------------------------------------------------------------------
\providecommand*\ClassDefault{article}                   % Edit 1
\providecommand*\ClassList{article,report,book,letter}   % Edit 1
\DeclareClassList{\ClassDefault}{\ClassList}             % Edit 1
\SetClassOption

\DeclareOption*{\PassOptionsToClass{\CurrentOption}{\ThisClass}}
\ProcessOptions\relax
\LoadClass{\ThisClass}
\endinput

It can then be used as follows:
\newcommand*\DocType{memoir}
\newcommand*\FontSize{10pt}
\newcommand*\PaperSize{a4paper}

%---- [ Put this in template for \input{} ] -------------
\newcommand*\ClassList{article,report,book,letter,memoir}
\documentclass[\DocType,\FontSize, \PaperSize]{generalclass}
%% Usage
%\IfClass{article}{..<true>..}{..<false..}
%\IfClass{report}{..<true>..}{..<false..}
%\IfClass{book}{..<true>..}{..<false..}
%\IfClass{letter}{..<true>..}{..<false..}
%\IfClass{memoir}{..<true>..}{..<false..}
%---- [ End template ] ----------------------------------

\begin{document}
    This class is: \ThisClass \par
    This is \IfClass{article}{an}{not an} article class document\par
    This is \IfClass{report}{a}{not a} report class document\par
    This is \IfClass{book}{a}{not a} book class document\par
    This is \IfClass{letter}{a}{not a} letter class document\par
    This is \IfClass{memoir}{a}{not a} memoir class document\par
\end{document}

A: You can define macros which hold the different values (letter, book, etc.) and then compare it with \doctype using \ifx\firstmacro\secondmacro <equal> \else <not equal> \fi:
\def\doctype{letter} % this could also be a book, article, beamer presentation, etc.
% ..
\def\doctypeletter{letter}
\def\doctypebook{book}
% ...

\ifx\doctype\doctypeletter
  % doctype is 'letter'
\else
\ifx\doctype\doctypebook
  % doctype is 'book'
\fi
\fi

Note that it is also possible (but not always recommendable) to load a package before the class using \RequirePackage instead of \usepackage.

You could also make your own class files which load the real class using \LoadClassWithOptions{<real class>} and then include your required settings for this class.


text:
Q: Excel nested MATCH? I have a spreadsheet (MASTER TIMETABLE) listing a number of venues, days and activities on each day, as shown below:

In a separate sheet, I want to provide inputs of the Venue and Day, and get an output of the Activity. For example, if I input VIC - Kennington (B20) and Thursday 5th April (J20), I'd get The Zone (J21) as my output.
My problem is that the days change from venue to venue, so I can't just highlight the entire array and use the top row to lookup the Day. I've been able to find out the row to search by using the following formula:
=MATCH($B$2,'MASTER TIMETABLE'!B:B,0)

Using this, if B2 is VIC - Kennington, I'll get an output of 20. That gives me the row I then need to search for the Day, but I can't seem to figure out how to then pull that into the next MATCH function, e.g.:
=MATCH($A$5,'MASTER TIMETABLE'!20:20,0)

If I can figure out how to generate the 20:20 part of the formula dynamically, I know that the next step is just a simple offset down by one row, but I can't figure out how to get the formulas to nest. I've also considered using VLOOKUP, but again I can't figure it out.

A: I've managed to get it to work, using INDEX. Considering the Day columns don't move in relation to the Venue, I can just set the column_num as a static. Nesting that inside an OFFSET gives me the Activity. Here's my final formula:
=OFFSET(INDEX('MASTER TIMETABLE'!$B$2:$Z$667,MATCH($B$2,'MASTER TIMETABLE'!$B$2:$B$666,0),5),1,0)

Thanks to Bandersnatch for putting me on the right track.


text:
Q: Javascript - biggest number from array using loop Can somebody please explain how this code gets which number from array is the biggest?
var num = [];
for( var i = 0; i < 10; i++ ) {
     num[i] = parseInt( prompt("Unesite broj " + (i+1) + "." ) );
}

var biggest = 0;
for(i=0; i < num.length; i++ ) {
    if( num[i] > biggest ) {
        biggest = num[i];
    }
}

console.log("The biggest number is " + biggest );

A: To start, we've seen no numbers, and the code assumest the biggest is 0 or larger:
var biggest = 0;

We'll look at each number in the list:
for(i=0; i < num.length; i++ ) {

Is the current number bigger than the biggest we've seen?
  if( num[i] > biggest ) {

If so, it's the new biggest number
    biggest = num[i];
  }
}

When the loop is done, biggest contains the largest number we saw along the way.

A: The if statement within the loop checks whether the number in the current element of the array is greater than the largest number found so far. If the current number is the greatest, the largest number found so far is updated to this new number.

A: First for loop just prompts you to add numbers to an array.
The second loop just checks each number in the num array, if that number is bigger than the number in the biggest variable then it sets the biggest variable to that number.
It's as simple as that.


text:
Q: How to use an OR statement in a Post-Build event? I am trying to use a conditional with an OR in a Post-Build event, but so far, I have had not luck.  The following does not work:
if not "$(ConfigurationName)" == "Debug" or not "$(ConfigurationName)" == "Release" (
but this works:
if not "$(ConfigurationName)" == "Debug" (
With the first one, I get an exist code 4.

A: It seems like there is no provision for OR/AND in conditionals in Pre-Post Build events, at least according to its lack of documentation over here: http://technet.microsoft.com/en-us/library/bb490920.aspx
You would have to re-write your IF statement to do what you would want to do.
if not "$(ConfigurationName)" == "Debug" (
   rem do something
) else if not "$(ConfigurationName)" == "Release" (
   rem do the same thing as above
)

Hope that helps, though your conditions don't make sense to me. :-)

A: If you want to execute some logic in a Post-Build event where the ConfigurationName is not "Debug" or "Release", try the following:
if not "$(ConfigurationName)" == "Debug" (if not "$(ConfigurationName)" == "Release" (***ADD LOGIC HERE - ConfigurationName is not "Debug" or "Release"***))


text:
Q: Necessity of braces when creating newcommand using csname Why does \expandafter\newcommand\csname hello\endcsname{Hello world} create a new macro while \expandafter\newcommand{\csname hello\endcsname}{Hello world} creates garbage?
Form what I understand, \csname hello\endcsname programatically creates a new string that can be used as a command name, in this case, something like \hello. You can write both \newcommand\hello{Hello world} and \newcommand{\hello}{Hello world} and they both work. So why is it that when csname is envolved, I have to use the form without curly braces surrounding the name?

A: You need to supply an explicit control sequence for \newcommand, and \csname <text>\endcsname is not a control sequence until it is expanded.
Using
\expandafter\newcommand\csname hello\endcsname{<stuff>}

expands to
\newcommand\hello{<stuff>}

as a result of the \expandafter skipping over \newcommand and expanding \csname hello\endcsname to \hello. However,
\expandafter\newcommand{\csname hello\endcsname}{<stuff>}

expands to
\newcommand{\csname hello\endcsname}{<stuff>}

as { is not expandable, making \expandafter useless. If you want to use the "grouped interface for \newcommand", you would need an additional \expandafter:
\expandafter\newcommand\expandafter{\csname hello\endcsname}{<stuff>}

However, without it, \newcommand fails since there's no explicit control sequence.
etoolbox provides a means around this via an interface to \@namedef{<csname>} (from the LaTeX kernel latex.ltx):
\csdef{<csname>}<args>{<stuff>}

That is, you can use
\csdef{hello}<args>{<stuff>}

<args> above are optional but take the \def form of argument specification (or pattern). That is, #1 instead of [1], say.

A: The "official" syntax for \newcommand is
\newcommand{<macro name>}[<args>]{<text>}

or
\newcommand{<macro name>}[<args>][<default>]{<text>}

but it turns out that the braces around the <macro name> are optional, so long as a single token appears. The braces are good for avoiding mistakes, but some self-control usually suffices.
With
\expandafter\newcommand\csname hello\endcsname{world}

the token \hello is built before \newcommand starts acting and absorbing its first argument (the story is much longer, actually, but this short explanation is precise enough).
On the other hand,
\expandafter\newcommand{\csname hello\endcsname}{world}

will try to expand the brace: \expandafter just acts on a single token, triggering its expansion, if the token is expandable, otherwise doing nothing. You can have the braces, if you prefer, but you need a further \expandafter:
\expandafter\newcommand\expandafter{\csname hello\endcsname}{world}

However this is too much for such a simple construction, isn't it?
If you find yourself in the position of having to do several of these definitions, it's "easy" to build a wrapper
\makeatletter
\newcommand\newnamecommand{\@star@or@long\new@name@command}
\newcommand\new@name@command[1]{\expandafter\new@command\csname #1\endcsname}
\newcommand\renewnamecommand{\@star@or@long\renew@name@command}
\newcommand\renew@name@command[1]{\expandafter\renew@command\csname #1\endcsname}
\newcommand\providenamecommand{\@star@or@long\provide@name@command}
\newcommand\provide@name@command[1]{\expandafter\provide@command\csname #1\endcsname}
\makeatother

\newnamecommand{hello}{Hello World}
\newnamecommand*{helloarg}[1]{Hello #1}

\renewnamecommand{hello}{Whatever}

\providenamecommand{foo}{FOO}


text:
Q: Choosing Youtube API v3 vs v2 for Python GUI application I am looking into writing a Python GUI app to make use of the Youtube API. This app intends to gather meta data and visualize the results in a variety of methods, however, I am unsure as to which API to use. V2 has plenty of documentation online and uses XML, while V3 is still experimental and uses JSON. Will the code examples for V2 be portable to V3 ?
Link: Python - v2 documentation

A: YouTube v3 is not marked as experimental. The code samples can be found here.
Your link points to the 1.0 documentation. 1.0 has been deprecated.


text:
Q: matplotlib figure vs subplot vs axes? Though I've been able to create basic plots with matplotlib.pyplot before, I cannot fully understand what the difference between these are:

*

*figure

*subplot

*axes

*(axis?)

As I understand, all three of these are objects for the area in which a graph is drawn, so what distinguishes them in terms of what can be drawn inside them?

A: Matplotlib's user guide gives a great description about the parts of a figure.

A: The components are hierarchical:
Figure object: the whole figure
Axes object: belongs to a Figure object and is the space where we add the data to visualize
Axis object: belongs to an Axes object. Axis object can be categorized as XAxis or YAxis.
For further info, visit this link:
Getting Started with Matplotlib


text:
Q: Android ScrollView not working properly when use toolbar I developed an android application in which the scroll-view is not scrolling.. I am posting the code here pls check and if found any error pls help.. Here I used RelativeLayout as root and then Scroll-view and Relative Layout inside the scroll-view and ... Edit text ans Spinner inside relative layout... but this is not scrolling up..
This is my XML :-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white">

<LinearLayout
    android:id="@+id/ll1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/app_bar" />
</LinearLayout>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true"
    android:scrollbars="none"
    android:layout_above="@+id/btnAccept"
    android:layout_below="@+id/ll1"
   >

    <RelativeLayout
        android:id="@+id/rel_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin">

        <TextView
            android:id="@+id/txvPanmain"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="WANT TO GET IN TOUCH WITH US?"
            android:textColor="#131517"
            android:textSize="18sp"
            android:textStyle="bold" />

        <android.support.design.widget.TextInputLayout
            android:id="@+id/floatedtFullName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/txvPanmain"
            android:layout_marginTop="10dp">

            <EditText
                android:id="@+id/edtFullName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:focusable="true"
                android:hint="Full Name"
                android:inputType="textCapSentences"
                android:textColor="@android:color/black"
                android:textColorHint="#ff0000"
                android:textSize="18sp" />
        </android.support.design.widget.TextInputLayout>

        <Spinner
            android:id="@+id/spinCountry"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/floatedtFullName"
            android:layout_marginTop="15dp"
            android:entries="@array/country"
            android:prompt="@string/addressProof" />

        <View
            android:id="@+id/vspincountry"
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:layout_below="@+id/spinCountry"
            android:layout_marginTop="2dp"
            android:background="#000000" />

        <Spinner
            android:id="@+id/spinCity"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/vspincountry"
            android:layout_marginTop="15dp"
            android:entries="@array/country"
            android:prompt="@string/addressProof" />

        <View
            android:id="@+id/vspincity"
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:layout_below="@+id/spinCity"
            android:layout_marginTop="2dp"
            android:background="#000000" />

        <android.support.design.widget.TextInputLayout
            android:id="@+id/float_edit_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/vspincity"
            android:layout_marginTop="10dp">

            <EditText
                android:id="@+id/edtEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:focusable="true"
                android:hint="Email id"
                android:inputType="textEmailAddress"
                android:textColor="@android:color/black"
                android:textColorHint="#A4A4A4"
                android:textSize="18sp" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/float_edit_mobileno"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/float_edit_email"
            android:layout_marginTop="10dp">

            <EditText
                android:id="@+id/edtMobile"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:focusable="true"
                android:hint="Mobile no."
                android:inputType="phone"
                android:maxLength="10"
                android:textColor="@android:color/black"
                android:textColorHint="#A4A4A4"
                android:textSize="18sp" />
        </android.support.design.widget.TextInputLayout>

        <Spinner
            android:id="@+id/spinFeedback"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/float_edit_mobileno"
            android:layout_marginTop="10dp"
            android:entries="@array/country"
            android:prompt="@string/addressProof" />

        <View
            android:id="@+id/vspinFeedback"
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:layout_below="@+id/spinFeedback"
            android:layout_marginTop="2dp"
            android:background="#000000" />

        <android.support.design.widget.TextInputLayout
            android:id="@+id/float_edit_comments"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/vspinFeedback"
            android:layout_marginTop="10dp">

            <EditText
                android:id="@+id/edtComments"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:focusable="true"
                android:inputType="text"
                android:hint="Comments"
                android:lines="3"
                android:maxLines="3"
                android:textColor="@android:color/black"
                android:textColorHint="#A4A4A4"
                android:textSize="18sp" />
        </android.support.design.widget.TextInputLayout>
    </RelativeLayout>
</ScrollView>

    <Button
        android:id="@+id/btnAccept"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/red"
        android:layout_alignParentBottom="true"
        android:padding="5dp"
        android:text="SUBMIT"
        android:textColor="@color/white_color"
        android:textSize="20sp"
        android:textStyle="normal" />

<ProgressBar
    android:id="@+id/progress"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:visibility="gone" />
</RelativeLayout>

This is my app_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar        xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:paddingTop="@dimen/app_bar_top_padding"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:theme="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar">

<TextView
    android:id="@+id/toolbar_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textSize="22sp"
    android:textColor="@android:color/white"
    android:textStyle="bold"
    android:text="Toolbar Title" />
</android.support.v7.widget.Toolbar>

A: Your ScrollView has to be a defined height. Try match_parent instead of wrap_content. When a ScrollView wraps its contents there is nothing beeing clipped of you might be able to scroll to.


text:
Q: Prime number modulo A would be very thankful if somebody would help me understand and resolve following problem:
"Let $p$ be an odd prime number, let $a$ be any integer, let $b = a^{(p-1)/2}$.    Show that $b$ mod $p$ is either $0$ or $1$ or $(p-1)$."
Thanks

A: Little Fermat's theorem tells that $a^p\equiv a\pmod p$. Since $p-1$ is even, we can write
$$a(a^{(p-1)/2}+1)(a^{(p-1)/2}-1)\equiv 0\pmod p$$
Now, since $\Bbb Z_p$ is an integral domain (in fact it is a field), one of the factors is $0$.

A: If $p$ divides $a$, then $a^{(p-1)/2}\equiv 0 \mod p$, and then  $b\equiv 0 \mod p$. If p does not divide $a$, then $a^{p-1} \equiv 1 \mod p$ (Fermat's little thm). Therefore, since $b=a^{(p-1)/2}$, we have $b^2\equiv 1 \mod p$, and then $b\equiv \pm 1 \mod p$.


text:
Q: Sin cos function giving wrong results for degrees greater than 90 When I use
cout<<"Cos: "<<cos(_theta)<<" Sin: "<<sin(_theta)<<endl;

where _theta = 180, it gives output,
Cos: -0.59846 Sin: -0.801153

But the output should be
Cos: -1 Sin: 0

I don't understand why this is happening!

A: Functions cos and sin receive angles in radians instead of degrees.

A: Ask google about "cos(180)"   => -0.59846006905
It's because it using radians and not degrees.
In radians, 180° is half a circle, so it's pi, ask google cos(pi) => -1
:)


text:
Q: Crash when dynamically updating ListLinePlot I was trying to solve a wave problem using numerical methods. The code below crashes each time I run it on Windows with version 10.2.
data = {ConstantArray[0, 121]};
matA[n_, alpha_, dx_] :=
  Block[{result},
    result =
      SparseArray[
        {{i_, i_} -> alpha/dx,
        {i_, j_} /; i - j == 1 -> (-1-alpha)/(2dx),
        {i_, j_} /; j-i == 1 -> (1 - alpha)/(2dx)}, n + 1];
    result[[n + 1, -2 ;; -1]] = {-1/dx, 1/dx};
    result[[1, 1 ;; 2]] = {0, 0};
    result]
bc1[t_] := 1 + 0.1 Sin[4t];
dpdt[n_, mat_, source_, alpha_, dx_, x_, t_] :=
  Block[{rho = x},
    rho[[1, 1]] = source[t];
    -(matA[n, alpha, dx].(rho*{1 + 0.5 Cos[#]& /@
      Table[dx*j, {j, 0, n }]}\[Transpose])) // N];
RK4ODEs[n_, init_, mat_, source_, alpha_, dx_, dt_, time_] :=
  Fold[
    Block[{s, coeff1 = {0, 0.5, 0.5, 1}, coeff2 ={1/6, 1/3, 1/3, 1/6}},
      s[0] = 0;
      Do[
        s[i] =
          dpdt[n, mat, source, alpha, dx,
               #1 + coeff1[[i]]*s[i - 1]*dt, #2 + coeff1[[i]]*dt],
        {i,1,4}]//N;
      data = #1 + (1/6 s[1] + 1/3 s[2] + 1/3 s[3] + 1/6 s[4])*dt//N;
      data[[1, 1]] = source[#2 + dt];
      data2 = data;
      data2]&,
    init,
    Table[dt*j, {j, 0, Floor[time/dt]}]]
Dynamic[
  Module[{},
    ListLinePlot[data2//Transpose, PlotRange->{All,All}]],
    TrackedSymbols :> data2]
Dynamic[data2 // Transpose]
sol1 =
  RK4ODEs[150, {ConstantArray[1, 151]}\[Transpose], matA, bc1, 0.0, 0.09, 0.025, 30];

I noticed that if I comment out the line that dynamically updates the ListLinePlot, then the kernel will not crash, which means the problem is probably due to dynamically updating ListLinePlot. I have also tried several methods in this question, i.e., adding TrackedSymbols:>{data2}, wrapping ListLinePlot with Module, but neither works. In fact, TrackedSymbols:>{data2} can sometimes force the evaluation to continue (but you can see that something is still wrong because many frames pink and the red error box is flashing around the plot), however, the kernel will crash eventually. Besides, the crash is rather random in terms of time of occurrence, i.e., sometimes it crashes as soon as I ran the code, and sometimes it crashes after 10 sec or so. The error message popped up was "Transpose[data2] is not a list of numbers or pairs of numbers. " and An unknown box name (ToBoxes) was sent as the BoxForm for the expression. Check the format rules for the expression.
I am also wondering if there is a better way of visualizing data2, which contains information of the points at each time step. Of course, I could use FoldList to collect the information of the points at all time steps and then use ListAnimate to generate the movie. However, the problem with this is that it consumes as much as 3GB RAM since it stores the information of all points at all time steps. Besides, I have to wait until RK4ODEs finishes evaluation before I could call ListAnimate, and ListAnimate also takes a lot of time to generate the movie.
P.S: I am required to implement RK4 myself, so I am not allowed to use NDSolve.

A: I can not confirm the crash, neither in 10.2 nor in 10.3 on Linux. I did, however change the following line:
matA[n, alpha, dx].(rho *Transpose[{1 + 0.5 Cos[#] & /@ Table[dx*j, {j, 0, n}]}])

The other notation for Transpose did not seem to work. Also, some of the frames during the dynamic pink but that might be a different issue. It certainly did not crash for me. (Perhaps it does for a different OS - then it were good to report this to the support of Wolfram Research) - Looks nice when it runs...


text:
Q: Synchronising N sibling processes after fork I'm having some hard time with synchronising N child process waiting each one of them to arrive at some specific point.
I've tried semaphores and signals but I can't get my head around it.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/msg.h>

#define NUM_KIDS 4

void handle(int signum);

int main(int argc, char const *argv[])
{
    sem_t* sem;
    sem = sem_open("/ok", O_CREAT, 0);
    signal(SIGUSR1, handle);

    for(int i = 0; i < NUM_KIDS; i++) {
        switch(fork()) {
            case 0:
                fprintf(stderr, "ready %d from %d\n", getpid(), getppid());
                /* i would like that each child stop here untill everyone is ready */
                for(int j = 0; j < 10; j++)
                fprintf(stderr, "lot of stuff\n");
                exit(0);
            break;
            default:
                /* unleashing the kids when everyone is ready */
                wait(NULL);
                fprintf(stderr, "OK\n");

            break;
        }
    }
    return 0;
}

void handle(int signum) {;}

And I believe that the output should be (once the child are sync)
ready ... from xxx
ready ... from xxx
ready ... from xxx
ready ... from xxx
...lots of stuff... 10 times
...lots of stuff... 10 times
...lots of stuff... 10 times
...lots of stuff... 10 times

A: Synchronization
There's a simple trick:

*

*Create a pipe before you fork anything.

*Have the children each close the write end of the pipe.

*Have the children read from the pipe when you want to synchronize them.

*Have the parent close both ends of the pipe when the children should be started.

*Have the children close the read end of the pipe when they're released, so that the resources are released.

*The children now do 'their thing' (grow up, produce output, die).

*The parent now waits for its children to die (it's a morbid business when you're playing with processes on Unix).

If done correctly, the children all get EOF (zero bytes read) at the same time because there's no longer any process that can write to the pipe.  (That's why it is important for the children to close the write end of the pipe before doing the synchronizing read().)
If you want the parent to know that the children are all ready, create two pipes before forking anything.  The parent process closes the write end of this second pipe, and then reads from the read end.  The children all close both ends of the pipe before settling into their read() call on the first pipe.  The parent process gets EOF when all the children have closed the write end of the pipe, so it knows the children have all started, at least as far as closing the second pipe.  The parent can then close the first pipe to release the children (and close the read end of the second pipe).
Don't wait too soon!
You are waiting in the default clause of the switch, which is not correct.  You need all four child processes launched before you do any waiting — otherwise they'll never all be able to synchronize.  When you do wait, you'll need to do your waiting in a (new) loop.  And, while debugging, you should add print statements to identify what is going on in the parent process.  For example, you'll print the status of the processes that exit, and their PID:
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
    printf("%d: child %d exited with status 0x%.4X\n", (int)getpid(), corpse, status);

Working code
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

#define NUM_KIDS 4

int main(void)
{
    int p_pipe[2];
    int c_pipe[2];
    char c;
    if (pipe(p_pipe) != 0 || pipe(c_pipe) != 0)
    {
        fprintf(stderr, "Oops: failed to create pipes\n");
        return 1;
    }

    for (int i = 0; i < NUM_KIDS; i++)
    {
        switch (fork())
        {
        case 0:
            fprintf(stderr, "ready %d from %d\n", (int)getpid(), (int)getppid());
            close(p_pipe[0]);
            close(p_pipe[1]);
            close(c_pipe[1]);
            read(c_pipe[0], &c, 1);
            close(c_pipe[0]);
            for (int j = 0; j < 10; j++)
                fprintf(stderr, "lot of stuff\n");
            return NUM_KIDS + i;
        case -1:
            fprintf(stderr, "failed to fork child %d\n", i+1);
            return 1;
        default:
            break;
        }
    }

    close(p_pipe[1]);
    read(p_pipe[0], &c, 1);
    printf("%d: %d children started\n", (int)getpid(), NUM_KIDS);
    close(c_pipe[0]);
    close(c_pipe[1]);

    int corpse;
    int status;
    while ((corpse = wait(&status)) >= 0)
        printf("%d: child %d exited with status 0x%.4X\n", (int)getpid(), corpse, status);
    return 0;
}

Sample run
ready 81949 from 81948
ready 81950 from 81948
ready 81951 from 81948
ready 81952 from 81948
81948: 4 children started
lot of stuff
lot of stuff
lot of stuff
lot of stuff
…lines omitted for brevity…
lot of stuff
lot of stuff
lot of stuff
lot of stuff
81948: child 81951 exited with status 0x0600
81948: child 81952 exited with status 0x0700
81948: child 81950 exited with status 0x0500
81948: child 81949 exited with status 0x0400


text:
Q: show convergence for x tending to zero for $(2 - a^{1/x})^x$ I have the following problem:
I need to show whether a limit exists for $F(x) = (2 - a^{1/x})^x$ for $x$ tending towards zero (and $x$ tending towards infinity) where $0<a<1$. If one of these limits exists I am supposed to calculate it.
Could anyone help me to solve this problem?
I already tried expressing $F(x)$ as a Summation according to the binomial theorem and calculating the limit of the series but without any luck :(

A: Note that if the limit exists, then
$$
\lim_{x \to 0} F(x)
 = \exp\left(\ln \left( \lim_{x \to 0} F(x) \right)\right)
 = \exp\left(\lim_{x \to 0} \ln ( F(x) )\right).
$$