text:
Q: How do I find out whether time has passed? Swift I'm developing an app where user should able to choose a time slot. i.e 8:00 AM - 8: 30 AM or 2:00 PM - 2: 30 PM. But I want the user to choose only the time slot based on current time. i.e if its 8PM, he shouldn't able to choose slots till 9PM. I need  minimum an hour gap.
For now I have just hard coded the time slots as shown below and displaying in a picker view.
var items = ["8.00 AM - 8.30 AM","8.30 AM - 9.00 AM","9.00 AM - 9.30 AM","9.30 AM - 10.00 AM","10.00 AM - 10.30 AM","10.30 AM - 11.00 AM","11.00 AM - 11.30 AM","11.30 AM - 12.00 PM","12.00 PM - 12.30 PM","12.30 PM - 1.00 PM","1.00 PM - 1.30 PM","1.30 PM - 2.00 PM","2.00 PM - 2.30 PM","2.30 PM- 3.00 PM","3.00 PM - 3.30 PM","3.30 PM - 4.00 PM","4.00 PM - 4.30 PM","4.30 PM - 5.00 PM","5.00 PM - 5.30 PM","5.30 PM - 6.00 PM","6.00 PM - 6.30 PM","6.30 PM - 7.00 PM","7.00 PM - 7.30 PM","7.30 PM - 8.00 PM","8.00 PM - 8.30 PM","8.30 PM - 9.00 PM"]

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

    if pickerView.tag == 1 {
        return dates[row] as? String
    }else{
        return items[row]
    }

}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView.tag == 1 {
        dateTextField.text = dates[row] as? String
    }else if pickerView.tag == 2{

        timeTextField.text = items[row]
    }

When the user selects the time and if it has past, I want to present an alert or I should disable the time slots which has past. Could anyone please help me to achieve this.

A: First of all you want to create a swift file named Calendar or whatever you like and add the following code :
import UIKit

extension NSDate {
    func hour() -> Int
    {
        //Get Hour
        let calendar = Calendar.current
        let components = calendar.components(.hour, from: self as Date)
        let hour = components.hour

        //Return Hour
        return hour!
    }

    func minute() -> Int
    {
        //Get Minute
        let calendar = Calendar.current
        let components = calendar.components(.minute, from: self as Date)
        let minute = components.minute

        //Return Minute
        return minute!
    }

    func toShortTimeString() -> String
    {
        //Get Short Time String
        let formatter = DateFormatter()
        formatter.timeStyle = .short
        let timeString = formatter.string(from: self as Date)

        //Return Short Time String
        return timeString
    }
}

After that you can write on your ViewController in viewDidLoad() something like that to get the time I have added a Label on my storyboard so I can see the current hour. :
    let currentDate = NSDate()
    timeLabel.text = currentDate.hour().description

The above code is from this post: https://stackoverflow.com/a/29319223/6598643
Above i used Swift 3. On the other post its Swift
---EDIT---
Here is the code for the pickerView:
import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var pickerView: UIPickerView!
    var array = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        let currentDate = NSDate()
        self.pickerView.dataSource = self;
        self.pickerView.delegate = self;
        var nextHour = 0
        var nextMinute = 0
        var forLoop = 0
        timeLabel.text = "\(currentDate.hour().description) : \(currentDate.minute())"
        if currentDate.minute() > 30 {
            nextHour = currentDate.hour()+2
            nextMinute = 30
        }else{
            nextHour = currentDate.hour()+1
            nextMinute = 0
        }
        if nextMinute == 0 {
            forLoop = (21 - nextHour-1)
            for index in 0 ... forLoop{
                array.append("\(nextHour+index):00")
                array.append("\(nextHour+index):30")
            }
            array.append("21:00")
        }else{
            forLoop = (21 - nextHour - 1)

            for index in 0 ... forLoop{
                array.append("\(nextHour+index):00")
                array.append("\(nextHour+index):30")
            }
            array.append("21:00")
        }
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return array.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return array[row]
    }
}

It calculates and loads on an array the times left from the current time until 21:00 and loads them on pickerView.
Hope I helped. Good luck with your project :)


