text:
Q: Retrieving data from a form in MVC3 i am currently trying to get data from a form in a view to my controller, i'm sending it a list of object and my goal is to get the one that have been modified by having multiple form. The probleme here is that i don't get anything back from the view, just null values.
@model List<Connection_User>

@for (int i = 0; i < Model.Count ; i++)
{
using(Html.BeginForm("DBLogin","User", FormMethod.Post, new { autocomplete ="off"}))
{
    <fieldset>

        @ConsoleV2.Resources.Strings.Name

        @Html.TextBoxFor(model => model[i].Username)
        @Html.ValidationMessageFor(model => model[i].Username)

        @ConsoleV2.Resources.Strings.Password

        @Html.PasswordFor(model => model[i].Password)
        @Html.ValidationMessageFor(model => model[i].Password)

        <input type="submit" value="@ConsoleV2.Resources.Strings.Valid" />

    </fieldset>
}
}

and the prototype of my method in the controller is
[HttpPost]
public ActionResult DBLogin(Connection_User Logins)
{

        return new EmptyResult();
}

Thanks in advance for your help.

A: Try foreach instead of for
@foreach(var modelItem in Model)
{
using(Html.BeginForm("DBLogin","User", FormMethod.Post, new { autocomplete ="off"}))
{
    <fieldset>

        @ConsoleV2.Resources.Strings.Name

        @Html.TextBoxFor(item => modelItem.Username)
        @Html.ValidationMessageFor(item => modelItem.Username)

        @ConsoleV2.Resources.Strings.Password

        @Html.PasswordFor(item => modelItem.Password)
        @Html.ValidationMessageFor(item=> modelItem.Password)

        <input type="submit" value="@ConsoleV2.Resources.Strings.Valid" />

    </fieldset>
}
}


text:
Q: Show Text in TextView when video reaches current time Android I want to make a text appear in TextView when the video reaches current time. I've tried this code :
public class VideoActivity extends Activity {
    private static final String MY_AD_UNIT_ID = null;
    protected static final String TAG = null;
    private AdView adView;
    int waktu;
    Button btncek;
    private MediaController controller = null;
    TextView textView2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.videoplayer);
    Bundle bundle = getIntent().getExtras();
    String urlbarus = getIntent().getStringExtra("urlbaru");
    final VideoView videoView = (VideoView) findViewById(R.id.videoView1);

    videoView.setVideoPath(urlbarus);

    MediaController.MediaPlayerControl mcEvents = new MediaController.MediaPlayerControl() {
        public void start() {
            videoView.start();
        }

        public void seekTo(int pos) {
            videoView.seekTo(pos);
        }

        public void pause() {
            videoView.pause();
        }

        public boolean isPlaying() {
            return videoView.isPlaying();
        }

        public int getDuration() {
            return videoView.getDuration();
        }

        public int getCurrentPosition() {
            return videoView.getCurrentPosition();
        }

        public boolean canSeekForward() {
            return true;
        }

        public boolean canSeekBackward() {
            return true;
        }

        public boolean canPause() {
            return true;
        }

        @Override
        public int getBufferPercentage() {
            // TODO Auto-generated method stub
            return 0;
        }
    };

    controller = new MediaController(this);
    controller.setMediaPlayer(mcEvents);
    controller.setAnchorView(findViewById(R.id.wrapper));

    videoView.start();

  if(mcEvents.getCurrentPosition()>=10000){
            textView2.setText("kebaca");
            }

@Override
public boolean onTouchEvent(MotionEvent event) {
    //the MediaController will hide after 3 seconds - tap the screen to make it appear again
    controller.show();
    return false;
}

This is the code for showing text :
if(mcEvents.getCurrentPosition()>=10000){
    textView2.setText("kebaca");
}

I have tried that code, but nothing happens (textview2 does not show the text)
Can anyone help me?

A: Try something like..
    final MediaController.MediaPlayerControl mcEvents = ....

    textView2.setText(""); // edited

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (mcEvents.getCurrentPosition()<10000){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) { }
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textView2.setText("kebaca");
                }
            });
        }
    }).start();

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to design a circuit checking if 12V car battery is charging? I have a small solar power charging module and load balancer, that takes input from a solar panel, has connectors for a car battery (12V) and output terminals.
These things are pretty common on thing like RVs, caravans, camper vans, etc.
The module however, has no digital readout displays. Attaching a couple of those to the terminals of the charger / power manager is trivial, but I was wondering how I can have an LED light up, when the car battery is charging, i.e. current is flowing in to the battery. And have no LED light up, when current is being drawn from the battery.
The Voltage / Amperage meters I use, just shows the absolute values, they don't display for instance a negative amp value to signify direction.
So, how / what would be the simplest circuit to display current direction, in to the battery (battery is being charged) and if current is drawn from the battery (battery is discharging)?
Obviously, the circuit should draw as little current as possible itself.

Edit
Couldn't I simply use a comparator, like an LM319, and use the batteries wire that connects its terminal to the power management unit as resistor? I.e. having the non-inverting input going to the battery terminal, and the inverting input to the power management box.


text:
Q: Unable to make custom copy event listener, bound to an element, work properly I have added a custom event listener to copy/cut of text from an element (say elementId). Now when I copy from elementId and paste on word the functionality works fine.
But when I copy from the elementId and paste on notepad, the paste doesn't work. By doesn't work I mean nothing is pasted at all.
document.getElementById(config.editorEl).addEventListener('copy', function(event) {
    const range = window.getSelection().getRangeAt(0);
    const content = range.cloneContents();
    const div = document.createElement('div');
    div.appendChild(content);
    $(div)
    .find('.remove_this_class')
    .contents()
    .unwrap();
    event.clipboardData.setData('text/html', div.innerHTML);
    event.preventDefault();
    });

Summary: The custom copy/cut handler doesn't work properly.

*

*Copy - paste on word (works correctly)

*Copy - paste on notepad(Nothing gets pasted at all)

*Copy - paste on url bar (Nothing gets
pasted at all)


text:
Q: Upload validation, allowing other extensions? At the moment I have allowed for .jpg files to be uploaded.
How do I add jpeg, gif and png?
My current code is as follows...
$filename = basename($_FILES['photo']['name']);
            $ext = substr($filename, strrpos($filename, '.') + 1);

            //Check if the file is JPEG image and it's size is less than 5Mb