text:
Q: MySQL and PHP - Password Compare I'm using a stored procedure to check the username and password on login attempts. - The passwords are stored using the password() function in MySQL.
And the login works fine, using the stored procedure, the problem is that I have a function that enables the user to change the password, how should I update it? as MD5 through PHP? or should I build a new stored procedure?
Thanks :)

A: You're not supposed to use the PASSWORD() function for your application-level passwords.
http://dev.mysql.com/doc/refman/5.6/en/encryption-functions.html#function_password says:

Note
  The PASSWORD() function is used by the authentication system in
  MySQL Server; you should not use it in your own applications. For that
  purpose, consider MD5() or SHA2() instead. Also see RFC 2195, section
  2 (Challenge-Response Authentication Mechanism (CRAM)), for more
  information about handling passwords and authentication securely in
  your applications.

If you use a standard cryptographic hash method like SHA2, you can perform the hashing in PHP, using the hash extension. Hashes calculated with the same algorithm in PHP are compatible with those calculated in MySQL.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating your personal colors in Xcode for iOS 5 How can you make custom colors in Xcode 4.3.2 for iOS5?
I have a few different colors that I would like to make.

*

*http://www.colorhexa.com/5893bd

*http://www.colorhexa.com/1a78be

A: http://www.colorhexa.com/5893bd
"In a RGB color space, hex #5893bd is composed of 34.5%red, 57.6% green and 74.1%blue."
Convert the percentage of the colors to decimals and enter the code in this function.
colorWithRed: 0.345 green: 0.576 blue


text:
Q: Exponential Distributions -- probability at least one customer will arrive in the next half minute? Assume the time between arriving customers is exponential distributed with a mean of half a minute.  Assume one minute has gone by since the last customer arrived. What then, is the probability that at least one customer will arrive in the next half minute?
I've determined that λ = 2 since the mean is 1/2.
\begin{align}
P(X \le x) &= 1 - e^{-2x}\\
P(X \le 1) &= 1 - e^{-2}\end{align}

A: Hint:
The probability you  look for is
$$
P(1<x<1.5 | x>1) = \frac{P(1<x<1.5 \text{ and }P( x>1)}{x>1)}= \frac{P(1<x<1.5)}{P(x>1)}
$$

solution:
Using the last expression:
$$
= \frac{P(x>1) - P(x> 1.5)}{P(x>1)} = \frac{e^{-2} - e^{-3}}{e^{-2}} = 1-e^{-1}
$$
Note that this is also $1-P(X>1.5 - 1)$. The same way you can prove that
$$
P(X>t+h | X>t) = P(X>h)
$$
This is why the exponential variable is said to be memoryless.


text:
Q: Symfony mailer raw content is weird, contains =20 =3D = I'm using symfony mailer component and making the HTML template with twig.
After sending email in symfony profiler email section, the raw content is something I can't understand!
What are those? do they affect the spamminess level?

And this is my code:
$email = (new TemplatedEmail())
            ->from(new Address($this->container->getParameter('mailer_no_replay'), 'B2B Marketing'))//TODO: Translation
            ->to(new Address($lead->getEmail(), $lead->getName()))
            ->subject($emailTemplate->getSubject())
            ->htmlTemplate('emails/email-messages/crm-email.html.twig')
            ->context([
                'user' => $lead,
                'content' => $mailContent,
            ]);
        $this->mailer->send($email);

And the templates:
1: child (extends 2)
{% extends 'emails/content-email.html.twig' %}
{% block emailMessage %}
    {{ content | raw}}
{% endblock %}