$allowedExts = array('jpg', 'jpeg', 'gif', 'png');
            if ( (in_array($ext, $allowedExts)) && ($_FILES["photo"]["type"] == "image/jpeg") && ($_FILES["photo"]["size"] <= 5242880) ){
                //Determine the path to which we want to save this file
                $newname = str_replace( ' ', '_', trim( strip_tags( $_POST['name'] ) ) ) . _ . $formKey->generateKey() . '_' . time() . '.jpg';

A: Make an array of allowed extensions, and check against it. Take a look at http://php.net/manual/en/function.in-array.php.
You'd end with something like:
$allowedExts = array('jpg', 'jpeg', 'gif'); // Add more here
if (in_array($ext, $allowedExts))
{
    // Do something here
}

Also, to check the extension of a file, I suggest you to use pathinfo: http://php.net/manual/en/function.pathinfo.php
Some people can trick you with uploading files ending with .jpg, but that could be .php files.
[EDIT] Updated as I hate the mini-commenting:
   $allowedExtensions = array("image/jpeg", "image/png", "image/gif", "image/pjpeg", "image/jpg");
   $pathInfo = pathinfo($_FILES["photo"]["type"]);
   if (in_array($pathInfo['extension'], $allowedExtensions))
   {
       // Do stuff
   }

Waaaay simpler this way. This can even be simplified by using pathinfo's second parameter, but I'm assuming you'll need the other elements of the array after.

A: You could use the following:
if(file_exists($path_image) && in_array(exif_imagetype($path_image),array(1, 2, 3, 6))){ ... }

http://php.net/manual/en/function.exif-imagetype.php


text:
Q: Using of Session Issues in Meteor JS? I need to know about the Sessions.Actually we using default sessions like session.set(key,value) and session.get(key). In this default session are cleared some cases like refresh and etc.
First i am using meteor add u2622:persistent-session Pkg.Use of this pkg gets one error i.e "Uncaught Error: Meteor does not currently support objects other than ObjectID as ids".
To overcome those problems to use amplify Sessions. But did one sample to using amplify Sessions as shown below code :
Js Code :
Messages = new Meteor.Collection("messages");
if (Meteor.isClient) {

  var AmplifiedSession = _.extend({}, Session, {
    keys: _.object(_.map(amplify.store(), function (value, key) {
      return [key, JSON.stringify(value)];
    })),
    set: function (key, value) {
      Session.set.apply(this, arguments);
      amplify.store(key, value);
    }
  });

  // counter starts at 0
  Session.setDefault('counter', 0);
  AmplifiedSession.set('no', 1);

  Template.hello.helpers({
    counter: function () {
      return Session.get('counter');
    }
  });

  Template.hello.helpers({
    no: function () {
      return AmplifiedSession.get('no');
    }
  });

  Template.hello.events({
    'click button': function () {
      // increment the counter when button is clicked
      console.log("Btn Clicked");
      Session.set('counter', Session.get('counter') + 1);
      AmplifiedSession.set('no',AmplifiedSession.get('no') + 1);
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup

  });
}

Even not working.amplify Sessions also cleared at the time of Refresh.I didn't get any idea about this.So please suggest me what to do for this.
Thanks in Advance.

A: Try this package on atmosphere and let me know if it helped.
meteor add u2622:persistent-session

A: In this particular example, on every page load, you are running AmplifiedSession.set('no', 1);, therefore setting 'no' to be 1.  This is why on page refreshes, 'no' is getting set to 1.  Remove this line, and then change this line AmplifiedSession.set('no',AmplifiedSession.get('no') + 1); to set the value of 'no' if it does not exist.


text:
Q: is NUnit bad choice for Selenium test? I have read umpteen answers on SO while searching for NUnit + dependent methods + order of test execution. Every single answer suggests that forcing any set of order for unit tests is extremely evil.
I am writing Selenium tests using NUnit.
So I am trying to write integration tests using Unit testing framework!!!
To cite an example of integration tests (and this is just one example). I need to create a valid account before proceeding with other tests. If creation of account fails then I would like to abort entire test execution.
Since I don't want to rely on alphabetic order of test and in true spirit of NUnit, decided to create an account before any further test. Though it does not look right to me for two core reasons -

*

*Unnecessary code duplication/execution

*What if application account creation is not working, all my tests would still try to create and account again and again and failing

I am inclined to think that NUnit may be not be right deal with Selenium tests.
But if not Nunit then what should I use?

A: Selenium Core itself comes with a TestRunner that is written in Javascript and you can run your tests directly from the browser.
For more see:
http://www.developerfusion.com/article/84484/light-up-your-development-with-selenium-tests/
Apart from that, using Nunit and tests written in C# are much more easier to write and maintain. Are you using SetUp and TearDown while writing your tests? That way you can avoid code duplication.
Regarding you second point, you can have a flag that is set on first setup failure and skips the setup the next time or the setup itself tracking it and quickly failing the next time. And tests don't run if setup fails in Nunit.

A: I run Selenium with NUnit all the time. It just depends on how you write your tests. To avoid code duplication, I make a library of helper functions that do common things, like log in or log out of my site, that the other tests use to get to the page they need to test. (I use the term 'library' in a loose sense; I don't actually split them into their own C# project.)
You are right that if the account creation function is broken, the other tests will fail. But personally, I don't see that as a problem, as the point of unit tests is to make sure that your changes didn't have unintended effects elsewhere in your project. If the account creation broke, clearly that affects a lot of things. Ditto if my login helper method fails: if you can't log in, you can't get to anything in the site. Effectively, the whole site is broken.

A: If you need to create new accounts on each test then the approach that I would take is to have that code moved into your SetUp code. If some of your tests don't require login, split them out into different files.
Any bits of duplcation should be removed, test code should be as clean and robust as production code. Splitting the files with different tests help maintain the idea of Single Responsibility.

A: Did you also look at PNunit?
See one of the anwers in this question:
Has anyone found a way to run C# Selenium RC tests in parallel?
I'm still not 100% sure how TestNG would work with grid, suppose you have a 3-step registration process and you divide this up in 3 tests. Is TestNG with grid going to help you here? I suppose not, or will it detect that test C needs to have test A and B runned on the same thread?
PNunit looks like it could provide a way to distribute dependent tests to the same machine. Although it's probably quite complicated to set up.

A: Two approaches might help you, with the problem you describe as an answer to AutomatedTester:
First, NUnit 2.4.4 defines a SuiteAttribute that lets you run tests in the order you want. Very handy but it has a major restriction: it is not compatible with TestCaseAttribute. That means all your tests have to be triggered only by TestAttribute; which is very annoying if you target coverage of value-based boundary tests (thus several data-driven test cases). More info on http://www.nunit.org/index.php?p=suite&r=2.5.10
Another approach is to prepare an integration sample database tailored just for your test cases. Say you have a 15-steps registration process: create a student record and push it to step one, then another student and push it to step two, and so on. Save your database and restore it as test fixture setup. Then test each step with a different student.
It is perfectly valid in most cases to do integration tests on different records for each step, as it provides the same functionwise and codewise coverage, and it follows the idea of integration testing because your records in the DB are true records (created by the UI with all flaws that comes with the UI).
Of course it needs more time to run and storage space because of the DB copies you'll have to store. If your system can't afford that, then you'll probably want to look at the first solution.
It also gives you the advantage of being able to spot bugs on later steps even if earlier steps are unstable: all tests are run on each test campaign which is not the case in the solution you ask for.


text:
Q: add class for selected radio button in thymeleaf I am new to Thymeleaf. I am trying to add a class based on the selected radio button in a for loop.

            <input type="radio" autocomplete="off"  th:field="*{nature}"  th:value="${obj}" />
            Radio

what test should I be making to compare the value of "nature" against the value of loop variable "obj", in order to add the "active" class in th:classappend?
Thank you.

A: did you try th:classappend="(${obj} eq *{nature})? 'active'"
if *{nature} is a String try th:classappend="(${obj.name()} eq *{nature})? 'active'"


text:
Q: what happen to the messages when connection is down between kafka server and producer? i m new in kafka using spring boot and i m working in projet that i want to integrate kafka using spring into it ,
so the problem is i want to send message from the producer to the consumer even if the kafka server don't running(offline mode)
Can anyone give me example of how using kafka in offline mode ,
i can't find a tuto for this topic
i want to stop my kafka server(for example) and in the same time producer want to send data to the topic,then the consumer can get these message?
what's the best solution?are they true ?
*sending data to a file, and when the server return to run (i test connexion for example),i export data from the file to the topic
*sending data to database and when the server return to run (test connexion),the same i send message(data) from database to my topic
*using a queue or a list to store message and when the server return to run (test connexion),i send data from the list to the topic but the problem that i have a lot of messages
-->if there are other solution with a simple example ,can anyone help me?
this is example of brocker Redis that we test the connection between Redis brocker and producer , if connection fails, i will store data inside a Queue which can store many messages, and when connection return to work between Redis and producer ,the producer now get these messages from the Queue and send them to the Redis Brocker .
But the problem in this brocker ,there are a few message lost
so we decide to integrate kafka brocker inside my project instead of Redis brocker!
Can anyone give me example in java how to store a lot of message before sending them by producer to kafka cluster?or what's the best solution to this problem  because we don't want to use the same Queue solution?
this example in python is how store message inside a Queue if connexion failed to the server:
    try:
    urllib.request.urlopen('http://serverAdress', timeout=0.1)
    r.publish(topicProduction,json_background_of_message1)
    print(json_background_of_message1)
    arretControle=Tru
    except Exception as e:
    qArret.put(json_background_of_message1)
    print("arret")
    arretControle=True

//json_background_of_message1 is the Queue that we can store a lot of messages in this Queue before sending these message if the connexion is failed

A: Kafka is designed to be a highly-available messaging system.  Configured correctly, and depending on the replication factor, you can have multiple brokers go down, completely, for days at a time, and the cluster would still work (albeit under higher load probably).  Every single Kafka production cluster I've worked with hasn't been completely down, ever, once it was successfully deployed.  We've had individual brokers go down, for days at a time sometimes, but that was never a problem.
What you're proposing is a fallback or backup method, in case Kafka is not available.  However, you still have the same problem.  If you dump messages to a file, how long until you run out of disk space?  If you store messages in a database, how long until the database runs out space?  If you store messages in an in-memory queue, how long until you run out of memory, and crashes the application?  And now you also have to build a mechanism to recover from a kafka outage, which adds complexity and overhead.
The best approach with Kafka is to configure it and handle it as a highly-available-system, configure alerts and metrics properly, so you'll be immediately alerted, and can react promptly, if something goes wrong.  Also, you should always size and test your applications so you have enough headroom to handle even your worst case scenario.  If you configure it to use replication factor 3, you would be able to lose any two brokers, and the cluster would still be able to function with no data loss.
Now, on the application side, your behavior in case Kafka is unavailable should depend on how important the messages are.  If you can tolerate losing messages, then just drop them if producer returns an exception, and log it/send an alert.  However, if they're extremely important records, then you shouldn't acknowledge/commit the messages on your upstream system (wherever the records originated from) until you have full confirmation that they're saved in Kafka.  I would recommend setting producer acks to -1 or all for this, multiple retries in case of failure, and setting up a proper Callback method on the producer.send() method.  See here for much more detailed explanation: https://kafka.apache.org/21/javadoc/index.html?org/apache/kafka/clients/producer/Callback.html
For more details, like others have said, please give the official docs a read:  https://kafka.apache.org/documentation/


text:
Q: VB.net How to remove quotes characters from a streamReader.readline.split() I had built a project that read data from a report and it used to work fine but now for some reason the report puts every thing in to strings. So I want to modify my stream reader to remove or ignore the quotes as it reads the lines.
This is a snipet of the part that reads the lines.
Dim RawEntList As New List(Of Array)()

Dim newline() As String
Dim CurrentAccountName As String
Dim CurrentAccount As Account
Dim AccountNameExsists As Boolean
Dim NewAccount As Account
Dim NewEntry As Entrey
Dim WrongFileErrorTrigger As String

ListOfLoadedAccountNames.Clear()
'opens the file
Try
    Dim sr As New IO.StreamReader(File1Loc)
    Console.WriteLine("Loading full report please waite")
    MsgBox("Loading full report may take a while.")
    'While we have not finished reading the file
    While (Not sr.EndOfStream)
        'spliting eatch line up into an array
        newline = sr.ReadLine.Split(","c)
        'storring eatch array into a list
        RawEntList.Add(newline)
    End While

And then of course I iterate through the list to pull out information to populate objects like this:
For Each Entr In RawEntList
    CurrentAccountName = Entr(36)
    AccountNameExsists = False
    For Each AccountName In ListOfLoadedAccountNames
        If CurrentAccountName = AccountName Then
            AccountNameExsists = True
        End If
    Next

A: You could just do
StringName.Replace(ControlChars.Quote, "")

or
StringName.Replace(Chr(34), "")

OR
streamReader.readline.split().Replace(Chr(34), "")

A: How about doing the replace before the split, after the readline? That should save iteration multiplication, or better yet (if possible), do a replace on the entire file (if the data is formatted in the way it can be done & you have enough memory) using the ReadAllText method of the File object, do your replace, then read the lines from memory to build your array (super fast!).
File.ReadAllText(path)


text:
Q: Can an Eloquent Relationship automatically include its reverse on the child? I have an Eloquent (Laravel 5.1) relationship like:
class Form extends Model {

  public function fields(){
    return $this->hasMany('App\Models\Field');
  }

}

class Field extends Model {

  public function form(){
    return $this->belongsTo('App\Models\Form');
  }

  public function getFullTitleAttribute(){
    return $this->form->title . ', ' . $this->title;
  }

}

I have a several processes that look up a Form, then for each Field, do something with the full_title attribute (which depends on the Field's Form), e.g.,
$form = Form::first();
foreach($form->fields as $field){
  echo $field->full_title . "\n";
}

The problem is that every Field makes a database query to look up the Form, it's a ton of unnecessary traffic.
Is there a way to update the relationships so that the Field object already has an in-memory link to the Form object that brought it into being?

A: The sloppy solution I'm using is, everywhere I use the Form->fields relationship, I explicitly tell the fetched Fields about their Form:
$form = Form::first();
foreach($form->fields as $field){
  $field->setRelation('form', $form);  // Saved you a query
  echo $field->full_title . "\n";
}

It's more performant, but it doesn't seem very... Eloquent.


text:
Q: Let $V = C[0, 1]$ and define an operator $T: V \rightarrow V$ by the following formulas for $T(f)$ as a function of the variable $x$. I am reading the book, Applied Linear Algebra and Matrix Analysis.
When I was doing the exercise of Section3.1 Exercise 13, I was puzzled at some answers of it.
Here is the problem description:

Let $V = C[0, 1]$ and define an operator $T: V \rightarrow V$ by the
following formulas for $T(f)$ as a function of the variable $x$.
Which of these operators is linear?
If so, is the target V of the operator equal to its range?
$(a)f(1)x^2$ $(b)f^2(x)$
$(c)2f(x)$ $(d)\int^x_0f(s)ds$

I think (a)$f(1)x^2$ is not linear just because:
$g(u) = f(1)u^2,\ g(v) = f(1)v^2 \\
g(cu) = f(1)c^2u^2 = c^2f(1)u^2 \\
cg(u) = cf(1)u^2 \neq g(cu) \\$
The range is $V$ and here is my derivation:
$\because V = C[0, 1] \\
\therefore x, f(x) \in C[0,1] \\
\therefore f(1) \in C[0,1] \\
\therefore f(1)x^2 \in C[0,1]$
But the answer of it is:

$(a)$linear,range not $V$ $(b)$ not linear, $(c)$ linear, range is $V (d)$
linear, range not $V$

So the answer of (a) is not like what I thought before.
I think the range of $(c)2f(x)$ is not $V$.
Also I think the range of $(d)\int^x_0f(s)ds$ is $V$ because the integral of $f(s)$ on the range$[0,x]$ is a area which is less than or equal to a area consisting of (0, 0) and (1, 1).
If not mind, could anyone tell my thoughts is right or not and give me some advice on how to determine it is the linear operator and its range on such questions?

A: The operator is linear if and only if $T(f+g)$ is the same function as $T(f)+T(g)$. To determine whether this is true, you need to calculate, for a pair of function $f,g$, what the function $T(h+g)$ is, and what $T(f)+T(g)$ is.

The function $T(f)$ maps $x$ to $f(1)\cdot x^2$, and the function $T(g)$ maps $u$ to $g(1)\cdot x^2$.
The function $T(f+g)$, therefore, maps $u$ to $(f+g)(1)\cdot x^2$.
Can you continue from here? Remember:

*

*in $V$, the definition of addition is such that $(f+g)(x)=f(x)+g(x)$, which should help you calculate $(f+g)(1)$.

*From that, you can write, in terms of $f$ and $g$, where $T(f+g)$ maps $x$.

*Then compare that to where $T(f)+T(g)$ maps $x$ (use rule from point 1 again)

A: Linear means $T(af+bg)(x)=aTf(x)+bTg(x)$. (You don't change $x$ to $cx$; you only change $f$ to $cf$ etc). It should now be clear that b) is not linear and the other three are linear. The range in a) and d) are functions with some special properties: in a) they vanish at $0$ and in d) they are differentiable. So the range is not $V$ in these cases. It is clear that the range is $V$ in c).


text:
Q: Create vector from loop in R I'm basically trying to create a vector of NA's and numbers but in a very particular order.  Here's the code I have so far:
x<-rep(rep(2:1,c(2,3)),40)
dummy=1
for (i in 0:length(x))
{ ifelse(x[i+1]==2, print(NA), print(dummy))
 if(i %% 5 == 0) dummy=i+1
}

So my vector should look as follows (NA, NA, 1, 1, 1, NA, NA, 6, 6, 6, etc).  However I cannot save this in this format so I can call it later in a matrix.  Any suggestions?  I have tried creating a vector of nothing and then filling it in the loop but that has worked with no avail either.
Liz
Statistics Student

A: After alot of stubbornness on my part I have learned to vectorize these things completely, not sure if this helps in your particular situation but I would write:
x<-rep(rep(2:1,c(2,3)),40)

get the lead of your x with:
leadx=c(x[-1],NA)

write the numbers that you would get if there were no NAs
filler=rep(5*0:7+1,each=5)

get a vector with the right size filled in with NAs
y=rep(NA,length(x))

plug in the values of the filler into your NA vector
y[which(leadx!=2)]=filler[which(leadx!=2)]

check it out with:
head(y)

> [1] NA  1  1  1 NA NA  6  6  6 NA

Vectorized stuff tends to be faster than for loops and if statements. Good luck!
Edit: You can do it all in one line with:
y=ifelse(c(x[-1],NA)==2,NA,1)*rep(5*0:7+1,each=5)

A: You need to assign your vector to something, rather than calling print, otherwise it will print to standard out.
out <- vector(length=length(x))

for (i in 0:length(x)) {
  out[i] <- ifelse(x[i+1]==2, NA, dummy)
  if(i %% 5 == 0) dummy=i+1
}

> head(out, 10)
 [1] NA  1  1  1 NA NA  6  6  6 NA
>


text:
Q: Go does not support operator overloading, but how do I explain the time package I have been doing the Go tour for a while now and I just noticed this line of code:-
today := time.Now().Weekday()
    switch time.Saturday {
    case today + 0:
        fmt.Println("Today.")
    case today + 1:
        fmt.Println("Tomorrow.")
    case today + 2:
        fmt.Println("In two days.")
    default:
        fmt.Println("Too far away.")
    }

If Go does not support operator overloading how is that I can use the '+' operator to increment the day?

A: time.Now().Weekday() returns a value of type time.Weekday, which is an int. today+1 works, because 1 is an untyped constant, and its type is determined based on context. In this context, both today and 1 are of type time.Weekday.
Also note that because of the way it is defined, time.Saturday is 6,
so time.Saturday == today+2 works, but time.Saturday+2 is not going to match any valid weekday.

A: I'm not sure about your problem, but I think you can pay attention to the time package. It's powerful.
There are many time types in go, such as time.weekday, time.duration, and time.month. They support the + operator, because their underlying type is numeric, but time.Time is not supported. Its underlying type is structure. We can use the method of time.Time for operation, such as Time.add, Time.sub, Time.adddate, Time.after, Time.before, Time.equa You can use Time.unix or Time.unixnano to get the Time stamp of numerical type for operation.
As an example, I implemented two methods to calculate the time from a certain time to the next week and the deviation from the current time.
import (
    "time"
)

func NextWeekdayTime(now time.Time, weekday time.Weekday) time.Time {
    return now.AddDate(0, 0, NextWeekdayNum(now, weekday))
}

func NextWeekdayNum(now time.Time, weekday time.Weekday) int {
    diff := (weekday - now.Weekday()) + 7
    if diff >= 7 {
        diff -= 7
    }

    return int(diff)
}


text:
Q: steps for upgrading sharepoint 2013 to service pack1 I want to upgrade my SHAREPOINT 2013 RTM version to SERVICE PACK1. Also, i have to upgrade my sql server 2012 to  SP2 version. so i have completed the sql server  upgrade from 2012 to 2012 service pack2.
MY current Version Number of SP 2013 is 15.0.4420.1017

Now, how can i upgrade SHAREPOINT 2013 TO SERVICE PACK1 ?
should i upgrade by directly running the sharepoint 2013 SP1 ISO FILE?
or
should i just run the SP1 EXE thats freely available from msft download center?
i have attached my current SP 2013 version number:

A: As you know Service Pack 1 is a mandatory requirement for installing any subsequent SharePoint 2013 cumulative updates as the new baseline!
In your case, you just need to install the Service Pack 1 over SharePoint 2013 RTM from Service Pack 1 for Microsoft SharePoint Server 2013 (KB2880552)

A: If you are using SharePoint 2013 foundation download from this link
Service Pack 1 for Microsoft SharePoint Foundation 2013 (KB2880551)
If you are using SharePoint 2013 Server download from this link
Service Pack 1 for Microsoft SharePoint Server 2013 (KB2880552)
The installation package is 1.3 GB for Server and 403 MB for Foundation. Ensure you have the necessary disk space available before downloading.
Run the exe and then run the SharePoint 2013 Products Configuration Wizard.
Once done, you need to verify the build number to be absolutely certain that the installation was successfull.
To do that, Open Central Admin > Manage servers in the farm.
The Configuration database version should read 15.0.4571.1502
Reference - Install SP 2013 SP1

A: Upgrade the SharePoint environment required some planning as it will have impact on the environment. As per my experience I would do it following way

*

*apply SP 1 in lower farm and do the testing and make sure the all functionality you are using working after the upgrade.once satisfied

*plan a date and time as it will cause outage for end user

*before start take a full backup of sharepoint farm, once sp1 installed you can't uninstall it, so in case of disaster you can recover it without losing data

*now download the SharePoint Sp1 from MSFT site the exe file you don't need to run ISO file as it is complete sharepoint package but you just need the sp1

*install SP1 on all sharepoint servers.once completed.then

*Run sharepoint config wizard on all servers in the farm.it should be one server at a time. I would start from central admin server.once done

*now test your farm, functionality, build number etc

Hope this help

A: One thing wasn't mentioned in previous answers: If you have installed a SharePoint LanguagePack, you also have to install the LanguagePack SP1. Install it directly after SharePoint SP1 binaries for each language and then execute ProductsConfiguration Wizard.
If You already installed SP1 without LP-SP1, you can install it afterwards. Please remember to also run ProductsConfig Wizard.
PS: If you forget to install LP-SP1, you won't be able to install any following CumulativeUpdates. You will get a very generic error during Update-Detection ("Update not applicaple to your system"), so this situation is hard to identify.


text:
Q: Stretched datacenter between cities We're planning to implement a stretched datacenter between our two sites. The connectivity between them is a single 100mbit QinQ connection. We have about 500 users at site A and 200 users at site B. There is a very low amount of traffic being generated on the link.
Disclaimer: I won't go through the replication, as it's a different story. We have SAN replication ready in a few months. L3 routing etc is also not an issue, as we know how to do this.
The network plan (right now) is the following:

*

*VLAN 300: Site A+B - 172.16.0.0/24 - management (switches, routers, vsphere etc)

*VLAN 310: Site A+B - 10.50.0.0/24 - shared servers for clients at either site

*VLAN 311: Site A(+B) - 10.51.0.0/24 - servers for clients at site A

*VLAN 312: Site B(+A) - 10.52.0.0/24 - servers for clients at site B

*VLAN 320: Site A - 192.168.0.0/24 - clients in the site A building

*VLAN 321: Site B - 192.168.10.0/24 - clients in the site B building

The general idea here is that services with HA/site awareness (AD, DFS, Exchange, Lync and so on) lives in VLAN 311 for site A and VLAN 312 for site B. This is simply to ensure that all clients are using the services closest to them, to prevent a bad user experience if the L2 link between the sites should go down. We will be using a single AD domain.
Servers that do not have any kind of HA built in should be put in VLAN 310, wich is active at both sites simultaneously. This way we can do a SAN replica failover of a specific LUN and bring up the VM's at the opposite site in case of disaster.
Questions

*

*Should I stop over-engineering stuff and rather do a completely flat design, with 3 VLAN's (one mgmt, one server and one client)? I'll lose site awareness, but it'll simplify the setup and management a great deal

*Will vSphere break my heart if I try to implement two different clusters on the same logical network?

*Will anything else break my heart? What are major gotchas/cons/prons?

A: I think having site aware setup it better:
1) You don't want to vMotion or storage vMotion across a 100 Mbit link.
2) It would be beneficial for users to use the DC located in their building
3) As time progresses, more & more data will travel over your 100 Mbit link.
4) Plan on what will happen should the link be down for an extended period of time.
That said, you can implement 2 different clusters on the same logical network.


text:
Q: Toggle Search Input Autofocus I am running a script when the search icon is clicked the search input is displayed with toggle but I cannot get this running so that the input autofocus is active so the user can type straight into the search box
    $(document).ready( function(){
         $("#velaSearchTop").each( function(){
            $("#velaSearchIcon").click( function(){
                 $("#velaSearchbox").toggleClass("show");
             });
            $(".btn-close").click( function(){
                 $("#velaSearchbox").removeClass("show");
             });
         });
    });
</script>

    <form id="velaSearchbox" class="formSearch" action="/search" method="get">
        <input type="hidden" name="type" value="product">
        <input class="velaSearch form-control" class="test" type="search" name="q" value="{{ search.terms | escape }}" placeholder="{{ 'general.search.placeholder' | t }}" autofocus />
        <button id="velaSearchButton" class="btnVelaSearch" type="submit" >

            {{ 'general.search.submit' | t }}
        </button>

    </form>

```

A: If you're using jquery.js you can write like this
$(function () {
    $("#velaSearchIcon").click(function () {
        $("#velaSearchbox").show();
        $("input[name='q']").focus();
    });
    $(".btn-close").click(function () {
        $("#velaSearchbox").hide();
    });
});


text:
Q: Convert Dictionary to String I have
  dic = {'value': '123','sort': 'desc','type': 'float'}

I want it become string like:
 str = 'value=123&sort=desc&type=float'

How can I do it?
Thanks

A: Like this:
>>> d = {'value':'123','sort':'desc','type':'float'}
>>> "&".join(["{}={}".format(k, v) for k, v in d.items()])
'sort=desc&type=float&value=123'
>>>

As pointed out in many of the comments; if this is for a HTTP Request, use the urllib.urlencode function.
>>> from urllib import urlencode
>>> urlencode(d)
'sort=desc&type=float&value=123'
>>>

A: Can also be done with urllib
import urllib
d = {'value':'123','sort':'desc','type':'float'}
urllib.urlencode(d)
'sort=desc&type=float&value=123'

A: This wont work with dictionaries if you care about the order of the string elements since the items are not stored in a specific order. Use OrderedDict instead.
Unless the resulting string has always the same format so you could use the format notation
>>> dic={'value':'123','sort':'desc','type':'float'}
>>> str='value={value}&sort={sort}&type={type}'.format(**dic)

A: dic={'value':'123','sort':'desc','type':'float'}
str=''
for i in dic:
    str = str + i + '=' + dic[i] + '&'
str[:-1]

Or with list comprehension and reduce:
reduce(lambda x,y: x+y, [i+'='+dic[i]+'&' for i in dic])[:-1]


text:
Q: C++ lambda ambiguous call I am trying to have two eachPixel functions. One returns an image, and the other returns nothing. I'm getting "call to eachPixel is ambiguous"  even though I am specifying the return type of the lambda.
How can I resolve the ambiguity?
// this one does not return an image
void eachPixel(const QImage &image, const std::function <void (uint)>& pixelFunc, const QRect &bounds=QRect()) {
...

    for (int y=region.y(); y<=region.bottom(); y++) {
        for (int x=region.x(); x<=region.right(); x++) {
            pixelFunc(image.pixel(x,y));
        }
    }
}

// This one returns an image
QImage eachPixel(const QImage &image, const std::function <uint (uint)>& pixelFunc, const QRect &bounds=QRect()) {
...

    QImage out(image.size(), image.format());
    for (int y=region.y(); y<=region.bottom(); y++) {
        for (int x=region.x(); x<=region.right(); x++) {
            out.setPixel(x,y, pixelFunc(image.pixel(x,y)));
        }
    }
    return out;
}

void test_pixelFunc() {
    QImage image(300,200, QImage::Format_ARGB32);
    image.fill(Qt::blue);

    QImage out = eachPixel(image, [] (uint p) -> uint { //uint specified!!
        return qRgb(qRed(p), qBlue(p), qGreen(p)); // swap green and blue channels
    }, QRect (0,0, 300, 200));
    out.save("test_pixelfunc.png");

    int accumulator=0;
    eachPixel(image, [&accumulator](uint p) -> void { // void specified!
        accumulator++;
    }, QRect (0,0, 300, 200));
    qDebug() << "accumulator" << accumulator;

};

A: You can use templates and SFINAE on the return type of the function you pass in.
#include <iostream>
#include <functional>

template <typename T, std::enable_if_t<std::is_same_v<void, decltype(std::declval<T>()(1))>, int> = 0>
void foo (T f) {
    // std::function<void(int)> func = f;
    // if you really need a std::function
    f(1);
}

template <typename T, std::enable_if_t<std::is_same_v<int, decltype(std::declval<T>()(1))>, int> = 0>
int foo (T f) {
    return f(1);
}

int main() {
    foo([](int x) { std::cout << "void " << x << '\n'; });

    foo([](int x) { std::cout << "int\n"; return x; });
}

For c++11 you can use std::is_same and std::enable_if directly.
template <typename T, typename std::enable_if<std::is_same<void, decltype(std::declval<T>()(1))>::value, int>::type = 0>
void foo (T f) {
    f(1);
}

template <typename T, typename std::enable_if<std::is_same<int, decltype(std::declval<T>()(1))>::value, int>::type = 0>
int foo (T f) {
    return f(1);
}

A: You can add ignored parameter to one of lambdas to help resolve ambiguity:
struct noreturn_tag {};
void foo( std::function<void(int,noreturn_tag)>);
void foo( std::function<int(int)>);

int main() {
    foo( []( int ) { return 0; } );
    foo( []( int, noreturn_tag ) {} );
}

live example


text:
Q: What is the point of clog? I've been wondering, what is the point of clog? As near as I can tell, clog is the same as cerr but with buffering so it is more efficient. Usually stderr is the same as stdout, so clog is the same as cout. This seems pretty lame to me, so I figure I must be misunderstanding it. If I have log messages going out to the same place I have error messages going out to (perhaps something in /var/log/messages), then I probably am not writing too much out (so there isn't much lost by using non-buffered cerr). In my experience, I want my log messages up to date (not buffered) so I can help find a crash (so I don't want to be using the buffered clog). Apparently I should always be using cerr.
I'd like to be able to redirect clog inside my program. It would be useful to redirect cerr so that when I call a library routine I can control where cerr and clog go to. Can some compilers support this? I just checked DJGPP and stdout is defined as the address of a FILE struct, so it is illegal to do something like "stdout = freopen(...)".

*

*Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr?

*Is the only difference between clog and cerr the buffering?

*How should I implement (or find) a more robust logging facility (links please)?

A: Since there are several answers here about redirection, I will add this nice gem I stumbled across recently about redirection:
#include <fstream>
#include <iostream>

class redirecter
{
public:
    redirecter(std::ostream & dst, std::ostream & src)
        : src(src), sbuf(src.rdbuf(dst.rdbuf())) {}
    ~redirecter() { src.rdbuf(sbuf); }
private:
    std::ostream & src;
    std::streambuf * const sbuf;
};

void hello_world()
{
    std::cout << "Hello, world!\n";
}

int main()
{
    std::ofstream log("hello-world.log");
    redirecter redirect(log, std::cout);
    hello_world();
    return 0;
}

It's basically a redirection class that allows you to redirect any two streams, and restore it when you're finished.

A:
Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr?

Yes. You want the rdbuf function.
ofstream ofs("logfile");
cout.rdbuf(ofs.rdbuf());
cout << "Goes to file." << endl;

Is the only difference between clog and cerr the buffering?

As far as I know, yes.

A: Redirections
Konrad Rudolph answer is good in regard to how to redirect the std::clog (std::wclog).
Other answers tell you about various possibilities such as using a command line redirect such as 2>output.log. With Unix you can also create a file and add another output to your commands with something like 3>output.log. In your program you then have to use fd number 3 to print the logs. You can continue to print to stdout and stderr normally. The Visual Studio IDE has a similar feature with their CDebug command, which sends its output to the IDE output window.

stderr is the same as stdout?

This is generally true, but under Unix you can setup the stderr to /dev/console which means that it goes to another tty (a.k.a. terminal). It's rarely used these days. I had it that way on IRIX. I would open a separate X-Window and see errors in it.
Also many people send error messages to /dev/null. On the command line you write:
command ...args... 2>/dev/null

syslog
One thing not mentioned, under Unix, you also have syslog().
The newest versions under Linux (and probably Mac OS/X) does a lot more than it used to. Especially, it can use the identity and some other parameters to redirect the logs to a specific file (i.e. mail.log). The syslog mechanism can be used between computers, so logs from computer A can be sent to computer B. And of course you can filter logs in various ways, especially by severity.
The syslog() is also very simple to use:
syslog(LOG_ERR, "message #%d", count++);

It offers 8 levels (or severity), a format a la printf(), and a list of arguments for the format.
Programmatically, you may tweak a few things if you first call the openlog() function. You must call it before your first call to syslog().
As mentioned by unixman83, you may want to use a macro instead. That way you can include some parameters to your messages without having to repeat them over and over again. Maybe something like this (see Variadic Macro):
// (not tested... requires msg to be a string literal)
#define LOG(lvl, msg, ...) \
     syslog(lvl, msg " (in " __FILE__ ":%d)", __VA_ARGS__, __LINE__)

You may also find __func__ useful.
The redirection, filtering, etc. is done by creating configuration files. Here is an example from my snapwebsites project:
mail.err /var/log/mail/mail.err
mail.* /var/log/mail/mail.log
& stop

I install the file under /etc/rsyslog.d/ and run:
invoke-rc.d rsyslog restart

so the syslog server handles that change and saves any mail related logs to those folders.
Note: I also have to create the /var/log/mail folder and the files inside the folder to make sure it all works right (because otherwise the mail daemon may not have enough permissions.)
snaplogger (a little plug)
I've used log4cplus, which, since version 1.2.x, is quite good. I have three cons about it, though:

*

*it requires me to completely clear everything if I want to call fork(); somehow it does not survive a fork(); call properly... (at least in the version I had it used a thread)

*the configuration files (.properties) are not easy to manage in my environment where I like the administrators to make changes without modifying the original

*it uses C++03 and we are now in 2019... I'd like to have at least C++11

Because of that, and especially because of point (1), I wrote my own version called snaplogger. This is not exactly a standalone project, though. I use many other projects from the snapcpp environment (it's much easier to just get snapcpp and run the bin/build-snap script or just get the binaries from launchpad.)
The advantage of using a logger such as snaplogger or log4cplus is that you generally can define any number of destinations and many other parameters (such as the severity level as offered by syslog()). The log4cplus is capable of sending its output to many different places: files, syslog, MS-Windows log system, console, a server, etc. Check out the appenders in those two projects to have an idea of the list of possibilities. The interesting factor here is that any log can be sent to all the destinations. This is useful to have a file named all.log where all your services send their logs. This allows to understand certain bugs which would not be as easy with separate log files when running many services in parallel.
Here is a simple example in a snaplogger configuration file:
[all]
type=file
lock=true
filename=/var/log/snapwebsites/all.log

[file]
lock=false
filename=/var/log/snapwebsites/firewall.log

Notice that for the all.log file I require a lock so multiple writers do not mangle the logs between each others. It's not necessary for the [file] section because I only have one process (no threads) for that one.
Both offer you a way to add your own appenders. So for example if you have a Qt application with an output window, you could write an appender to send the output of the SNAP_LOG_ERROR() calls to that window.
snaplogger also offers you a way to extend the variable support in messages (also called the format.) For example, I can insert the date using the ${date} variable. Then I can tweak it with a parameter. To only output the year, I use ${date:year}. This variable parameter support is also extensible.
snaplogger can filter the output by severity (like syslog), by a regex, and by component. We have a normal and a secure component, the default is normal. I want logs sent to the secure component to be written to secure files. This means in a sub-directory which is way more protected than the normal logs that most admins can review. When I run my HTTP services, some times I send information such as the last 3 digits of a credit card. I prefer to have those in a secure log. It could also be password related errors. Anything I deem to be a security risk in a log, really. Again, components are extensible so you can have your own.

A: One little point about the redirecter class. It needs to be destroyed properly, and only once. The destructor will ensure this will happen if the function it is declared in actually returns, and the object itself is never copied.
To ensure it can't be copied, provide private copy and assignment operators:
class redirecter
{
public:
    redirecter(std::ostream & src, std::ostream & dst)
        : src_(src), sbuf(src.rdbuf(dst.rdbuf())) {}
    ~redirecter() { src.rdbuf(sbuf); }
private:
    std::ostream & src_;
    std::streambuf * const sbuf_;
    // Prevent copying.
    redirecter( const redirecter& );
    redirecter& operator=( const redirecter& );
};

I'm using this technique by redirecting std::clog to a log file in my main(). To ensure that main() actually returns, I place the guts of main() in a try/catch block. Then elsewhere in my program, where I might call exit(), I throw an exception instead. This returns control to main() which can then execute a return statement.

A: If you're in a posix shell environment (I'm really thinking of bash), you can redirect any
file descriptor to any other file descriptor, so to redirect, you can just:
$ myprogram 2>&5

to redirect stderr to the file represented by fd=5.
Edit: on second thought, I like @Konrad Rudolph's answer about redirection better.  rdbuf() is a more coherent and portable way to do it.
As for logging, well...I start with the Boost library for all things C++ that isn't in the std library.  Behold: Boost Logging v2
Edit: Boost Logging is not part of the Boost Libraries; it has been reviewed, but not accepted.
Edit: 2 years later, back in May 2010, Boost did accept a logging library, now called Boost.Log.
Of course, there are alternatives:

*

*Log4Cpp (a log4j-style API for C++)

*Log4Cxx (Apache-sponsored log4j-style API)

*Pantheios (defunct?  last time I tried I couldn't get it to build on a recent compiler)

*Google's GLog (hat-tip @SuperElectric)

There's also the Windows Event logger.
And a couple of articles that may be of use:

*

*Logging in C++ (Dr. Dobbs)

*Logging and Tracing Simplified (Sun)

A: Basic Logger
#define myerr(e) {CriticalSectionLocker crit; std::cerr << e << std::endl;}

Used as myerr("ERR: " << message); or myerr("WARN: " << message << code << etc);
Is very effective.
Then do:
./programname.exe 2> ./stderr.log
perl parsestderr.pl stderr.log

or just parse stderr.log by hand
I admit this is not for extremely performance critical code. But who writes that anyway.


text:
Q: mouse_move_to DEPRECATED ruby selenium cucumber I am new to Selenium and want to hover over Category button then click the Subcategory in provided drop down. I used 'mouse_move to' command before but now it says: WARN Selenium [DEPRECATION] Driver#mouse is deprecated. Use driver.action..perform instead.
I tried this code changing 'mouse' to 'action' and 'click' to 'perform' but it doesn't work.
 element = $driver.find_element :xpath => "//span[@class = 'ls_2px' and text() = 'Accessories']"
  $driver.mouse.move_to element
 element = $driver.find_element :xpath => "(//div[@class = 'vt'][.//a[text() = 'View All']]//a[0])"
  element.click
 end

Do I need to add WebDriver::W3CActionBuilder to my env file?
I have only this:
require 'rubygems'
require 'selenium-webdriver'
require 'cucumber'
$driver = Selenium::WebDriver.for :chrome
$dropdown = Selenium::WebDriver::Support::Select

A: driver.action.move_to(element).perform should work in this case for Hover.
Resource: Class: Selenium::WebDriver::ActionBuilder - move_to


text:
Q: If CancellationToken is a struct and is passed by Value, how is it updated? I see that CancellationToken is a struct
https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken?view=netframework-4.7.1
If I pass a struct to a new function by value, it shouldn't be modified in the caller. So if i'm passing a CancellationTokenSource (by value), then I call cts.cancel(), how does the method that has a copy of that token is notified that it has been canceled? Shouldn't it work only if we pass by reference?
For example:
public static void Main()
{
    var cts = new CancellationTokenSource();
    SomeCancellableOperation(cts.Token);
    cts.cancel();
}

public void SomeCancellableOperation(CancellationToken token) {
...
    token.ThrowIfCancellationRequested();
...
}

A: You can look at the source code for CancellationToken. The basic idea is that the token only stores a reference to a CancellationTokenSource.
internal CancellationToken(CancellationTokenSource source)
{
    m_source = source;
}

The CancellationTokenSource is what is modified when it is cancelled. Checking whether the token is cancelled really just goes back to the source:
public bool IsCancellationRequested
{
    get
    {
        return m_source != null && m_source.IsCancellationRequested;
    }
}

A: The struct  is passed by value, but it contains a reference to a WaitHandle. The WaitHandle is global.


text:
Q: Find the probability that a matrix is diagonalizable The original question is as follows,
Let $p$ be an odd prime number. The entries of a $2\times2$ matrix $A\in M_2(\mathbb Z_p)$ are selected at random.
(a) Find the possibility that $f_A(x)$ splits
(b) Find the possibility that $A$ is diagonalizable.
So I started by calculating probability with very small $p$. But this did not give me any useful information. I would like to seek for some hint to get me start with the question. Thanks for any help.

A: (I'm assuming $\Bbb Z_p$ means the integers modulo $p$ rather than the $p$-adic integers)
First let's do some simple counting.

*

*The cardinality of $M_{2\times 2}(\Bbb Z_p)$ is $p^4$.

*The cardinality of $GL_{2\times 2}(\Bbb Z_p)$ is $(p^2-1)(p^2-p)=p(p+1)(p-1)^2$.

*The center of $GL_{2\times 2}(\Bbb Z_p)$ has cardinality $p-1$.

*The cardinality of the diagonal matrices are $(p-1)^2$.

Now let's count the number of diagonalizable matrices. A matrix $A$ is diagonalizable if there is a $B\in GL_{2\times 2}(\Bbb Z_p)$ such that $BAB^{-1}$ is diagonal. We would be mistaken to say the number of diagonalizable matrices is $(p-1)^2\cdot p(p+1)(p-1)^2$ because we could have two different invertible matrices $G$ and $H$ such that $GAG^{-1}=HAH^{-1}$. However, if we have such a $G$ and $H$, they satisfy a non-trivial relation. Namey $A(G^{-1}H)=(G^{-1}H)A$. That is $A$ commutes with $G^{-1}H$. Thus $G^{-1}H$ is in the centralizer of $A$. Now $G^{-1}H$ is in the centralizer of $A$ if and only if $G$ and $H$ lie in the same coset of the centralizer of $A$. And the number of cosets of the centralizer of $A$ is $|GL_{2\times 2}(\Bbb Z_p)|/|Z(A)|$ where $Z(A)$ is the centralizer of $A$.
Another reason that $(p-1)^2\cdot(p+1)(p-1)^2$ is wrong is that there could be diagonal matrices which are similar. This happens if the eigenvalues on the diagonal are the same. So to avoid double counting, we will only consider diagonal matrices whose eigenvalues are weakly increasing. Thus, to find the number of diagonalizable matrices it suffices to figure out how to count $|Z(A)|$ for each matrix $A$, for then the number of diagonalizable matrices is
$$\sum_{\substack{D\text{ diagonal}\\\text{increasing}}}\frac{(p^2-1)(p^2-p)}{|Z(D)|}$$
For elements of the center (which are diagonal matrices with a single non-zero scalar occuring) computing the center is easy - it's the whole group. Thus we have that the number of diagonalizable matrices is:
$$p-1+\sum_{\substack{D\text{ diagonal}\\\text{not central}\\\text{increasing}}}\frac{(p^2-1)(p^2-p)}{|Z(D)|}$$
That is, we want to compute $|Z(D)|$ for a matrix of the form $\left[\begin{smallmatrix}\lambda_1 & 0\\ 0 &\lambda 2\end{smallmatrix}\right]$ with $\lambda_1<\lambda_2$ (this is speaking loosely. There is no real order on $\Bbb Z_p$).
Now we abandon theory and actually do some 'dirty computation'. Another matrix $G\in GL_{2\times 2}(\Bbb Z_p)$ commutes with such a matrix if and only if $G=\left[\begin{smallmatrix}a &0\\0& b\end{smallmatrix}\right]$ for $a, b\in \Bbb Z_p^*$.
There are $(p-1)^2$ such matrices for a single matrix $D$. Thus our formula is now:
$$p-1+\sum_{\substack{D\text{ diagonal}\\\text{not central}\\\text{increasing}}}\frac{(p^2-1)(p^2-p)}{(p-1)^2}=p-1+\sum_{\substack{D\text{ diagonal}\\\text{not central}\\\text{increasing}}}p(p+1)$$
Now we need to calculate the number of diagonal, non-central, (strictly) increasing matrices (we took care of the central matrices). There are $1+\cdots + (p-2)=(p-2)(p-1)/2$ such matrices. Thus we arrive at
$$p-1+\frac{(p-1)(p-2)}{2}p(p+1)=\frac{p^4}{2}-p^3-\frac{p^2}{2}+2p-1$$
So for b) the probability that a matrix is diagonalizable is

$$1/2-1/p-1/2p^2+2/p^3-1/p^4$$

which interestingly approaches probability 1/2 as $p\rightarrow\infty$.
For a) recall a matrix's characteristic polynomial splits if and only if  $\Bbb Z_p^2$ has a basis of generalized eigenvalues of the matrix. This is equivalent to a matrix being similar to a matrix in Jordan normal form. For a vector space of dimension two this is simple. You can rework what I did for Jordan normal matrices. You just need to consider matrices of the form $\left[\begin{smallmatrix}\lambda & 1\\0&\lambda\end{smallmatrix}\right]$ in addition.
Or you can read this paper which investigates a much more general question and actually does your problem as a simple case.
The number of matrices similar to a Jordan normal matrix is $$\frac{p^4}{2}+p^3-\frac{p}{2}$$
and the probability of $f_A$ splitting is

$$1/2+1/p-1/2p^3$$

UPDATE
As Julian Rosen remarked in the comments, there are diagonalizable matrices with $0$ as an eigenvalue. My answer only computes the invertible diagonalizable matrices. This gives another element in the 'center' and $p(p-1)/2$ diagonal, strictly increasing, matrices.
The updated computation is:

$$p+\frac{p(p-1)}{2}\cdot p(p+1)=\frac{p^4}{2}-\frac{p^2}{2}+p$$

which yields the probability

$$\frac{1}{2}-\frac{1}{2p^2}+\frac{1}{p^3}$$

the same as Julian Rosen posted.
The paper I linked took into the account the matrices $\left[\begin{smallmatrix} 0&0\\0&0\end{smallmatrix}\right]$ and $\left[\begin{smallmatrix} 0&1\\0&0\end{smallmatrix}\right]$. So that computation is still correct.

A: Say $A=(a,b; c,d)\in M_2(\mathbb{F}_p)$. The characteristic polynomial splits if and only if the discriminant of the characteristic polynomial, $(a+d)^2-4(ad-bc)$, is a square in $\mathbb{F}_p$. Consider two cases:
Case 1 ($b\neq 0$) There are $(p+1)/2$ squares in $\mathbb{F}_p$, and for fixed $a,b,d$, the map $c\mapsto (a+d)^2-4(ad-bc)$ is bijective on $\mathbb{F}_p$, so the discriminant is a square with probability $(p+1)/(2p)$.
Case 2 ($b=0$) In this case the discriminant is $(a-d)^2$ (always a square).
Case 1 happens with probability $(p-1)/p$ and Case 2 with probability $1/p$, so the probability the characteristic polynomial splits is
$$
\frac{p-1}{p}\frac{p+1}{2p}+\frac{1}{p}1=\frac{1}{2}+\frac{1}{p}-\frac{1}{2p^2}.
$$
To compute the probability of diagonalizability: a $2\times 2$ matrix has a defective eigenvalue if and only if it is of the form $\lambda\cdot I+M$, with $\lambda\in\mathbb{F}_p$, $I$ the $2\times 2$ identity matrix, and $M$ a non-zero matrix having 0 as an eigenvalue with multiplicity 2. Let's count the number of such $M$. One checks that $M$ must have the form $M=(a,b;c,-a)\neq 0$,
with $a^2+bc=0$.
If $a=0$ we need $b=0$ or $c=0$ but not both, so there are $2(p-1)$ possibilities.
For fixed $a\neq 0$, we need $bc=-a^2$, so each non-zero $b$ determines a values of $c$, giving $p-1$ possibilities. There are $p-1$ possibilities for $a$, so there are $(p-1)^2$ matrices of this form (with $a\neq 0$). This gives a total of $2(p-1)+(p-1)^2=p^2-1$ matrices $M$. There are $p$ possible values of $\lambda$, so we get $p(p^2-1)$ matrices with a defective eigenvalue. A matrix is diagonalizable if and only if its characteristic polynomial splits and there are no defective eigenvalues, so the probability a matrix is diagonalizable is
$$
\frac{1}{2}+\frac{1}{p}-\frac{1}{2p^2}-\frac{p(p^2-1)}{p^4}=\frac{1}{2}-\frac{1}{2p^2}+\frac{1}{p^3}.
$$


text:
Q: Monty Hall simulator is not working properly I tried to simulate Monty Hall problem.
First I choosed the winning door and randomized a selection. Then opened a door which is not the selected door. Then checked if selected = winning door. If it is, I added 1 to not switching point (b.num).
Then to switch the selection, I removed selected door from the doors list and equalized selected to the only item in the list. Then checked if selected = winning door again and if it is I added 1 to switching point (s.num1).
The problem is switching win percent is roughly equal 33. The expected value of it is about 66. Where is the problem?
import random
from random import randint

def b():
    b.num+=1
b.num=0

def s():
    s.num+=1
s.num=0

d=int(input("try count: "))

def a():
    winner=randint(1,3)
    selection=randint(1,3)
    doors=[1,2,3]
    doors_to_open=randint(1,2)
    if selection == 1:
        if doors_to_open==1:
            doors.remove(2)
        else:
            doors.remove(3)

    if selection == 2:
        if doors_to_open==1:
            doors.remove(1)
        else:
            doors.remove(3)

    if selection == 3:
        if doors_to_open==1:
            doors.remove(1)
        else:
            doors.remove(2)

    if selection == winner:
        b()
        #print("Not switching win count: ",b.num)

    # switch

    doors.remove(selection)
    selection = doors[0]

    if selection == winner:
        s()
        #print("Switching win count: ",s.num)

for q in range (0,d):
    a()

#print("Switching win count: ",s.num)
print("Switching percent: ",(s.num/d)*100)
#print("Not switching win count: ",b.num)
print("Not switching percent: ",(b.num/d)*100)

input()

A: you have missed a not equal to operator while calling s function. if you add ! in the condition. it will fix your simulation.
import random
from random import randint

def b():
    b.num+=1
b.num=0

def s():
    s.num+=1
s.num=0

d=int(input("try count: "))

def a():
    winner=randint(1,3)
    selection=randint(1,3)
    doors=[1,2,3]
    doors_to_open=randint(1,2)
    if selection == 1:
        if doors_to_open==1:
            doors.remove(2)
        else:
            doors.remove(3)

    if selection == 2:
        if doors_to_open==1:
            doors.remove(1)
        else:
            doors.remove(3)

    if selection == 3:
        if doors_to_open==1:
            doors.remove(1)
        else:
            doors.remove(2)

    if selection == winner:
        b()
        #print("Not switching win count: ",b.num)

    # switch

    doors.remove(selection)
    selection = doors[0]

    if selection != winner: #Change is done in this line
        s()
        #print("Switching win count: ",s.num)

for q in range (0,d):
    a()

#print("Switching win count: ",s.num)
print("Switching percent: ",(s.num/d)*100)
#print("Not switching win count: ",b.num)
print("Not switching percent: ",(b.num/d)*100)

A: (thanks to Mark Meyer) the problem has solved. That code was opening the winning door too. Here is the proper code:
import random
from random import randint

def a():
    a.sayı+=1
a.sayı=0

def b():
    b.sayı+=1
b.sayı=0

def c():
    kapılar=[1,2,3]
    cevap=randint(1,3)
    seçim=randint(1,3)

    #kapı aç
    kapılar1=[1,2,3]
    if seçim==cevap:
        kapılar1.remove(cevap)
    else:
            kapılar1.remove(cevap)
            kapılar1.remove(seçim)
    #kapılar1.remove(cevap)
    #kapılar1.remove(seçim)
    kapılar.remove(kapılar1[0])

    #dont switch
    if seçim==cevap:
        a()

    #switch
    kapılar.remove(seçim)
    seçim=kapılar[0]

    if seçim==cevap:
        b()

d=int(input("Deneme sayısı: "))

for e in range(0,d):
    c()

print("Switching win percent: ",(b.sayı/d)*100)
print("Not switching win pecent: ",(a.sayı/d)*100)
input()


text:
Q: UIScrollView / UIImageView multiple page PDF possible? I'm trying to use UIScrollView together with UIImageView to display a PDF with several pages. Problem is that only seems to render the first page of the PDF and nothing else.
Is this possible at all with UIScrollView + UIImageview?

A: Perhaps you can create as UIImageView in the UIScrollView as pages has the PDF, and then when you load the PDF page (you wold use something like CGPDFDocumentGetPage(document, pageNumber)), just set the pageNumber to the number you want. You can know how many pages does the PDF document have with CGPDFDocumentGetNumberOfPages.


text:
Q: Setting text in UIAutomator I was just exploring the UIAutomator for Android app testing and came across this issue.
Based on the API.
https://github.com/xiaocong/uiautomator#screen-actions-of-the-device
I am trying to add a new contact programmatically as part of my exploration.

I have reached this page by using this code.
from uiautomator import device as d
d.click(x,y) #used to click all the way to contacts.

How do I insert text into the name textbox? Since I do not know the class image and there are not many examples on github.

A: According to document, it should be
d(text="Settings").set_text("My text...")  # set the text

A: Alternatively, you can use culebra from AndroidViewClient/culebra to autogenerate the script that does it through a GUI.
Run
culebra -uG --scale=0.5

then you can touch on the EditText and enter the value

which is reflected on the device

While you do this, the script is automatically generated
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2013-2014  Diego Torres Milano
Created on 2015-08-19 by Culebra v10.7.1
                      __    __    __    __
                     /  \  /  \  /  \  /  \
____________________/  __\/  __\/  __\/  __\_____________________________
___________________/  /__/  /__/  /__/  /________________________________
                   | / \   / \   / \   / \   \___
                   |/   \_/   \_/   \_/   \    o \
                                           \_____/--<
@author: Diego Torres Milano
@author: Jennifer E. Swofford (ascii art snake)
'''

import re
import sys
import os

try:
    sys.path.insert(0, os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src'))
except:
    pass

from com.dtmilano.android.viewclient import ViewClient

TAG = 'CULEBRA'

_s = 5
_v = '--verbose' in sys.argv

kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': False}
device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1)
kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': True}
vc = ViewClient(device, serialno, **kwargs2)
#vc.dump(window='-1') # FIXME: seems not needed

vc.dump(window=-1)
vc.findViewWithTextOrRaise("u'Name'").type(u"My Contact")

A: Use adb shell input text instead.
Don't forget to import
import os
os.system("adb shell input text "+ your_text)

A: I hope your exploration were doing well and funny :)
I see you have found an alternative to set the text. But there's an easy way to do it, something similar to the @Fang Wang answer, and I'll answer this for future researches about it.
d(text="Name").set_text("My text...")

This line above will works for sure. If you want to discovery the properties of any screen on Android you just need to use uiautomatorviewer and you will get something like that:

Then you will be able to inspect any screen element and discovery their details.
With these informations we can create our code to interact with any Android element.
In this case you need to use the text set on the field because the attribute class is the same for all fields.
Also you won't need to click on the fields if you specify the action you want and their name or class or resourceId etc...
PS: UiAutomatorViewer is installed with Android Studio.


text:
Q: How do I get subtitles automatically? I would like to use a movie player that downloads subtitles in the language of my preference automatically. Is there anything like it? And plugins?

A: SMPlayer intends to be a complete front-end for MPlayer, from basic features like playing videos, DVDs, and VCDs to more advanced features like support for MPlayer filters and more.
One of the most interesting features of SMPlayer: it remembers the settings of all files you play. So you start to watch a movie, but you have to leave... Don't worry, when you open that movie again it will resume at the same point you left it, and with the same settings: audio track, subtitles, volume...

Other additional interesting features:

*

*Configurable subtitles. You can choose font and size, and even colors for the subtitles.

*Audio track switching. You can choose the audio track you want to listen. It works with AVI and MKV. And of course with DVDs.

*Seeking by mouse wheel. You can use your mouse wheel to go forward or backward in the video.

*Video equalizer, allows you to adjust the brightness, contrast, hue, saturation, and gamma of the video image.

*Multiple speed playback. You can play at 2X, 4X... and even in slow motion.

*Filters. Several filters are available: deinterlace, postprocessing, denoise, etc. And even a karaoke filter (voice removal).

*Audio and subtitles delay adjustment. It allows you to synchronise audio and subtitles.

*Advanced options, such as selecting a demuxer or video & audio codecs.

*Playlist. It allows you to enqueue several files to be played one after each other. Autorepeat and shuffle are supported too.

*Preferences dialog. You can easily configure every option of SMPlayer by using a nice preferences dialog.

*Possibility to search automatically for subtitles in opensubtitles.org.

*Translations: currently SMPlayer is translated into more than 20 languages, including Spanish, German, French, Italian, Russian, Chinese, and Japanese.

*It's multiplatform, and binaries are available for Windows and Linux.

SMPlayer is free open source software (FOSS), and a portable version is available.

A: VLC media player can do this with an integrated addon.

The addon, called VLSub, is to be found separately here. It searches and downloads subtitles from opensubtitles.org using the hash of the video currently playing or its title.
VLC media player has an addons/extension site: addons.videolan.org. There is to be found another VLC media player addon for subtitles, called Subtitle Finder. It seems a bit deprecated from time to time, while the VLSub is actively supported and updated.

How to install extensions in VLC media player:
- Put the file in the VLC subfile /lua/extensions, by default:

*

*Windows (all users): %ProgramFiles%\VideoLAN\VLC\lua\extensions\

*Windows (current user): %APPDATA%\vlc\lua\extensions\

*Linux (all users): /usr/lib/vlc/lua/extensions/

*Linux (current user): ~/.local/share/vlc/lua/extensions/

*Mac OS X (all users): /Applications/VLC.app/Contents/MacOS/share/lua/extensions/
(Create directories if they don't exist.)

VLC media player with VLSub can even find subtitles for DVDs, although VLC media player is not too good at displaying such external subtitles for DVD movies. But it can search and download them, as follows:

*

*Load the DVD movie in VLC media player and open VLSub under 'View'

*Enter the name of the movie and search by name. If found, download it; the subtitles will be announced as loaded but in fact VLC media player will probably not be able to display them (more here); "click here to open the file", the file will be then downloaded via the default browser; in case the VLSub window will say that it cannot save the file, try to see if in fact it has saved it in a temporary folder (in Windows the subtitle will be in 'C:\Users\username\AppData\Roaming\vlc\lua\extensions\userdata\vlsub') and will have no name: will appear as '.srt'. In order to test the subtitle and see if it's synced, follow this answer. It involves using Media Player Classic (which can also easily create synced subtitles) or PotPlayer. Open the DVD movie in MPC-HC or PotPlayer and drag and drop the '.srt' file into the player. (I have tested this part only in Windows for the moment.)

Also, in Windows, BSPlayer downloads subtitles automatically, as already mentioned by a previous answer.

Media Player Classic (Home Cinema) has a download option under: File - Subtitle database - Download

Subdownloader, is a great tool. (For Windows it is not free.)
One might try Sublight: but it looks bloated and all for nothing after all, compared with something like the tiny VLC media player script.

Summing up:
For Windows:

*

*VLC media player - VLSub

*BSPlayer

*Media Player Classic - Home Cinema

For Linux:

*

*VLC media player - VLSub

*SMPlayer

*SubDownloader

For Mac:

*

*VLC media player - VLSub

VLSUB does not work with VLC media player 2.1 on any platform. Use older or newer versions of VLC media player.

A: Splayer claims it can do this, but I haven't tested it myself though.

A: BSPlayer used to automatically search for subtitles on the web when I used it.


text:
Q: Python Flask - TypeError: an integer is required (got type str) I'm building a simple web-app in Python Flask but when I am trying to submit the form, I am getting this error message -
"TypeError: an integer is required (got type str)"
from flask import Flask, render_template, request, flash, redirect, url_for, session, logging
from data import Articles
from flask_mysqldb import MySQL
from wtforms import Form, StringField, TextAreaField, PasswordField, validators
from passlib.hash import sha256_crypt

app = Flask(__name__)

# Config MySQL
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_PORT'] = '8889'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = '123456'
app.config['MYSQL_DB'] = 'myflaskapp'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'

#init MYSQL
mysql = MySQL(app)

Articles = Articles()

@app.route('/')
def index():
    return render_template('home.html')

@app.route('/about')
def about():
    return render_template('about.html')

@app.route('/articles')
def articles():
    return render_template('articles.html', articles = Articles)

@app.route('/article/<string:id>')
def article(id):
    return render_template('article.html', id = id)

class RegisterForm(Form):
    name = StringField('Name', [validators.Length(min=1, max=50)])
    username = StringField('Username', [validators.Length(min=4, max=25)])
    email = StringField('Email', [validators.Length(min=6, max=50)])
    password = PasswordField('New Password', [
            validators.DataRequired(),
            validators.EqualTo('confirm', message='Passwords must match')
        ])
    confirm = PasswordField('Repeat Password')

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        name = form.name.data
        email = form.email.data
        username = form.username.data
        password = sha256_crypt.encrypt(str(form.password.data))

        # Create cursor
        cur = mysql.connection.cursor()

        # Execute query
        cur.execute("INSERT INTO users(name, email, username, password) VALUES (%s, %s, %s, %s)", (name, email, username, password))

        # Commit to DB
        mysql.connection.commit()

        #  Close connection
        cur.close()

        flash('You are now registered and can log in', 'success')

        return redirect(url_for('login'))

    return render_template('register.html', form=form)

if __name__ == '__main__':
    app.secret_key = 'secret123'
    app.run(debug=True)

Traceback (most recent call last)
File "C:\Users\Harsh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\Harsh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\Harsh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Harsh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\Harsh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\Harsh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\Harsh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Harsh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\Harsh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\Harsh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\Harsh\Desktop\Projects\py\myflaskapp\app.py", line 58, in register
    cur = mysql.connection.cursor()
  File "C:\Users\Harsh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask_mysqldb\__init__.py", line 94, in connection
    ctx.mysql_db = self.connect
  File "C:\Users\Harsh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask_mysqldb\__init__.py", line 81, in connect
    return MySQLdb.connect(**kwargs)
  File "C:\Users\Harsh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\MySQLdb\__init__.py", line 86, in Connect
    return Connection(*args, **kwargs)
  File "C:\Users\Harsh\AppData\Local\Programs\Python\Python36-32\lib\site-packages\MySQLdb\connections.py", line 204, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
TypeError: an integer is required (got type str)

I am not sure why this is happening, can anyone guide me on this please. I looked at the other solutions on here, but they didn't really work for me

A: In config parameters PORT must be an Integer
you are here passing it in string
#Config MySQL
app.config['MYSQL_PORT'] = '8889' ##pass 8889 instead of '8889'


text:
Q: Stormcrawler slow with high latency crawling 300 domains I am currently struggling with this issue since about 3 month. The Crawler seems to fetch pages every 10 minutes but seems to do nothing in between. With an overall very slow throughput. I am crawling 300 domains in parallel. Which should make around 30 pages/second with a crawling delay of 10 seconds. Currently it is about 2 pages per second.
The topology runs on a PC with

*

*8GB Memory

*Normal Harddrive

*Core Duo CPU

*Ubuntu 16.04

Elasticsearch is installed on another machine with the same specs.
Here you can see the metrics from the Grafana Dashboard

They are also reflected in the process latency seen in the Storm UI:

My current architecture for Stormcrawler is:
spouts:
  - id: "spout"
    className: "com.digitalpebble.stormcrawler.elasticsearch.persistence.AggregationSpout"
    parallelism: 25

bolts:
  - id: "partitioner"
    className: "com.digitalpebble.stormcrawler.bolt.URLPartitionerBolt"
    parallelism: 1
  - id: "fetcher"
    className: "com.digitalpebble.stormcrawler.bolt.FetcherBolt"
    parallelism: 6
  - id: "sitemap"
    className: "com.digitalpebble.stormcrawler.bolt.SiteMapParserBolt"
    parallelism: 1
  - id: "parse"
    className: "com.digitalpebble.stormcrawler.bolt.JSoupParserBolt"
    parallelism: 1
  - id: "index"
    className: "de.hpi.bpStormcrawler.BPIndexerBolt"
    parallelism: 1
  - id: "status"
    className: "com.digitalpebble.stormcrawler.elasticsearch.persistence.StatusUpdaterBolt"
    parallelism: 4
  - id: "status_metrics"
    className: "com.digitalpebble.stormcrawler.elasticsearch.metrics.StatusMetricsBolt"
    parallelism: 1

with the configuration (here the most relevant part):
config:
  topology.workers: 1
  topology.message.timeout.secs: 300
  topology.max.spout.pending: 100
  topology.debug: false

  fetcher.threads.number: 50

  worker.heap.memory.mb: 2049
  partition.url.mode: byDomain

  fetcher.server.delay: 10.0

and here the storm configuration (also just the relevant part):

nimbus.childopts: "-Xmx1024m -Djava.net.preferIPv4Stack=true"

ui.childopts: "-Xmx768m -Djava.net.preferIPv4Stack=true"

supervisor.childopts: "-Djava.net.preferIPv4Stack=true"

worker.childopts: "-Xmx1500m -Djava.net.preferIPv4Stack=true"

Do you have any idea what could be the problem? Or is it just a problem of the hardware?
What I already tried out

*

*Increase the fetcher.server.delay to a higher and lower value which didn't change anything

*Decrease and increase the number of fetcher threads

*Played around with the parallelism

*Calculated if it is the network bandwidth. With a bandwidth of 400mbit/s and an average page size of 0.5 MB it would be 15MB/s which would be 120mbit/s which should also not the problem

*Increased the number of workers

Do you have any more ideas which I should check out or reasons that could explain the slow fetching? Maybe it is also just the slow hardware? Or the bottleneck is Elasticsearch?
Thank you very much in advance
EDIT:
I changed the topology to two workers and have a recurring error

2018-07-03 17:18:46.326 c.d.s.e.p.AggregationSpout Thread-33-spout-executor[26 26] [INFO] [spout #12]  Populating buffer with nextFetchDate <= 2018-06-21T17:52:42+02:00
2018-07-03 17:18:46.327 c.d.s.e.p.AggregationSpout I/O dispatcher 26 [ERROR] Exception with ES query
java.io.IOException: Unable to parse response body for Response{requestLine=POST /status/status/_search?typed_keys=true&ignore_unavailable=false&expand_wildcards=open&allow_no_indices=true&preference=_shards%3A12&search_type=query_then_fetch&batched_reduce_size=512 HTTP/1.1, host=http://ts5565.byod.hpi.de:9200, response=HTTP/1.1 200 OK}
 at org.elasticsearch.client.RestHighLevelClient$1.onSuccess(RestHighLevelClient.java:548) [stormjar.jar:?]
 at org.elasticsearch.client.RestClient$FailureTrackingResponseListener.onSuccess(RestClient.java:600) [stormjar.jar:?]
 at org.elasticsearch.client.RestClient$1.completed(RestClient.java:355) [stormjar.jar:?]
 at org.elasticsearch.client.RestClient$1.completed(RestClient.java:346) [stormjar.jar:?]
 at org.apache.http.concurrent.BasicFuture.completed(BasicFuture.java:119) [stormjar.jar:?]
 at org.apache.http.impl.nio.client.DefaultClientExchangeHandlerImpl.responseCompleted(DefaultClientExchangeHandlerImpl.java:177) [stormjar.jar:?]
 at org.apache.http.nio.protocol.HttpAsyncRequestExecutor.processResponse(HttpAsyncRequestExecutor.java:436) [stormjar.jar:?]
 at org.apache.http.nio.protocol.HttpAsyncRequestExecutor.inputReady(HttpAsyncRequestExecutor.java:326) [stormjar.jar:?]
 at org.apache.http.impl.nio.DefaultNHttpClientConnection.consumeInput(DefaultNHttpClientConnection.java:265) [stormjar.jar:?]
 at org.apache.http.impl.nio.client.InternalIODispatch.onInputReady(InternalIODispatch.java:81) [stormjar.jar:?]
 at org.apache.http.impl.nio.client.InternalIODispatch.onInputReady(InternalIODispatch.java:39) [stormjar.jar:?]
 at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady(AbstractIODispatch.java:114) [stormjar.jar:?]
 at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:162) [stormjar.jar:?]
 at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:337) [stormjar.jar:?]
 at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:315) [stormjar.jar:?]
 at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:276) [stormjar.jar:?]
 at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104) [stormjar.jar:?]
 at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:588) [stormjar.jar:?]
 at java.lang.Thread.run(Thread.java:748) [?:1.8.0_171]
Caused by: java.lang.NullPointerException

Still the crawling process seems much more balanced but still does not fetch a lot of links

Also after running the topology for some weeks the latency went up a lot

A: Sorry for the late reply, just back from holidays.
Judging by the graph, the worker gets restarted, which makes me think that something is blocking or crashing the topology. After a while where nothing happens, the worker is restarted, it processed some URLs and the issue happens again.
Have you checked the logs for error messages? Is there a memory dump in the logs? Can you isolate the URL(s) which cause the issue?

A: This happens when you do not ack() or fail() all tuples in all your (custom) bolts.
Also, when emitting from an intermediate bolt, make sure to anchor the new tuple correctly to the previous tuple.
See this SO answer for an explanation.
I had the same issue, also with an ES setup. I first thought it was about the nextFetchDate logic of the ES Spout, but after disabling my custom bolts, the issue was fixed. So I found that I missed to ack() a tuple somewhere.
This resulted in un-acked tuples being lost in the topology, which then would be re-emitted after 10 minutes / 600 seconds.
Though I did not find where the 10 minute replay timeout is defined, as the storm-replay mechanism was set to 5 minutes via
topology.message.timeout.secs: 300


text:
Q: Why isn't [[carries_dependency]] the default in C++? I know that memory_order_consume has been deprecated, but I'm trying to understand the logic that went into the original design and how [[carries_dependency]] and kill_dependency were supposed to work.  For that, I would like a specific example of code that would break on an IBM PowerPC or DEC alpha or even a hypothetical architecture with a hypothetical compiler that fully implemented consume semantics in C++11 or C++14.
The best I can come up with is an example like this:
int v;
std::atomic<int*> ap;

void
thread_1()
{
  v = 1;
  ap.store(&v, std::memory_order_release);
}

int
f(int *p [[carries_dependency]])
{
  return v;
}

void
thread_2()
{
  int *p;
  while (!(p = ap.load(std::memory_order_consume)))
    ;
  int v2 = f(p);
  assert(*p == v2);
}

I understand that the assertion could fail in this code.  However, is it the case that the assertion is not supposed to fail if you remove [[carries_dependency]] from f?  If so, why is that the case?  After all, you requested a memory_order_consume, so why would you expect other accesses to v to reflect acquire semantics?  If removing [[carries_dependency]] does not make the code correct, then what's an example where [[carries_dependency]] (or making [[carries_dependency]] the default for all variables) breaks otherwise correct code?
The only thing I can think is that maybe this has to do with register spills?  If a function spills a register onto the stack and later re-loads it, this could break the dependency chain.  So maybe [[carries_dependency]] makes things efficient in some cases (says no need to issue memory barrier in the caller before calling this function) but also requires the callee to issue a memory barrier before any register spills or calling another function, which could be less efficient in other cases?  I'm grasping at straws here, though, so would still love to hear from someone who understands this stuff...

A: return v doesn't have a data dependency on int *p, so you'd need acquire not consume for ap.load(consume) / f(p) to synchronize with the release store.
If you'd used return *p then this would be sufficient thanks to dependency ordering, because that load would have a data dependency on the earlier load, no way for the CPU to generate the address earlier and thus load from v before the load from ap that saw the value you were waiting for.
Promoting dropping the dependency-ordering stuff effectively requires promoting consume to acquire by using a memory barrier before the function call.
DEC Alpha would always need a barrier even for consume to work, i.e. it had to promote consume to acquire because the ISA didn't guarantee dependency ordering by the hardware.
Some ISAs (mostly just x86) are so strongly ordered they don't need a barrier because every load is an acquire load, not reordered with other loads.  Or at least giving the illusion of not being reordered; actual implementations speculatively load early but nuke the pipeline if mis-speculation is detected, i.e. where a cache line isn't still valid by the time the load was architecturally allowed to happen.
So x86 and Alpha would likely still work even with the [[carries-dependency]] version, because they're either too strong or too weak for mo_consume to be something the hardware can actually do (more cheaply than mo_acquire).
For Alpha it would depend where the compiler put the barrier; it could put it after f(p)'s return v, only before the *p that actually depends on the consume load.  Or it could just promote consume to acquire on the spot at the load, like compilers do now (since consume is deprecated after proving too hard to support in its current design.)

As for why ISO C++11 decided to promote consume results to effectively acquire when passing across function boundaries, that might have been a usability consideration.  But also performance.  Without that, compilers would lose the ability to do some optimizations on incoming function args.
e.g. int ready = foo.load(consume); / if(ready == 1) return non_atomic[ready-ready]; is required to make asm that has a data dependency on the consume-load result, unlike normal when the compiler would just optimize it to return *non_atomic.
(You might be familiar with x86 xor eax,eax being a good way to zero a register.  In weakly-ordered ISAs that guarantee dependency ordering, like ARM, eor r0, r0,r0 is guaranteed not to break the dependency on the old value of r0.)
Also constant-propagation in branches like if(ready == 1) should be possible; code inside that if can only run when ready has the constant value 1.  So even if we weren't cancelling it out, non_atomic[ready] can't be optimized to non_atomic[1];.
If every incoming function arg potentially carried a dependency, compilers would not be able to do those usual optimizations on any function args or values derived from them.

Related re: what consume is about and/or its deprecation, and that it's still used in a hand-rolled way with volatile in Linux kernel code (e.g. RCU):

*

*[[carries_dependency]] what it means and how to implement

*When should you not use [[carries_dependency]]?


text:
Q: how to make breadcrumb in ionic framework? Can Ionic provide the functionality of breadcrub .Actually I search on ionic website did not find found documentation of breadcrub .In other words how to make breadcrub in ionic .Actually I don't want to use bootstrap in my project .Actually using bootstrap it is easily achievable .But i just want to use ionic .can we make breadcrub using ionic
I found a link
I want to make this type of breadcrub in ionic.can we achieve this ?
http://www.lendmeyourear.net/breadcrumb-navigation-with-css-arrows.html
I found one solution but they are using jquery .

A: I was looking for the same. However, I found that breadcrumb is possible with AngularJS and as Ionic is based of AngularJS you can use it for sure.
Please check this link for more details https://github.com/michaelbromley/angularUtils/tree/master/src/directives/uiBreadcrumbs


text:
Q: how to make different authentication in asp.net c# web form? we have two part for authentication in web site. the first use in admin and the second use for users to enter to site.when admin authentication in site  and go to user page ,make error.how to create different authentication for those?web config code:
<authentication mode="Forms">
  <forms loginUrl="~/admin/Login.aspx" timeout="2880" />
</authentication>

A: Based on your reply in comments...

we read users permissions on sign on.when i use User.Identity.IsAuthenticated then its return true.but this Authenticated for admin.how to make different Authenticated for users?

Checking whether a user is authenticated is different from checking a user's permissions. Authentication only tells you that the person visiting your site has authenticated themselves (i.e. logged on to their account).
What's missing in your equation is the authorization phase (Remember college/uni? Everyone is issued ID cards, on access to the college/uni grounds you authenticate yourself, staff members also authenticate themselves, students won't have authorization to enter the staff room or perform certain tasks, but staff members do).
We implement this using what's called Roles, every user should have a Role. Every Role should have a set of Permissions associated with it, for now I wouldn't worry about Permissions as it can get real complicated real quick, if you focus on ìmplementing roles alone for now, it would be enough to get you going.
Once every user has a role associated to their account, you can check their Role  instead of whether they're simply authenticated, which doesn't tell you much.
There should be an extension method to the IPrinciple interface along the lines of GetUserRoles() already implemented in framework, User.Identity.GetUserRoles() something along the lines of that.


text:
Q: Airflow in docker keep restarting Im trying to create a local Airflow env with Docker + ubuntu in a Windows OS.
I used the following wizard:
https://github.com/aws/aws-mwaa-local-runner
This wizard creates 2 containers (1 for DB and 1 for the Airflow)
Now I'm stuck with the following problem:
My Airflow container keeps restarting after troughing 2 exceptions:

*

*"ERROR: You need to initialize the database. Please run airflow db init. Make sure the command is run using Airflow version 2.3.2."

*Traceback (most recent call last):
File "/usr/local/bin/airflow", line 8, in
sys.exit(main())
File "/usr/local/airflow/.local/lib/python3.7/site-packages/airflow/main.py", line 38, in main
args.func(args)
File "/usr/local/airflow/.local/lib/python3.7/site-packages/airflow/cli/cli_parser.py", line 51, in command
return func(*args, **kwargs)
File "/usr/local/airflow/.local/lib/python3.7/site-packages/airflow/cli/commands/db_command.py", line 35, in initdb
db.initdb()
File "/usr/local/airflow/.local/lib/python3.7/site-packages/airflow/utils/session.py", line 71, in wrapper
return func(*args, session=session, **kwargs)
File "/usr/local/airflow/.local/lib/python3.7/site-packages/airflow/utils/db.py", line 648, in initdb
upgradedb(session=session)
File "/usr/local/airflow/.local/lib/python3.7/site-packages/airflow/utils/session.py", line 68, in wrapper
return func(*args, **kwargs)
File "/usr/local/airflow/.local/lib/python3.7/site-packages/airflow/utils/db.py", line 1449, in upgradedb
command.upgrade(config, revision=to_revision or 'heads')
File "/usr/local/lib/python3.7/site-packages/alembic/command.py", line 294, in upgrade
script.run_env()
File "/usr/local/lib/python3.7/site-packages/alembic/script/base.py", line 490, in run_env
util.load_python_file(self.dir, "env.py")
File "/usr/local/lib/python3.7/site-packages/alembic/util/pyfiles.py", line 97, in load_python_file
module = load_module_py(module_id, path)
File "/usr/local/lib/python3.7/site-packages/alembic/util/compat.py", line 182, in load_module_py
spec.loader.exec_module(module)
File "", line 728, in exec_module
File "", line 219, in _call_with_frames_removed
File "/usr/local/airflow/.local/lib/python3.7/site-packages/airflow/migrations/env.py", line 107, in
run_migrations_online()
File "/usr/local/airflow/.local/lib/python3.7/site-packages/airflow/migrations/env.py", line 101, in run_migrations_online
context.run_migrations()
File "", line 8, in run_migrations
File "/usr/local/lib/python3.7/site-packages/alembic/runtime/environment.py", line 813, in run_migrations
self.get_context().run_migrations(**kw)
File "/usr/local/lib/python3.7/site-packages/alembic/runtime/migration.py", line 548, in run_migrations
for step in self._migrations_fn(heads, self):
File "/usr/local/lib/python3.7/site-packages/alembic/command.py", line 283, in upgrade
return script._upgrade_revs(revision, rev)
File "/usr/local/lib/python3.7/site-packages/alembic/script/base.py", line 365, in _upgrade_revs
revs = list(revs)
File "/usr/local/lib/python3.7/site-packages/alembic/script/revision.py", line 1040, in _iterate_revisions
total_space.remove(rev.revision)
KeyError: '75d5ed6c2b43'"
I tried to run the following command in ubuntu for updating the DB:
"docker exec -it aws-mwaa-local-runner-202_local-runner_1 /entrypoint.sh airflow db upgrade"
but getting same error:
"..... KeyError: '75d5ed6c2b43'"
I also tried to reset and init the Airflow DB with-

*

*docker exec -it aws-mwaa-local-runner-202_local-runner_1 /entrypoint.sh airflow initdb

*docker exec -it aws-mwaa-local-runner-202_local-runner_1 /entrypoint.sh airflow reset
and still getting the "..... KeyError: '75d5ed6c2b43'" error.

waiting for response,
Thanks