2: parent
{% extends 'emails/emailBase.html.twig' %}
{#
This Template used for rendering emails that just have a content not need to render anything else
#}
{% block content %}

                                    {% block emailMessage %}{% endblock %}

{% endblock %}

A: These characters are:
Quoted-Printable, or QP encoding, is a binary-to-text encoding system using printable ASCII characters.
QP works by using the equals sign = as an escape character.
Example:
The following example is a French text (encoded in UTF-8), with a high frequency of letters with diacritical marks (such as the é).
J'interdis aux marchands de vanter trop leurs marchandises. Car ils se font=
vite p=C3=A9dagogues et t'enseignent comme but ce qui n'est par essence qu=
'un moyen, et te trompant ainsi sur la route =C3=A0 suivre les voil=C3=
=A0 bient=C3=B4t qui te d=C3=A9gradent, car si leur musique est vulgaire il=
s te fabriquent pour te la vendre une =C3=A2me vulgaire.
   =E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry, Citadelle (1948)

This encodes the following quotation:

J'interdis aux marchands de vanter trop leurs marchandises. Car ils se font vite pédagogues et t'enseignent comme but ce qui n'est par essence qu'un moyen, et te trompant ainsi sur la route à suivre les voilà bientôt qui te dégradent, car si leur musique est vulgaire ils te fabriquent pour te la vendre une âme vulgaire.
— Antoine de Saint-Exupéry, Citadelle (1948)

More details: https://en.wikipedia.org/wiki/Quoted-printable
Thanks to msg.


text:
Q: How to combine variable with the rest of the command How do I combine a variable with the rest of the command, without getting an error:
i.e. I want to issue:
Set-MailboxFolderPermission -Identity fred.bloggs@here.com:\Calendar -User Default -AccessRights Reviewer

But using a variable $email for the email address. I tried:
Set-MailboxFolderPermission -Identity $email:\Calendar -User Default -AccessRights Reviewer

But this gives an error.

A: The colon (:) is a valid character in variable names (it's a scope specifier or a PSDrive reference) and thus it looks for the variable $email: (which in itself is invalid, but still problematic here). You need either a subexpression and quotes:
"$($email):\Calendar"

or escape the colon:
$email`:\Calendar

A: You can also use braces to isolate the variable. Notice that with this syntax the variable name doesn't include the dollar sign:
"${email}:\Calendar"

A: The variable wont expand unless its in double quotes:
set-MailboxFolderPermission -Identity "$email:\Calendar" -User Default -AccessRights Reviewer


text:
Q: What is probabilistic inference? I am reading Chris Bishop's Pattern Recognition and Machine Learning textbook. I came across the term probabilistic inference several times. I have a couple of questions.

*

*Is probabilistic inference only applicable in a graphical modelling context?

*What's the distinction between traditional statistical inference (p-values, confidence intervals, Bayes factors etc.) and probabilistic inference?

*Is this a term that's specific to the CS community or is it widely used in the statistics community as well?

A: I will answer your questions from my experience in learning Probabilistic Graphical Models (PGM) in university and the way my PGM teacher defined probabilistic inference. Knowing the material of this class was based on [1], I assume you could find more precise answers in this book.
In answer to 2: Probabilistic inference is a type of statistical inference. From [2] and [3], statistical inference makes statistical propositions about a population, which includes point estimate, interval estimate, hypothesis rejection, clustering and classification. "Probabilistic inference" was introduced and roughly defined in the PGM context as any marginalisation task of a probability function, whether it is a marginal probability computation or finding the most probable outcome (for e.g. classification). It thus enters in the definition of statistical inference as making a proposition on the underlying probability distribution of the population.
To illustrate mathematically some marginalisation tasks in the context of PGM, let $\mathcal{X} = \{X_1, \ldots, X_n\}$ be a set of random variables. For a given bayesian network $(\mathscr{G}, \mathbb{P}_{\theta})$ or markovian network $(\mathscr{H}, \mathbb{P}_{\theta})$ with $\mathbb{P}_\theta$, then the following routines are considered probabilistic inferences:

*

*Computing a marginal or conditional probablity: For $\mathbf{E}, \mathbf{X} \subset \mathcal{X}$, we want to answer:
$$\mathbb{P}_\theta(\mathbf{X} = \mathbf{x} \mid \mathbf{E} =
   \mathbf{e}) = ~?.$$

*Most probable realization: For $\mathbf{E}, \mathbf{X} \subset \mathcal{X}$, we want to answer:
$${\rm arg}\min_{\!\!\!\!\!\!\!\!\mathbf{x}}\mathbb{P}_\theta(\mathbf{X} = \mathbf{x} \mid \mathbf{E} = \mathbf{e}) = ~?.$$
In answer to 1 and 3: It was the first time I had seen this terminology. The term does make sense, since you make inference on questions that are directly related to probabilities. I cannot answer whether it is used solely in CS or the PGM context.
[1] Koller, Daphne, and Nir Friedman. 2009. Probabilistic Graphical Models: Principles and Techniques. MIT Press.
[2] https://en.wikipedia.org/wiki/Statistical_inference
[3] https://encyclopediaofmath.org/wiki/Statistical_inference

A: Probabilistic inference uses probabilistic models, i.e. models that describe the statistical problems in terms of probability theory and probability distributions. While statistics use probability theory quite heavily, you cannot say that those two disciplines are the same thing (check the discussion in this thread). Notice that many statistical and machine learning methods do not explicitly use probability theory to define the problems, e.g. many clustering algorithms, or classification methods that work by minimizing some loss function etc. But the distinction is not that straightforward, take as example approximate Bayesian computation -- theoretically it is based on Bayesian (probabilistic!) inference, but it deals with cases where we do not have likelihood function, so instead of it we use a distance measure.


text:
Q: Question about aggregate function I'm an R user and I'm trying to rewrite some second hand SPSS code in R. Could someone give me a basic idea of what this code is achieving?:
AGGREG OUTFILE=*
/BREAK = subj task cond
/lat wind inwind primehit primefa =
mean(lat wind inwind primehit primefa)
/Ntrials = n.

Some background info is that subj, task, cond, lat, wind, inwind, primhit, and primefa are all variables in a dataset I'm using.

A: Here's what it would look like in R:
#subj, task, cond, lat, wind, inwind, primhit, primefa
#Creating some fake data for you to aggregate by
df<-data.frame(subj=c(rep(1,10),rep(2,10),rep(3,10)),
           task=rep(c(rep("A",5),rep("B",5)),3),
           cond=rep(rep(c(rep(T,3),rep(F,2)),2),3),
           lat=rnorm(30,100,20),wind=rnorm(30,10,10),inwind=rnorm(30,5,1),
           primhit=rnorm(30,5000,75),primefa=rnorm(30,200,30))
aggregate(df[,-c(1:3)],by=list(df$subj,df$task,df$cond),FUN="mean")

The (truncated) output should be similar to this (will vary due to rnorm):
   Group.1 Group.2 Group.3       lat      wind   inwind  primhit  primefa
1        1       A   FALSE 102.96070  5.637264 5.213994 5043.498 213.3119
2        2       A   FALSE 114.91123 11.161194 5.004008 5055.676 221.1172
....
11       2       B    TRUE  97.04035  6.450370 4.755714 5113.725 196.4184
12       3       B    TRUE 114.92453 12.888350 4.667839 5022.614 199.3125

Essentially, the SPSS code is doing the same thing where the /BREAK is the BY list and your third line is redefining the variables to take on the mean for the given subject, task, and condition.  The /Ntrials is giving the number of cases for the given group by.  You could do something like aggregate(df[,1)],by=list(df$subj,df$task,df$cond),FUN="length").
If you ever need to look something up for SPSS, I'd recommend ats.ucla.edu (http://www.ats.ucla.edu/stat/spss/seminars/spss_syntax08/default08_part2.htm).  They have some of the most comprehensive tutorials out there.


text:
Q: Анимация прозрачности Друзья, помогите пожалуйста. Надо, чтобы звезды мерцали - то есть рандомное значение opacity [0; 1), дойдя до 0.9, "гасло", а дойдя до 0.1 - снова росло.

const SF_SIZE = 1;
const SF_COUNT = 1000;
const WIND = 0.7;
const SPEED = 1.2;

var r = 255;
var g = 255;
var b = 0;

var canvas = document.getElementById("drawingCanvas"),
    context = canvas.getContext("2d"),
    sfArr = [];

context.lineWidth = SF_SIZE;

for(let i = 0; i < SF_COUNT; i++) {
  sfArr.push({
    x: randomInt(-canvas.width * WIND, canvas.width - 1),
    y: randomInt(0, canvas.height - 1),
    op: Math.random()
  });
}

let intrvl = setInterval(() => {
  for (let i = 0; i < SF_COUNT; i++) {
   if (sfArr[i].op < 0.1) {
      sfArr[i].op += 0.1;
    }

 else if (sfArr[i].op>0.9)
 { sfArr[i].op -= 0.1;}

  context.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ', ' + sfArr[i].op + ')';
  snowflake(sfArr[i].x, sfArr[i].y, sfArr[i].op);
  }
}, 200);

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function snowflake(squarePosition_x, squarePosition_y){
context.beginPath();
context.moveTo(squarePosition_x, squarePosition_y);
context.lineTo(squarePosition_x + context.lineWidth, squarePosition_y + context.lineWidth);
context.stroke();
}
#drawingCanvas {
  height: 80vh;
  width: 80vw;
  background-color: #000;
 }
<!-- Learn about this code on MDN: https://developer.mozilla.org/ru/docs/Web/API/CanvasRenderingContext2D/clearRect -->

<canvas id="drawingCanvas"></canvas>

Вот в этом условии что-то не так. Заранее спасибо
https://jsfiddle.net/Nata_Hamster/04pe3362/12/

A: Я бы сделал примерно так:

const SF_SIZE = 1;
const SF_COUNT = 1000;
const WIND = 0.7;
const SPEED = 1.2;

var r = 255;
var g = 255;
var b = 0;

var canvas = document.getElementById("drawingCanvas"),
    context = canvas.getContext("2d"),
    sfArr = [];

context.lineWidth = SF_SIZE;

for(let i = 0; i < SF_COUNT; i++) {
  sfArr.push({
    x: randomInt(-canvas.width * WIND, canvas.width - 1),
    y: randomInt(0, canvas.height - 1),
    op: Math.random(),
// Для каждой звезды по отдельности храним, тухнет она в данный момент или разгорается. Можно вынести этот флаг для всех звёзд оптом
    delta_opacity: 0.1
  });
}

let intrvl = setInterval(() => {

  // Если не очищать - то старые звездочки так и останутся отрисованными
  context.clearRect(0, 0, canvas.width, canvas.height);
  // И ничего мерцать не будет

  for (let i = 0; i < SF_COUNT; i++) {
    if (sfArr[i].op < 0.1 || sfArr[i].op > 0.9) {
      sfArr[i].delta_opacity = -sfArr[i].delta_opacity;
    }
    sfArr[i].op += sfArr[i].delta_opacity;

  context.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ', ' + sfArr[i].op + ')';
  snowflake(sfArr[i].x, sfArr[i].y, sfArr[i].op);
  }
}, 200);

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function snowflake(squarePosition_x, squarePosition_y){
context.beginPath();
context.moveTo(squarePosition_x, squarePosition_y);
context.lineTo(squarePosition_x + context.lineWidth, squarePosition_y + context.lineWidth);
context.stroke();
}
#drawingCanvas {
  height: 80vh;
  width: 80vw;
  background-color: #000;
 }
<!-- Learn about this code on MDN: https://developer.mozilla.org/ru/docs/Web/API/CanvasRenderingContext2D/clearRect -->

<canvas id="drawingCanvas"></canvas>


text:
Q: Vue: header doesn't get renewed after login/logout but localStorage is changed When I login using a form this happens:

*

*loggedIn value in localStorage is changed to "true"

*Router pushes to /home

*Header doesn't change and still shows Login/Signup buttons

I need it to be

*

*loggedIn value in localStorage is changed to "true"

*Router pushes to /home

*Header changes and a picture

Header.vue:

        <HeaderItem v-if="!isLoggedIn"
            class="pl-10" text = "Login" link="/login"/>
        <HeaderItem v-if="!isLoggedIn" class="pl-10"
                    text = "Signup" link="/signup"/>

          <UserHeader/>

export default {
  name: 'App',
  components: {HeaderItem, UserHeader},
  data() {
    return {
      homeLink: "/home"
    }
  },
  created: {
    isLoggedIn() {
      console.log(JSON.parse(localStorage.getItem("loggedIn")) === "true");

      if (localStorage.getItem("loggedIn") === "true")  {
        console.log("STORAGE LOGGED IN TRUE");
      }
      else  {
        console.log("STORAGE LOGGED IN FALSE");
      }

      return localStorage.getItem("loggedIn") === "true";
    }
  }
}

It only prints the correct message and changes header after I press Ctrl+Shift+R. But the localStorage has the correct loggedIn value right away. How do I fix it?
EDIT:
I also tried this:

        <HeaderItem v-if="!loggedIn"
            class="pl-10" text = "Login" link="/login"/>
        <HeaderItem v-if="!loggedIn" class="pl-10"
                    text = "Signup" link="/signup"/>

          <UserHeader/>

export default {
  name: 'App',
  components: {HeaderItem, UserHeader},
  data() {
    return {
      homeLink: "/home",
     // loggedIn: false
    }
  },
  computed: {
    loggedIn() {
      return localStorage.getItem("loggedIn") === "true";
    },
...

It has the same results: the header only changes after the page refresh (Ctrl+Shift+R).

A: The created is a lifecycle or hook of vue.js, inside it whatever functions/methods you define, is not available to run.
As in your case, you want to use as a variable, then use computed property.
Here is the fix version of your code:
computed: {
      isLoggedIn() {
        console.log(JSON.parse(localStorage.getItem("loggedIn")) === "true");

        if (localStorage.getItem("loggedIn") === "true")  {
          console.log("STORAGE LOGGED IN TRUE");
        }
        else  {
          console.log("STORAGE LOGGED IN FALSE");
        }

        return localStorage.getItem("loggedIn") === "true";
      }
    },

Updated:
If you want your functions to be reactive on the same component, then create a variable and set its value where you set the localStorage loggedIn value.
This is just an example code:
<template>

{{ isLoggedIn }}

</template>

Update 2 as per your situation:
After understanding your situation, here is the code, that will help you. I used the Bus Event in order to communicate between the component which might be far on the parent to access, such as App.vue.
event-bus.js
import Vue from 'vue';
const EventBus = new Vue();
export default EventBus;

LoginForm.vue
<template>

    <button type="submit" @click="onSignIn()">Login</button>

</template>

App.vue
<template>

    <router-view/>

</template>

Header.vue
<template>

{{ userLoggedIn }}

</template>


text:
Q: DataGridView custom cell should use normal ForeColor when selected I made some custom DataGridViewTextBoxCell instances. In most of them I set custom ForeColor values and that works fine. But when the SelectionMode is FullRowSelect it overrides my ForeColor values for this cell.
I tried to set it in the Draw event when the cell is selcted but it does not work.
My cell is definde as follows.
public class CustomCell : DataGridViewTextBoxCell
{
    protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context)
    {
        if (string.IsNullOrEmpty(value.ToString()))
        {
            return base.GetFormattedValue(value, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context);
        }

        if (value.ToString().Contains("test"))
        {
            cellStyle.ForeColor = Color.Blue;
        }
        return base.GetFormattedValue(value, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context);
    }
}

I don't want to change the selection mode but I want to show this cell with its right ForeColor but the selection BackColor.
How could the solution to this look like?

A: You can override Paint method of cell and set cellStyle.SelectionForeColor to the same color of ForeColor:
protected override void Paint(Graphics graphics, Rectangle clipBounds,
    Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState,
    object value, object formattedValue,
    string errorText, DataGridViewCellStyle cellStyle,
    DataGridViewAdvancedBorderStyle advancedBorderStyle,
    DataGridViewPaintParts paintParts)
{
    if (string.Format("{0}", formattedValue) == "something")
    {
        cellStyle.ForeColor = Color.Red;
        cellStyle.SelectionForeColor = cellStyle.ForeColor;
    }
    base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value,
        formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
}

Note: You can do the same using CellFormatting or CellPainting event of DataGridView without creating a custom cell.


text:
Q: iterative dom tree traversal I'm iterating little bits of jQuery for other people to use.
However, to get this to work I'm hoping to traverse up and then down the dom tree. This is so that the effects stay within the wrapping div, rather than affect the whole page. (I'm assuming multiple iterations of the same 'wrappingdivclass' and its content)

series name

image

image

image

image

athing

athing

athing

athing

and the jquery (lives in an outside file)
these iterates for hoverheading1-3 and hovercontent1-3
example:
//does not work
jQuery(document).ready(function() {
  jQuery(".hovercontent").show();
  jQuery(".hoverheading").hover(function()
  {
    $(this).parent().children(".hovercontent").show()
    $(this).parent().children(".hovercontent").siblings().hide();
  });
});
//      $(".hovercontent2").siblings().hide();
  });
});

example 2:
//also does not work
jQuery(document).ready(function() {
  jQuery(".hovercontent1").hide();
  //toggle the componenet with class msg_body
  jQuery(".hoverheading1").hover(function()
   {
    jQuery(this).closest(".hovercontent1").show();
    jQuery(this).closest(".hovercontent1").siblings().hide();
  });
});

A: You should be consistent.....either use the $ or use JQuery. You should avoid mixing them....
You might also benefit from using descendant selectors.
$(".wrappingdivclass > .hovercontents > .hovercontent2")
//Selects elements of class "hovercontent2" that have a parent element of "hovercontents", whose parent element is "wrappingdivclass"
$(".wrappingdivclass .hovercontent2")
//Selects elementss of class "hovercontent2" that are indirect descendants of "wrappingdivclass". Indirect means that it doesn't have to be direct child....it could be the grand-child, etc....


text:
Q: не могу установить куки в POST запросе Node.js не могу установить дефолтную куку express-session - connect.sid
Создал новые файлы: test.html и test.js
вот код:
test.js
var express = require("express");
var session = require("express-session");
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");

var app = express();
var port = 4000;

app.use(bodyParser());
app.use(cookieParser());

app.use(session({
     secret: "Secret word"
}));

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
 Content-Type, Accept");
    next();
});

app.use("/login",function (req,res) {
    var login = req.body.user;
    var pass = req.body.password;

    console.log(login);
    console.log("Work");
    res.send("Work");
});

app.listen(port);

а вот test.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<body>
<form action="http://localhost:4000/login" name="login" id="login">
    <input type="text" name="user">
    <input type="password" name="password"/>
    <input type="button" id="btn"  value="Send">
</form>
<script>
    var btn = document.getElementById("btn");
    $("#btn").click(function () {
        var data = $("#login").serializeArray();
            $.ajax({
                url:"http://localhost:4000/login",
                data: data,
                type: "POST",
                success: function (res) {
                    console.log(res);
                }
            })

    })

</script>

</body>
</html>

если вручную открыть новую вкладку, и перейти по такому пути http://localhost/4000/login тогда кука connect.sid создаться.
И еще хотел спросить по поводу сессий, что бы мне обяснили.
Я думаю должно быть так:
Вводиш логин и пароль, он отправляеться на сервер, там проверяеться есть ли такой юзер в БД, и подоходит ли пароль. Если да, то создать ключ(ид сессии).
И вернуть на клиент например объект user.auth = true , на клиенте проверить , если етот объект = true , то перенаправить например на страницу MyOffice.html.
А вот тут вопрос.
Как на странице MyOffice.html проверить авторизирован ли юзер? я думаю по куки connect.sid , так?
Извините за ошибки, и объясните мне пожалуйста :)

A: Я уже понял) я не предоставил статические файлы)
нужно  убрать :
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
 Content-Type, Accept");
    next();
});

и дописать
app.use(express.static(path.join(__dirname,"public")));
 app.get("/",function (req, res) {

    });

в папку "public" кинуть  html файлы, и заходить на сайт нужно под доменом сервера: http://localhost:4000/ , чтобы сервер вернул html страницу) а  я запускал через WebStorm и адрес был такой: http://localhost:63342/Tvolex/FirstApp/index.html .